@polderlabs/bizar 4.3.0 → 4.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/bizar-dash/src/server/opencode-sdk.mjs +72 -0
  2. package/bizar-dash/src/server/routes/background.mjs +92 -0
  3. package/bizar-dash/src/server/routes/chat.mjs +300 -123
  4. package/bizar-dash/src/server/routes/opencode-session-detail.mjs +26 -0
  5. package/bizar-dash/src/server/routes/tasks.mjs +59 -1
  6. package/bizar-dash/src/server/task-delegator.mjs +154 -8
  7. package/bizar-dash/src/server/tasks-store.mjs +50 -2
  8. package/bizar-dash/src/web/components/background/AttachButton.tsx +96 -0
  9. package/bizar-dash/src/web/components/background/TmuxAttachCard.tsx +122 -0
  10. package/bizar-dash/src/web/components/chat/AgentNode.tsx +127 -0
  11. package/bizar-dash/src/web/components/chat/AgentTree.tsx +80 -0
  12. package/bizar-dash/src/web/components/chat/ChatComposer.tsx +76 -0
  13. package/bizar-dash/src/web/components/chat/ChatInfoPanel.tsx +144 -0
  14. package/bizar-dash/src/web/components/chat/ChatRail.tsx +387 -0
  15. package/bizar-dash/src/web/components/chat/ChatThread.tsx +28 -7
  16. package/bizar-dash/src/web/components/chat/JumpToLatest.tsx +58 -0
  17. package/bizar-dash/src/web/components/chat/MessageBlock.tsx +260 -0
  18. package/bizar-dash/src/web/components/chat/SessionRowMenu.tsx +206 -0
  19. package/bizar-dash/src/web/components/chat/StreamingIndicator.tsx +33 -5
  20. package/bizar-dash/src/web/components/chat/_legacy.ts +30 -0
  21. package/bizar-dash/src/web/components/chat/index.ts +11 -0
  22. package/bizar-dash/src/web/components/chat/useChat.ts +345 -167
  23. package/bizar-dash/src/web/components/tasks/BacklogPanel.css +109 -0
  24. package/bizar-dash/src/web/components/tasks/BacklogPanel.tsx +209 -0
  25. package/bizar-dash/src/web/styles/chat.css +1536 -133
  26. package/bizar-dash/src/web/views/BackgroundAgents.tsx +3 -0
  27. package/bizar-dash/src/web/views/Chat.tsx +147 -57
  28. package/bizar-dash/src/web/views/Tasks.tsx +23 -1
  29. package/cli/bg.mjs +94 -71
  30. package/cli/bin.mjs +19 -7
  31. package/cli/service-controller.mjs +587 -0
  32. package/cli/service-controller.test.mjs +92 -0
  33. package/cli/service.mjs +162 -14
  34. package/config/agents/baldr.md +2 -0
  35. package/config/agents/browser-harness.md +2 -0
  36. package/config/agents/forseti.md +2 -0
  37. package/config/agents/frigg.md +2 -0
  38. package/config/agents/heimdall.md +2 -0
  39. package/config/agents/hermod.md +2 -0
  40. package/config/agents/mimir.md +2 -0
  41. package/config/agents/odin.md +2 -0
  42. package/config/agents/quick.md +2 -0
  43. package/config/agents/semble-search.md +2 -0
  44. package/config/agents/thor.md +2 -0
  45. package/config/agents/tyr.md +2 -0
  46. package/config/agents/vidarr.md +2 -0
  47. package/config/agents/vor.md +2 -0
  48. package/config/opencode.json.template +1 -0
  49. package/install.sh +448 -787
  50. package/package.json +1 -1
  51. package/packages/sdk/package.json +20 -0
  52. package/packages/sdk/src/client.ts +5 -0
  53. package/packages/sdk/src/errors.ts +11 -2
  54. package/packages/sdk/src/index.ts +19 -0
  55. package/packages/sdk/src/opencode-events.ts +134 -0
  56. package/packages/sdk/src/opencode-types.ts +66 -0
  57. package/packages/sdk/src/opencode.ts +335 -0
@@ -37,10 +37,11 @@
37
37
  * after the plugin is up.
38
38
  */
39
39
 
40
- import { tasksStore } from './tasks-store.mjs';
40
+ import { tasksStore, ALLOWED_TASK_STATUSES } from './tasks-store.mjs';
41
41
  import { agentsStore } from './agents-store.mjs';
42
42
  import { notificationsStore } from './notifications-store.mjs';
43
43
  import { backgroundStore } from './background-store.mjs';
44
+ import { projectsStore } from './projects-store.mjs';
44
45
  import { getActualBgLogPath } from './lib/path-safe.mjs';
45
46
  import { existsSync, readFileSync, writeFileSync, mkdirSync, readdirSync, statSync, renameSync } from 'node:fs';
46
47
  import { join } from 'node:path';
@@ -161,6 +162,12 @@ function autoTitleFromContent(body, fallback = true) {
161
162
  return (lastSpace > 20 ? cut.slice(0, lastSpace) : cut).trimEnd() + '…';
162
163
  }
163
164
 
165
+ // v3.22 — Shared helper: count running + pending bg instances.
166
+ async function runningBgCount() {
167
+ const list = await backgroundStore.list();
168
+ return list.filter((b) => b.status === 'running' || b.status === 'pending').length;
169
+ }
170
+
164
171
  export const taskDelegator = {
165
172
  /**
166
173
  * Submit a task to Odin. Odin analyzes, splits, and dispatches.
@@ -492,13 +499,8 @@ export const taskDelegator = {
492
499
  maxParallel = 6;
493
500
  }
494
501
 
495
- // Count currently running bg instances across all candidate dirs.
496
- // v3.5.4 (bug #5) — `list()` is now async because it merges
497
- // opencode-direct sessions via fetch.
498
- const runningInstances = (await backgroundStore.list()).filter(
499
- (b) => b.status === 'running' || b.status === 'pending',
500
- );
501
- const runningCount = runningInstances.length;
502
+ // v3.22 Reuse the shared runningBgCount helper.
503
+ const runningCount = await runningBgCount();
502
504
  const slotsAvailable = Math.max(0, maxParallel - runningCount);
503
505
 
504
506
  // v3.5.4 (bug: dispatch stuck) — Resolve the opencode serve child
@@ -770,6 +772,150 @@ export const taskDelegator = {
770
772
 
771
773
  /** For tests / introspection. */
772
774
  _BG_DIRS: BG_DIRS,
775
+
776
+ // v3.22 — Expose runningBgCount so callers can check dispatch capacity.
777
+ async runningBgCount() {
778
+ return runningBgCount();
779
+ },
780
+
781
+ /**
782
+ * Odin-pick: drain backlog into queued slots.
783
+ *
784
+ * Algorithm:
785
+ * 1. Determine active project. If none, return zeros + warning.
786
+ * 2. Read agents.maxParallel (default 6).
787
+ * 3. Compute running bg count via runningBgCount().
788
+ * 4. Compute slotsAvailable = max(0, maxParallel - runningCount). If 0, bail.
789
+ * 5. Load all non-archived tasks. Collect queued (parent or subtask, not yet
790
+ * dispatched) and backlog items as candidates.
791
+ * 6. Sort: priority high>normal>low; tiebreak createdAt ASC; backlog items
792
+ * sort after queued at the same priority (drain queue first).
793
+ * 7. Promote backlog items to fill candidate pool up to slotsAvailable.
794
+ * 8. Dispatch each candidate via dispatchToBackground.
795
+ *
796
+ * @param {object} ctx - { logLine?, broadcast? }
797
+ * @returns {{ promoted: number, dispatched: number, skipped: string[], warnings: string[] }}
798
+ */
799
+ async tickBacklog(ctx = {}) {
800
+ const logLine = ctx.logLine || (() => {});
801
+ const broadcast = ctx.broadcast || (() => {});
802
+ const warnings = [];
803
+ const skipped = [];
804
+
805
+ // 1. Active project or bail.
806
+ const active = projectsStore.active();
807
+ if (!active) {
808
+ warnings.push('no active project — tickBacklog skipped');
809
+ return { promoted: 0, dispatched: 0, skipped, warnings };
810
+ }
811
+ const projectId = active.id;
812
+ const projectRoot = active.path || process.cwd();
813
+
814
+ // 2. Read maxParallel.
815
+ const SETTINGS_FILE = join(HOME, '.config', 'bizar', 'settings.json');
816
+ let maxParallel = 6;
817
+ try {
818
+ if (existsSync(SETTINGS_FILE)) {
819
+ const raw = readFileSync(SETTINGS_FILE, 'utf8');
820
+ const settings = JSON.parse(raw);
821
+ maxParallel = settings?.agents?.maxParallel ?? 6;
822
+ }
823
+ } catch {
824
+ maxParallel = 6;
825
+ }
826
+
827
+ // 3 & 4. Running count and slots check.
828
+ const runningCount = await runningBgCount();
829
+ const slotsAvailable = Math.max(0, maxParallel - runningCount);
830
+ if (slotsAvailable === 0) {
831
+ skipped.push('no slots available');
832
+ return { promoted: 0, dispatched: 0, skipped, warnings };
833
+ }
834
+
835
+ // 5. Collect candidates.
836
+ const allTasks = tasksStore.loadTasks(projectId, { includeArchived: false });
837
+
838
+ const queuedCandidates = allTasks.filter((t) => {
839
+ if (t.status !== 'queued' || t.archived) return false;
840
+ // Parent tasks need subtasks; subtasks need a parent; both need to NOT already be dispatched.
841
+ const isSubtask = !!t.parent;
842
+ const hasSubtasks = Array.isArray(t.subtasks) && t.subtasks.length > 0;
843
+ if (isSubtask && !hasSubtasks) return false;
844
+ if (!isSubtask && hasSubtasks) return false;
845
+ const meta = t.metadata || {};
846
+ if (meta.bgInstanceId || meta.dispatchPending) return false;
847
+ return true;
848
+ });
849
+
850
+ const backlogItems = allTasks.filter((t) => t.status === 'backlog' && !t.archived);
851
+
852
+ // 6. Sort: priority ASC, createdAt ASC. Backlog items go after queued at same priority.
853
+ const priorityWeight = { high: 0, normal: 1, low: 2 };
854
+ const sortKey = (t, source) => {
855
+ const pw = priorityWeight[t.priority] ?? 1;
856
+ const src = source === 'backlog' ? 1 : 0;
857
+ return [pw, src, t.createdAt];
858
+ };
859
+ const allCandidates = [
860
+ ...queuedCandidates.map((t) => ({ task: t, source: 'queued' })),
861
+ ...backlogItems.map((t) => ({ task: t, source: 'backlog' })),
862
+ ];
863
+ allCandidates.sort((a, b) => {
864
+ const [pwA, srcA, ca] = sortKey(a.task, a.source);
865
+ const [pwB, srcB, cb] = sortKey(b.task, b.source);
866
+ if (pwA !== pwB) return pwA - pwB;
867
+ if (srcA !== srcB) return srcA - srcB;
868
+ return new Date(ca).getTime() - new Date(cb).getTime();
869
+ });
870
+
871
+ // 7. Promote backlog items to fill slots.
872
+ let promoted = 0;
873
+ const toPromote = allCandidates.filter((c) => c.source === 'backlog');
874
+ const toDispatch = [
875
+ ...allCandidates.filter((c) => c.source === 'queued'),
876
+ ...toPromote,
877
+ ].slice(0, slotsAvailable);
878
+
879
+ for (const c of toPromote) {
880
+ if (toDispatch.includes(c)) {
881
+ const updated = await tasksStore.promote(projectId, c.task.id);
882
+ if (updated) {
883
+ broadcast({ type: 'tasks:change', task: updated });
884
+ promoted++;
885
+ }
886
+ }
887
+ }
888
+
889
+ // 8. Dispatch each candidate.
890
+ let dispatched = 0;
891
+ for (const c of toDispatch) {
892
+ if (c.source === 'backlog') {
893
+ // Already promoted above.
894
+ continue;
895
+ }
896
+ const asSubtask = {
897
+ id: c.task.id,
898
+ title: c.task.title,
899
+ description: c.task.description,
900
+ assignee: c.task.assignee || 'tyr',
901
+ parent: c.task.parent || null,
902
+ };
903
+ const synthMain = { id: c.task.id };
904
+ try {
905
+ const result = await this.dispatchToBackground(synthMain, [asSubtask], { projectRoot, projectId, state: {}, broadcast }, broadcast);
906
+ if (result && Array.isArray(result.dispatched) && result.dispatched.length > 0) {
907
+ dispatched++;
908
+ } else if (result && result.warnings?.length) {
909
+ warnings.push(...result.warnings);
910
+ }
911
+ } catch (err) {
912
+ skipped.push(c.task.id);
913
+ warnings.push(`dispatch failed for ${c.task.id}: ${err.message}`);
914
+ }
915
+ }
916
+
917
+ return { promoted, dispatched, skipped, warnings };
918
+ },
773
919
  };
774
920
 
775
921
  // ── Public helpers for routes that need to walk bg state ─────────────
@@ -16,6 +16,10 @@ import { homedir } from 'node:os';
16
16
  import { randomBytes } from 'node:crypto';
17
17
  import { projectsStore } from './projects-store.mjs';
18
18
 
19
+ // v3.22 — Canonical status list. All status checks flow through this
20
+ // constant so a new status needs a change in only this one place.
21
+ export const ALLOWED_TASK_STATUSES = ['backlog', 'queued', 'doing', 'done', 'blocked', 'archived'];
22
+
19
23
  const HOME = homedir();
20
24
  const LEGACY_FILE = join(HOME, '.config', 'bizar', 'tasks.json');
21
25
 
@@ -154,7 +158,7 @@ export const tasksStore = {
154
158
  id: genId(),
155
159
  title: input.title,
156
160
  description: input.description || '',
157
- status: ['queued', 'doing', 'done', 'blocked', 'archived'].includes(input.status) ? input.status : 'queued',
161
+ status: ALLOWED_TASK_STATUSES.includes(input.status) ? input.status : 'queued',
158
162
  tags: Array.isArray(input.tags) ? input.tags : [],
159
163
  priority: ['low', 'normal', 'high'].includes(input.priority) ? input.priority : 'normal',
160
164
  assignee: input.assignee || null,
@@ -196,7 +200,7 @@ export const tasksStore = {
196
200
 
197
201
  if (typeof patch.title === 'string') task.title = patch.title.slice(0, 200);
198
202
  if (typeof patch.description === 'string') task.description = patch.description;
199
- if (['queued', 'doing', 'done', 'blocked', 'archived'].includes(patch.status)) {
203
+ if (ALLOWED_TASK_STATUSES.includes(patch.status)) {
200
204
  if (patch.status !== task.status) {
201
205
  appendActivity(task, 'status', { from: task.status, to: patch.status });
202
206
  }
@@ -505,4 +509,48 @@ export const tasksStore = {
505
509
  }
506
510
  return created;
507
511
  },
512
+
513
+ // v3.22 — Backlog helpers. Tasks in `backlog` are parked; Odin
514
+ // promotes them to `queued` via tickBacklog when slots are free.
515
+
516
+ /**
517
+ * List all backlog tasks for a project.
518
+ * @returns {Task[]}
519
+ */
520
+ listBacklog(projectId) {
521
+ return this.loadTasks(projectId).filter((t) => t.status === 'backlog' && !t.archived);
522
+ },
523
+
524
+ /**
525
+ * Promote a single backlog task to queued.
526
+ * @returns {Task | null}
527
+ */
528
+ async promote(projectId, id) {
529
+ return this.update(projectId, id, { status: 'queued' });
530
+ },
531
+
532
+ /**
533
+ * Demote a queued task back to backlog.
534
+ * @returns {Task | null}
535
+ */
536
+ async demote(projectId, id) {
537
+ return this.update(projectId, id, { status: 'backlog' });
538
+ },
539
+
540
+ /**
541
+ * Bulk-promote multiple backlog tasks to queued.
542
+ * @returns {{ affected: object[] }}
543
+ */
544
+ async promoteBatch(projectId, ids) {
545
+ const affected = [];
546
+ for (const id of ids) {
547
+ try {
548
+ const t = await this.update(projectId, id, { status: 'queued' });
549
+ affected.push({ id, ok: !!t });
550
+ } catch (err) {
551
+ affected.push({ id, ok: false, error: err.message });
552
+ }
553
+ }
554
+ return { affected };
555
+ },
508
556
  };
@@ -0,0 +1,96 @@
1
+ // src/components/background/AttachButton.tsx — small reusable tmux attach button
2
+ // v3.22.0
3
+ //
4
+ // Renders a primary button with two affordances:
5
+ // 1. "Run" — POST /api/background/:id/open-terminal to spawn the system
6
+ // terminal emulator with the tmux attach command.
7
+ // 2. "Copy" — ghost button to copy the command to clipboard.
8
+ //
9
+ // Safety: the "run" endpoint only accepts commands that start with
10
+ // `tmux attach -t ` (server-side whitelist). The `command` prop is
11
+ // only used for clipboard copy; the POST endpoint reconstructs the
12
+ // command server-side from the tmux session name.
13
+
14
+ import { useState } from 'react';
15
+ import { Copy, ExternalLink } from 'lucide-react';
16
+ import { Button } from '../Button';
17
+ import { useToast } from '../Toast';
18
+ import { api } from '../../lib/api';
19
+
20
+ type AttachButtonProps = {
21
+ /** The full `tmux attach -t <session>` command. Used for clipboard copy. */
22
+ command: string;
23
+ /** Button label. Defaults to "Attach". */
24
+ label?: string;
25
+ /** Instance id, sent in the POST body so the server validates the session. */
26
+ instanceId: string;
27
+ };
28
+
29
+ export function AttachButton({
30
+ command,
31
+ label = 'Attach',
32
+ instanceId,
33
+ }: AttachButtonProps) {
34
+ const toast = useToast();
35
+ const [opening, setOpening] = useState(false);
36
+
37
+ // Client-side pre-check: only allow tmux attach commands.
38
+ const valid = /^tmux attach -t /.test(command);
39
+
40
+ const copyCommand = async () => {
41
+ try {
42
+ await navigator.clipboard.writeText(command);
43
+ toast.success('Command copied');
44
+ } catch {
45
+ toast.error('Could not copy');
46
+ }
47
+ };
48
+
49
+ const runInTerminal = async () => {
50
+ if (!valid || !instanceId) return;
51
+ setOpening(true);
52
+ try {
53
+ const res = await api.post<{ ok: boolean; error?: string }>(
54
+ `/background/${encodeURIComponent(instanceId)}/open-terminal`,
55
+ { emulator: 'system' },
56
+ );
57
+ if (res.ok) {
58
+ toast.success('Opening terminal…');
59
+ } else {
60
+ toast.error(res.error || 'Failed to open terminal');
61
+ // Fallback: copy the command.
62
+ await copyCommand();
63
+ }
64
+ } catch (err) {
65
+ toast.error(`Failed: ${(err as Error).message}`);
66
+ // Fallback: copy on network error.
67
+ await copyCommand();
68
+ } finally {
69
+ setOpening(false);
70
+ }
71
+ };
72
+
73
+ return (
74
+ <div className="attach-button-group">
75
+ <Button
76
+ variant="primary"
77
+ size="sm"
78
+ onClick={runInTerminal}
79
+ loading={opening}
80
+ disabled={!valid}
81
+ title={valid ? 'Open in system terminal' : 'Invalid attach command'}
82
+ >
83
+ <ExternalLink size={14} /> {label}
84
+ </Button>
85
+ <Button
86
+ variant="ghost"
87
+ size="sm"
88
+ onClick={copyCommand}
89
+ disabled={!command}
90
+ title="Copy attach command"
91
+ >
92
+ <Copy size={14} />
93
+ </Button>
94
+ </div>
95
+ );
96
+ }
@@ -0,0 +1,122 @@
1
+ // src/components/background/TmuxAttachCard.tsx — per-instance tmux attach card
2
+ // v3.22.0
3
+ //
4
+ // Shows the tmux session name, a "Copy attach command" button, and
5
+ // an "Open in terminal" button that POSTs to /api/background/:id/open-terminal.
6
+ // When tmux is missing on the host, shows a friendly warning instead.
7
+
8
+ import { useState } from 'react';
9
+ import { Copy, Terminal, AlertTriangle } from 'lucide-react';
10
+ import { Button } from '../Button';
11
+ import { Card } from '../Card';
12
+ import { useToast } from '../Toast';
13
+ import { api } from '../../lib/api';
14
+ import type { BgInstance } from '../../lib/types';
15
+
16
+ type TmuxAttachCardProps = {
17
+ instance: BgInstance;
18
+ };
19
+
20
+ export function TmuxAttachCard({ instance }: TmuxAttachCardProps) {
21
+ const toast = useToast();
22
+ const [opening, setOpening] = useState(false);
23
+
24
+ const sessionName = instance.tmuxSession;
25
+ const attachCommand = sessionName ? `tmux attach -t ${sessionName}` : null;
26
+
27
+ const copyCommand = async () => {
28
+ if (!attachCommand) return;
29
+ try {
30
+ await navigator.clipboard.writeText(attachCommand);
31
+ toast.success('Attach command copied');
32
+ } catch {
33
+ toast.error('Could not copy to clipboard');
34
+ }
35
+ };
36
+
37
+ const openTerminal = async () => {
38
+ if (!instance.instanceId || !sessionName) return;
39
+ setOpening(true);
40
+ try {
41
+ const result = await api.post<{ ok: boolean; command: string; error?: string }>(
42
+ `/background/${encodeURIComponent(instance.instanceId)}/open-terminal`,
43
+ { emulator: 'system' },
44
+ );
45
+ if (result.ok) {
46
+ toast.success('Opening terminal…');
47
+ } else {
48
+ toast.error(result.error || 'Failed to open terminal');
49
+ // Fallback: copy the command so the user can paste it manually.
50
+ if (attachCommand) {
51
+ try {
52
+ await navigator.clipboard.writeText(attachCommand);
53
+ toast.success('Command copied to clipboard');
54
+ } catch { /* noop */ }
55
+ }
56
+ }
57
+ } catch (err) {
58
+ toast.error(`Failed: ${(err as Error).message}`);
59
+ // Fallback: copy command on network error.
60
+ if (attachCommand) {
61
+ try {
62
+ await navigator.clipboard.writeText(attachCommand);
63
+ toast.success('Command copied to clipboard');
64
+ } catch { /* noop */ }
65
+ }
66
+ } finally {
67
+ setOpening(false);
68
+ }
69
+ };
70
+
71
+ // Don't render anything if there's no tmux session to attach to.
72
+ if (!sessionName) {
73
+ return (
74
+ <Card variant="outlined" className="bg-tmux-card bg-tmux-card-warn">
75
+ <div className="bg-tmux-card-header">
76
+ <AlertTriangle size={14} />
77
+ <span>No tmux session</span>
78
+ </div>
79
+ <p className="bg-tmux-hint muted">
80
+ This instance does not have a tmux session attached.
81
+ Sessions are created automatically when a background agent starts.
82
+ </p>
83
+ </Card>
84
+ );
85
+ }
86
+
87
+ return (
88
+ <Card variant="outlined" className="bg-tmux-card">
89
+ <div className="bg-tmux-card-header">
90
+ <Terminal size={14} />
91
+ <span>tmux session</span>
92
+ {instance.tmuxActive !== false ? (
93
+ <span className="badge badge-success">live</span>
94
+ ) : (
95
+ <span className="badge badge-warning">inactive</span>
96
+ )}
97
+ </div>
98
+
99
+ <code className="mono bg-tmux-session-name">{sessionName}</code>
100
+
101
+ <p className="muted bg-tmux-hint">
102
+ Attach to the agent's tmux session from a terminal on the host
103
+ running the dashboard.
104
+ </p>
105
+
106
+ <div className="bg-tmux-card-actions">
107
+ <Button variant="ghost" size="sm" onClick={copyCommand} title="Copy attach command">
108
+ <Copy size={14} /> Copy
109
+ </Button>
110
+ <Button
111
+ variant="primary"
112
+ size="sm"
113
+ onClick={openTerminal}
114
+ loading={opening}
115
+ title="Open in system terminal"
116
+ >
117
+ <Terminal size={14} /> Open terminal
118
+ </Button>
119
+ </div>
120
+ </Card>
121
+ );
122
+ }
@@ -0,0 +1,127 @@
1
+ // src/components/chat/AgentNode.tsx — single card in the agent orchestration tree.
2
+ //
3
+ // Two modes:
4
+ // collapsible=true — header is a button with a chevron; toggles its
5
+ // own summary + children visibility.
6
+ // collapsible=false — header is a static div (no chevron / no toggle).
7
+ // Children render if present but cannot be
8
+ // collapsed by the user.
9
+ //
10
+ // FIX #1 (session-collapsed-by-default) is handled at the *parent*
11
+ // (SubAgentList / AgentTree) which decides whether to mount this
12
+ // node's children at all. This component is purely presentational.
13
+
14
+ import { useState } from 'react';
15
+
16
+ export type AgentStatus = 'idle' | 'streaming' | 'done' | 'blocked' | 'awaiting';
17
+
18
+ export interface AgentTreeNode {
19
+ id: string;
20
+ name: string;
21
+ role?: string;
22
+ status: AgentStatus;
23
+ summary?: string;
24
+ children?: AgentTreeNode[];
25
+ }
26
+
27
+ interface Props {
28
+ node: AgentTreeNode;
29
+ depth?: number;
30
+ collapsible?: boolean;
31
+ isLast?: boolean;
32
+ /** Controlled open state — used by SubAgentList so the parent rail
33
+ * row's tree-chevron is the single source of truth for collapse. */
34
+ open?: boolean;
35
+ onToggle?: (next: boolean) => void;
36
+ }
37
+
38
+ export function AgentNode({
39
+ node,
40
+ depth = 0,
41
+ collapsible = false,
42
+ isLast = true,
43
+ open: controlledOpen,
44
+ onToggle,
45
+ }: Props) {
46
+ const [internalOpen, setInternalOpen] = useState<boolean>(collapsible);
47
+ const isControlled = controlledOpen !== undefined;
48
+ const open = isControlled ? controlledOpen : internalOpen;
49
+ const setOpen = (next: boolean) => {
50
+ if (!isControlled) setInternalOpen(next);
51
+ onToggle?.(next);
52
+ };
53
+
54
+ const hasChildren = (node.children?.length ?? 0) > 0;
55
+
56
+ const headContent = (
57
+ <>
58
+ {collapsible && (
59
+ <span
60
+ className={`agent-node-chevron ${open ? 'open' : ''}`}
61
+ aria-hidden
62
+ >
63
+
64
+ </span>
65
+ )}
66
+ <span
67
+ className={`agent-node-dot status-${node.status}`}
68
+ aria-hidden
69
+ />
70
+ <span className="agent-node-name">{node.name}</span>
71
+ {node.role && <span className="agent-node-role chat-mono">{node.role}</span>}
72
+ <span className={`agent-node-pill status-${node.status}`}>{node.status}</span>
73
+ </>
74
+ );
75
+
76
+ return (
77
+ <div
78
+ className={[
79
+ 'agent-node',
80
+ `depth-${depth}`,
81
+ `status-${node.status}`,
82
+ open ? 'open' : 'closed',
83
+ isLast ? 'last' : '',
84
+ ]
85
+ .filter(Boolean)
86
+ .join(' ')}
87
+ >
88
+ {collapsible ? (
89
+ <button
90
+ type="button"
91
+ className={`agent-node-head status-${node.status} collapsible`}
92
+ onClick={(e) => {
93
+ e.stopPropagation();
94
+ setOpen(!open);
95
+ }}
96
+ aria-expanded={open}
97
+ >
98
+ {headContent}
99
+ </button>
100
+ ) : (
101
+ <div className={`agent-node-head status-${node.status}`}>
102
+ {headContent}
103
+ </div>
104
+ )}
105
+ {open && (
106
+ <>
107
+ {node.summary && (
108
+ <div className="agent-node-summary">{node.summary}</div>
109
+ )}
110
+ {hasChildren && (
111
+ <div className="agent-node-children">
112
+ {node.children!.map((child, i) => (
113
+ <AgentNode
114
+ key={child.id}
115
+ node={child}
116
+ depth={depth + 1}
117
+ collapsible={false}
118
+ isLast={i === node.children!.length - 1}
119
+ />
120
+ ))}
121
+ </div>
122
+ )}
123
+ </>
124
+ )}
125
+ </div>
126
+ );
127
+ }
@@ -0,0 +1,80 @@
1
+ // src/components/chat/AgentTree.tsx — vertical chain of session cards connected by
2
+ // backbone+L-stub connectors. Two modes:
3
+ //
4
+ // full tree (variant="full") — renders the root card and all its children.
5
+ // Used inside the thread head when the active session has sub-agents.
6
+ //
7
+ // children-only (variant="rail" via SubAgentList) — renders only the children
8
+ // of the root; the rail row above already shows the root card, so
9
+ // re-rendering it would duplicate. Children hang directly off the
10
+ // rail row via standard backbone + L-stub connectors.
11
+ //
12
+ // FIX #1 — the parent (ChatRail) passes `open=false` by default for a
13
+ // freshly-clicked session so the tree is collapsed on first click; the
14
+ // user can open it via the chevron in the row.
15
+
16
+ import { Fragment } from 'react';
17
+ import { AgentNode, type AgentTreeNode } from './AgentNode';
18
+
19
+ interface FullTreeProps {
20
+ tree: { root: AgentTreeNode };
21
+ variant?: 'full';
22
+ open?: boolean;
23
+ }
24
+
25
+ interface ChildrenOnlyProps {
26
+ children: AgentTreeNode[];
27
+ variant: 'rail' | 'thread';
28
+ open?: boolean;
29
+ }
30
+
31
+ function isFullTree(props: FullTreeProps | ChildrenOnlyProps): props is FullTreeProps {
32
+ return (props as FullTreeProps).tree !== undefined;
33
+ }
34
+
35
+ export function AgentTree(props: FullTreeProps | ChildrenOnlyProps) {
36
+ const open = props.open ?? true;
37
+
38
+ if (isFullTree(props)) {
39
+ return (
40
+ <div className={`agent-tree variant-${props.variant ?? 'full'}`}>
41
+ <AgentNode node={props.tree.root} depth={0} open={open} />
42
+ </div>
43
+ );
44
+ }
45
+
46
+ // Children-only path (used by SubAgentList hanging off the rail row).
47
+ const list = props.children ?? [];
48
+ return (
49
+ <div className={`agent-tree variant-${props.variant} agent-tree-children-only`}>
50
+ <div className="agent-tree-children-body">
51
+ {list.map((child, i) => (
52
+ <Fragment key={child.id}>
53
+ <AgentNode
54
+ node={child}
55
+ depth={0}
56
+ collapsible={false}
57
+ open={open}
58
+ isLast={i === list.length - 1}
59
+ />
60
+ </Fragment>
61
+ ))}
62
+ </div>
63
+ </div>
64
+ );
65
+ }
66
+
67
+ /* ── SubAgentList — convenience wrapper used by the ChatRail to render
68
+ the children of a session's tree directly under the active row. ── */
69
+ export function SubAgentList({
70
+ children,
71
+ variant = 'rail',
72
+ open = true,
73
+ }: {
74
+ children: AgentTreeNode[];
75
+ variant?: 'rail' | 'thread';
76
+ open?: boolean;
77
+ }) {
78
+ if (!open) return null;
79
+ return <AgentTree variant={variant} open={open} children={children} />;
80
+ }