File size: 16,695 Bytes
3193174
 
 
 
 
 
 
 
 
 
 
 
5cdde73
3193174
 
 
 
 
 
 
 
 
 
 
 
 
5cdde73
3193174
 
5cdde73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81f5c1c
5cdde73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81f5c1c
 
5cdde73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3193174
 
 
 
 
 
 
 
 
 
 
 
 
 
5cdde73
3193174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5cdde73
3193174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5cdde73
 
 
 
 
3193174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5cdde73
 
 
 
 
3193174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5cdde73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3193174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
import { useState } from "react";
import {
  CheckCircle2,
  Layout,
  Save,
  FolderOpen,
  FilePlus,
  Download,
  Upload,
  PlayCircle,
  Flag,
  Trash2,
  BookTemplate,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Separator } from "@/components/ui/separator";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
} from "@/components/ui/dialog";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Badge } from "@/components/ui/badge";
import { useGraphStore, type AgentNodeData, type GraphTemplate } from "@/stores/graphStore";
import type { GraphListItem } from "@/types/graph";

// ── Predefined graph templates ──────────────────────────────────────────
const GRAPH_TEMPLATES: GraphTemplate[] = [
  {
    name: "Linear Pipeline",
    description: "Sequential: Researcher -> Writer -> Reviewer",
    agents: [
      { agent_id: "researcher", display_name: "Researcher", persona: "Expert researcher", description: "Gathers information", tools: ["web_search"] },
      { agent_id: "writer", display_name: "Writer", persona: "Technical writer", description: "Writes content", tools: [] },
      { agent_id: "reviewer", display_name: "Reviewer", persona: "Quality reviewer", description: "Reviews output", tools: [] },
    ],
    edges: [
      { source: "researcher", target: "writer", weight: 1.0, condition: null },
      { source: "writer", target: "reviewer", weight: 1.0, condition: null },
    ],
    start_node: "researcher",
    end_node: "reviewer",
  },
  {
    name: "Fan-Out / Fan-In",
    description: "Planner fans out to parallel workers, Aggregator collects results",
    agents: [
      { agent_id: "planner", display_name: "Planner", persona: "Task planner", description: "Breaks task into subtasks", tools: [] },
      { agent_id: "worker_a", display_name: "Worker A", persona: "Specialist A", description: "Handles subtask A", tools: [] },
      { agent_id: "worker_b", display_name: "Worker B", persona: "Specialist B", description: "Handles subtask B", tools: [] },
      { agent_id: "aggregator", display_name: "Aggregator", persona: "Synthesizer", description: "Combines results", tools: [] },
    ],
    edges: [
      { source: "planner", target: "worker_a", weight: 1.0, condition: null },
      { source: "planner", target: "worker_b", weight: 1.0, condition: null },
      { source: "worker_a", target: "aggregator", weight: 1.0, condition: null },
      { source: "worker_b", target: "aggregator", weight: 1.0, condition: null },
    ],
    start_node: "planner",
    end_node: "aggregator",
  },
  {
    name: "Conditional Branching",
    description: "Writer outputs, conditional edges route to Editor or Fixer based on response",
    agents: [
      { agent_id: "writer", display_name: "Writer", persona: "Content writer", description: "Generates draft", tools: [] },
      { agent_id: "editor", display_name: "Editor", persona: "Editor", description: "Polishes good drafts", tools: [] },
      { agent_id: "fixer", display_name: "Fixer", persona: "Error corrector", description: "Fixes problematic drafts", tools: [] },
      { agent_id: "publisher", display_name: "Publisher", persona: "Publisher", description: "Publishes final version", tools: [] },
    ],
    edges: [
      { source: "writer", target: "editor", weight: 0.9, condition: "contains:APPROVED" },
      { source: "writer", target: "fixer", weight: 0.7, condition: "source_failed" },
      { source: "editor", target: "publisher", weight: 1.0, condition: null },
      { source: "fixer", target: "publisher", weight: 1.0, condition: null },
    ],
    start_node: "writer",
    end_node: "publisher",
  },
  {
    name: "Review Loop",
    description: "Coder writes code, Reviewer checks quality; conditional edges route back or forward",
    agents: [
      { agent_id: "planner", display_name: "Planner", persona: "Architect", description: "Plans the approach", tools: [] },
      { agent_id: "coder", display_name: "Coder", persona: "Software developer", description: "Writes code", tools: ["code_interpreter"] },
      { agent_id: "reviewer", display_name: "Reviewer", persona: "Code reviewer", description: "Reviews code quality", tools: [] },
      { agent_id: "finalizer", display_name: "Finalizer", persona: "Integrator", description: "Delivers final result", tools: [] },
    ],
    edges: [
      { source: "planner", target: "coder", weight: 1.0, condition: null },
      { source: "coder", target: "reviewer", weight: 1.0, condition: null },
      { source: "reviewer", target: "finalizer", weight: 0.9, condition: "contains:LGTM" },
      { source: "reviewer", target: "coder", weight: 0.5, condition: "contains:REVISE" },
    ],
    start_node: "planner",
    end_node: "finalizer",
  },
  {
    name: "Diamond with Weights",
    description: "Dispatcher -> two parallel paths with different weights -> Merger",
    agents: [
      { agent_id: "start", display_name: "Dispatcher", persona: "Task dispatcher", description: "Dispatches task", tools: [] },
      { agent_id: "fast_path", display_name: "Fast Path", persona: "Quick processor", description: "Fast but less thorough", tools: [] },
      { agent_id: "deep_path", display_name: "Deep Path", persona: "Deep analyzer", description: "Slow but thorough", tools: ["web_search"] },
      { agent_id: "merger", display_name: "Merger", persona: "Result merger", description: "Merges results", tools: [] },
    ],
    edges: [
      { source: "start", target: "fast_path", weight: 0.6, condition: null },
      { source: "start", target: "deep_path", weight: 1.0, condition: null },
      { source: "fast_path", target: "merger", weight: 0.6, condition: null },
      { source: "deep_path", target: "merger", weight: 1.0, condition: null },
    ],
    start_node: "start",
    end_node: "merger",
  },
];

interface GraphToolbarProps {
  onValidate: () => void;
  onRun: () => void;
  isRunning: boolean;
}

export function GraphToolbar({ onValidate, onRun, isRunning }: GraphToolbarProps) {
  const {
    graphName,
    setGraphName,
    autoLayout,
    saveGraph,
    loadGraph,
    newGraph,
    loadTemplate,
    fetchSavedGraphs,
    savedGraphs,
    nodes,
    validationErrors,
    validationWarnings,
    setStartNode,
    setEndNode,
    startNode,
    endNode,
    toGraphRequest,
  } = useGraphStore();

  const [saving, setSaving] = useState(false);
  const [loadOpen, setLoadOpen] = useState(false);
  const [startEndOpen, setStartEndOpen] = useState(false);
  const [templatesOpen, setTemplatesOpen] = useState(false);

  const handleSave = async () => {
    setSaving(true);
    try {
      await saveGraph();
    } catch {
      // handle error
    } finally {
      setSaving(false);
    }
  };

  const handleLoadOpen = async () => {
    await fetchSavedGraphs();
    setLoadOpen(true);
  };

  const handleLoad = async (graph: GraphListItem) => {
    await loadGraph(graph.graph_id);
    setLoadOpen(false);
  };

  const handleExport = () => {
    const data = toGraphRequest();
    const blob = new Blob([JSON.stringify(data, null, 2)], { type: "application/json" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `${graphName.replace(/\s+/g, "-").toLowerCase()}.json`;
    a.click();
    URL.revokeObjectURL(url);
  };

  const handleImport = () => {
    const input = document.createElement("input");
    input.type = "file";
    input.accept = ".json";
    input.onchange = async (e) => {
      const file = (e.target as HTMLInputElement).files?.[0];
      if (!file) return;
      const text = await file.text();
      try {
        const data = JSON.parse(text);
        if (data.name) setGraphName(data.name);
      } catch {
        // invalid JSON
      }
    };
    input.click();
  };

  const handleLoadTemplate = (template: GraphTemplate) => {
    loadTemplate(template);
    setTemplatesOpen(false);
  };

  return (
    <>
      <div className="flex items-center gap-2 border-b bg-card px-3 py-2">
        <Input
          value={graphName}
          onChange={(e) => setGraphName(e.target.value)}
          className="h-8 w-48 text-sm font-medium"
        />

        <Separator orientation="vertical" className="h-6" />

        <Button variant="outline" size="sm" onClick={onValidate} className="gap-1">
          <CheckCircle2 className="h-3.5 w-3.5" />
          Validate
        </Button>

        {validationErrors.length > 0 && (
          <Badge variant="destructive" className="text-xs">
            {validationErrors.length} error{validationErrors.length > 1 ? "s" : ""}
          </Badge>
        )}
        {validationWarnings.length > 0 && (
          <Badge variant="secondary" className="text-xs">
            {validationWarnings.length} warning{validationWarnings.length > 1 ? "s" : ""}
          </Badge>
        )}

        <Button variant="outline" size="sm" onClick={autoLayout} className="gap-1">
          <Layout className="h-3.5 w-3.5" />
          Auto Layout
        </Button>

        <Button variant="outline" size="sm" onClick={() => setStartEndOpen(true)} className="gap-1">
          <Flag className="h-3.5 w-3.5" />
          Start/End
        </Button>

        <Separator orientation="vertical" className="h-6" />

        <Button variant="outline" size="sm" onClick={handleSave} disabled={saving} className="gap-1">
          <Save className="h-3.5 w-3.5" />
          {saving ? "Saving..." : "Save"}
        </Button>

        <Button variant="outline" size="sm" onClick={handleLoadOpen} className="gap-1">
          <FolderOpen className="h-3.5 w-3.5" />
          Load
        </Button>

        <Button variant="outline" size="sm" onClick={() => setTemplatesOpen(true)} className="gap-1">
          <BookTemplate className="h-3.5 w-3.5" />
          Templates
        </Button>

        <Button variant="outline" size="sm" onClick={newGraph} className="gap-1">
          <FilePlus className="h-3.5 w-3.5" />
          New
        </Button>

        <Button
          variant="outline"
          size="sm"
          onClick={() => { if (nodes.length === 0 || window.confirm("Clear all nodes and edges?")) newGraph(); }}
          disabled={nodes.length === 0}
          className="gap-1 text-destructive hover:text-destructive"
        >
          <Trash2 className="h-3.5 w-3.5" />
          Clear
        </Button>

        <Button variant="ghost" size="icon" className="h-8 w-8" onClick={handleExport}>
          <Download className="h-3.5 w-3.5" />
        </Button>

        <Button variant="ghost" size="icon" className="h-8 w-8" onClick={handleImport}>
          <Upload className="h-3.5 w-3.5" />
        </Button>

        <div className="flex-1" />

        <Button onClick={onRun} disabled={isRunning || nodes.length === 0} className="gap-1">
          <PlayCircle className="h-4 w-4" />
          {isRunning ? "Running..." : "Execute"}
        </Button>
      </div>

      {/* Load dialog */}
      <Dialog open={loadOpen} onOpenChange={setLoadOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Load Workflow</DialogTitle>
            <DialogDescription>Select a saved workflow to load.</DialogDescription>
          </DialogHeader>
          <ScrollArea className="max-h-[400px]">
            {savedGraphs.length === 0 ? (
              <p className="p-4 text-center text-sm text-muted-foreground">No saved workflows.</p>
            ) : (
              <div className="space-y-2 p-1">
                {savedGraphs.map((g) => (
                  <div
                    key={g.graph_id}
                    className="flex items-center justify-between rounded-md border p-3 cursor-pointer hover:bg-accent"
                    onClick={() => handleLoad(g)}
                  >
                    <div>
                      <div className="font-medium text-sm">{g.name}</div>
                      <div className="text-xs text-muted-foreground">
                        {g.agent_count} agents, {g.edge_count} edges
                      </div>
                    </div>
                    <div className="text-xs text-muted-foreground">
                      {g.updated_at ? new Date(g.updated_at).toLocaleDateString() : ""}
                    </div>
                  </div>
                ))}
              </div>
            )}
          </ScrollArea>
        </DialogContent>
      </Dialog>

      {/* Templates dialog */}
      <Dialog open={templatesOpen} onOpenChange={setTemplatesOpen}>
        <DialogContent className="sm:max-w-[520px]">
          <DialogHeader>
            <DialogTitle>Graph Templates</DialogTitle>
            <DialogDescription>Start from a predefined topology with agents and conditional edges.</DialogDescription>
          </DialogHeader>
          <ScrollArea className="max-h-[400px]">
            <div className="space-y-2 p-1">
              {GRAPH_TEMPLATES.map((t) => (
                <div
                  key={t.name}
                  className="rounded-md border p-3 cursor-pointer hover:bg-accent transition-colors"
                  onClick={() => handleLoadTemplate(t)}
                >
                  <div className="font-medium text-sm">{t.name}</div>
                  <div className="text-xs text-muted-foreground mt-0.5">{t.description}</div>
                  <div className="flex gap-2 mt-1.5">
                    <Badge variant="secondary" className="text-[10px]">
                      {t.agents.length} agents
                    </Badge>
                    <Badge variant="secondary" className="text-[10px]">
                      {t.edges.length} edges
                    </Badge>
                    {t.edges.some((e) => e.condition) && (
                      <Badge variant="outline" className="text-[10px] text-indigo-600">
                        conditional
                      </Badge>
                    )}
                    {t.edges.some((e) => e.weight < 1.0) && (
                      <Badge variant="outline" className="text-[10px] text-amber-600">
                        weighted
                      </Badge>
                    )}
                  </div>
                </div>
              ))}
            </div>
          </ScrollArea>
        </DialogContent>
      </Dialog>

      {/* Start/End node dialog */}
      <Dialog open={startEndOpen} onOpenChange={setStartEndOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Set Start/End Nodes</DialogTitle>
            <DialogDescription>
              Select which agent starts and ends the workflow execution.
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div className="space-y-2">
              <label className="text-sm font-medium">Start Node</label>
              <div className="space-y-1">
                {nodes.map((n) => (
                  <div
                    key={n.id}
                    className={`flex items-center gap-2 rounded-md border p-2 cursor-pointer transition-colors ${
                      startNode === n.id ? "border-green-500 bg-green-50 dark:bg-green-950" : "hover:bg-accent"
                    }`}
                    onClick={() => setStartNode(startNode === n.id ? null : n.id)}
                  >
                    <span className="text-sm">{(n.data as unknown as AgentNodeData).displayName}</span>
                    {startNode === n.id && <Badge className="ml-auto text-xs">START</Badge>}
                  </div>
                ))}
              </div>
            </div>
            <div className="space-y-2">
              <label className="text-sm font-medium">End Node</label>
              <div className="space-y-1">
                {nodes.map((n) => (
                  <div
                    key={n.id}
                    className={`flex items-center gap-2 rounded-md border p-2 cursor-pointer transition-colors ${
                      endNode === n.id ? "border-orange-500 bg-orange-50 dark:bg-orange-950" : "hover:bg-accent"
                    }`}
                    onClick={() => setEndNode(endNode === n.id ? null : n.id)}
                  >
                    <span className="text-sm">{(n.data as unknown as AgentNodeData).displayName}</span>
                    {endNode === n.id && <Badge className="ml-auto text-xs">END</Badge>}
                  </div>
                ))}
              </div>
            </div>
          </div>
        </DialogContent>
      </Dialog>
    </>
  );
}