@bridgebrew/sessions 0.0.0-stage → 0.0.8

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 (44) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +43 -2
  3. package/answers.ts +167 -0
  4. package/browser/branch-actions.tsx +166 -0
  5. package/browser/changes.tsx +415 -0
  6. package/browser/children.tsx +650 -0
  7. package/browser/conversation.tsx +2381 -0
  8. package/browser/decision-questions.tsx +191 -0
  9. package/browser/elapsed.tsx +44 -0
  10. package/browser/gallery.tsx +218 -0
  11. package/browser/index.tsx +3434 -0
  12. package/browser/media-origins.tsx +38 -0
  13. package/browser/mobile.tsx +663 -0
  14. package/browser/open-link.tsx +30 -0
  15. package/browser/pull-request.tsx +116 -0
  16. package/browser/questions.tsx +156 -0
  17. package/browser/session-scheduled.tsx +203 -0
  18. package/browser/subagent-view.tsx +136 -0
  19. package/browser/subagents.tsx +339 -0
  20. package/browser/tabs.tsx +228 -0
  21. package/browser/tsconfig.json +15 -0
  22. package/browser/views/view.tsx +1064 -0
  23. package/browser/views.tsx +166 -0
  24. package/contract.ts +287 -0
  25. package/delegations.ts +1975 -0
  26. package/diff.ts +88 -0
  27. package/docs/en/images.mdx +51 -0
  28. package/docs/en/index.mdx +22 -0
  29. package/docs/en/meta.json +4 -0
  30. package/docs/en/organize-sessions.mdx +53 -0
  31. package/docs/en/start-a-session.mdx +63 -0
  32. package/docs/meta.json +4 -0
  33. package/git.ts +223 -0
  34. package/listing.ts +382 -0
  35. package/package.json +1023 -4
  36. package/peers.ts +677 -0
  37. package/pull-request-watch.ts +282 -0
  38. package/pull-requests.ts +606 -0
  39. package/server.ts +5920 -0
  40. package/text.ts +19 -0
  41. package/tsconfig.json +3 -0
  42. package/viewer-activity.ts +57 -0
  43. package/views/examples.ts +153 -0
  44. package/views/library.ts +1116 -0
@@ -0,0 +1,30 @@
1
+ import type { Context } from 'cordis';
2
+
3
+ /** What a page did with an agent's page (`bridge_link`'s `show`, research-069): shown (`visible`: a window showed it
4
+ * already, `replaced`, `opened` beside), or why not, for the log (the agent gives the link without explaining). */
5
+ export type Shown =
6
+ | { shown: 'visible' | 'replaced' | 'opened'; reason?: undefined }
7
+ | { shown: false; reason: string };
8
+
9
+ /** An agent's page shown from the page showing its session in `viewport`, as the window manager decides
10
+ * (`shell.present`): only where the session is shown (not `inert`, not hidden, its browser tab not in the background);
11
+ * `turn`, the agent's, one window for all of it. */
12
+ export const showLink = (
13
+ shell: Context['shell'],
14
+ path: string,
15
+ viewport: Element | null | undefined,
16
+ turn?: string,
17
+ ): Shown => {
18
+ if (
19
+ !viewport?.isConnected ||
20
+ document.hidden ||
21
+ viewport.closest('[inert], [aria-hidden="true"]')
22
+ )
23
+ return { shown: false, reason: 'not-shown' };
24
+ const view = shell.viewAt(path);
25
+ if (!view?.screen) return { shown: false, reason: 'not-a-screen' };
26
+ const from = viewport.closest('[data-window]')?.getAttribute('data-window');
27
+ if (!from) return { shown: false, reason: 'not-shown' };
28
+ const done = shell.present(view, from, turn);
29
+ return done.shown ? { shown: done.shown } : { shown: false, reason: done.reason };
30
+ };
@@ -0,0 +1,116 @@
1
+ // A session's pull request in its header (research-086): its state's icon and number (as the Branches screen's pill),
2
+ // its checks' mark (a conflict before them), an eye while watched; its menu opens it on GitHub, watches it or stops,
3
+ // unlinks it. The page asks Sessions to read it again as it opens the session (`refresh`), and lists again at each
4
+ // change Sessions tells (`queue` on its watch stream).
5
+ import * as React from 'react';
6
+ import {
7
+ Button,
8
+ DropdownMenu,
9
+ DropdownMenuContent,
10
+ DropdownMenuItem,
11
+ DropdownMenuTrigger,
12
+ Icon,
13
+ StatusIcon,
14
+ } from '@bridge/ui';
15
+
16
+ /** A session's pull request as its listing gives it (`pull-requests.ts`). */
17
+ export interface SessionPullRequest {
18
+ repository: string;
19
+ number: number;
20
+ url: string;
21
+ title?: string;
22
+ headBranch?: string;
23
+ by: 'branch' | 'agent' | 'user';
24
+ state?: 'draft' | 'open' | 'merged' | 'closed';
25
+ checks?: 'none' | 'pending' | 'passed' | 'failed';
26
+ conflicting?: true;
27
+ watching?: true;
28
+ }
29
+
30
+ /** A pull request's state as GitHub shows it: its icon, colour and word (the Branches screen's). */
31
+ const LOOK = {
32
+ open: { icon: 'git-pull-request-arrow', className: 'text-success', label: 'Open' },
33
+ draft: { icon: 'git-pull-request-draft', className: 'text-muted', label: 'Draft' },
34
+ merged: { icon: 'git-merge', className: 'text-merged', label: 'Merged' },
35
+ closed: { icon: 'git-pull-request-closed', className: 'text-destructive', label: 'Closed' },
36
+ } as const;
37
+
38
+ /** The mark beside the number: a conflict, else the checks' sum (none: no mark). */
39
+ const markOf = (pr: SessionPullRequest) =>
40
+ pr.state === 'merged' || pr.state === 'closed'
41
+ ? undefined
42
+ : pr.conflicting
43
+ ? ({ status: 'warning', label: 'Conflicts with its base branch' } as const)
44
+ : pr.checks === 'failed'
45
+ ? ({ status: 'error', label: 'Checks failed' } as const)
46
+ : pr.checks === 'passed'
47
+ ? ({ status: 'resolved', label: 'Checks passed' } as const)
48
+ : pr.checks === 'pending'
49
+ ? ({ status: 'in-progress', label: 'Checks running' } as const)
50
+ : undefined;
51
+
52
+ /** The pill; `act` posts to Sessions' pull request routes (`watch`, `unwatch`, `unlink`). */
53
+ export function PullRequestPill({
54
+ pullRequest: pr,
55
+ act,
56
+ }: {
57
+ pullRequest: SessionPullRequest;
58
+ act: (action: 'watch' | 'unwatch' | 'unlink') => void;
59
+ }) {
60
+ const look = LOOK[pr.state ?? 'open'];
61
+ const mark = markOf(pr);
62
+ const label = [
63
+ `Pull request #${pr.number}`,
64
+ look.label,
65
+ ...(mark ? [mark.label] : []),
66
+ ...(pr.watching ? ['Watched: Bridge wakes the agent on news'] : []),
67
+ ].join(' · ');
68
+ const done = pr.state === 'merged' || pr.state === 'closed';
69
+ return (
70
+ <DropdownMenu>
71
+ <DropdownMenuTrigger
72
+ render={
73
+ <Button
74
+ size="sm"
75
+ // Not `property`: it mutes every icon inside, and the icon carries the state's colour.
76
+ variant="outline"
77
+ title={pr.title ? `${pr.title}\n${label}` : label}
78
+ aria-label={label}
79
+ className="shrink-0 gap-1 rounded-full tabular-nums"
80
+ />
81
+ }
82
+ >
83
+ <Icon name={look.icon} size={13} className={look.className} />#{pr.number}
84
+ {mark && <StatusIcon status={mark.status} size="sm" aria-label={mark.label} />}
85
+ {pr.watching && <Icon name="eye" size={13} className="text-muted" aria-hidden />}
86
+ </DropdownMenuTrigger>
87
+ <DropdownMenuContent align="end">
88
+ <DropdownMenuItem
89
+ // A link, drawn as the other items (no underline).
90
+ className="no-underline"
91
+ render={<a href={pr.url} target="_blank" rel="noreferrer" />}
92
+ >
93
+ <Icon name="external-link" />
94
+ Open on GitHub
95
+ </DropdownMenuItem>
96
+ {pr.watching ? (
97
+ <DropdownMenuItem onClick={() => act('unwatch')}>
98
+ <Icon name="eye-off" />
99
+ Stop watching
100
+ </DropdownMenuItem>
101
+ ) : (
102
+ !done && (
103
+ <DropdownMenuItem onClick={() => act('watch')}>
104
+ <Icon name="eye" />
105
+ Watch checks and reviews
106
+ </DropdownMenuItem>
107
+ )
108
+ )}
109
+ <DropdownMenuItem onClick={() => act('unlink')}>
110
+ <Icon name="unlink" />
111
+ Unlink
112
+ </DropdownMenuItem>
113
+ </DropdownMenuContent>
114
+ </DropdownMenu>
115
+ );
116
+ }
@@ -0,0 +1,156 @@
1
+ // The open questions between this session and the others (`peers.ts`), above the composer. A question is its agent's to
2
+ // answer: until its deadline it shows quietly, saying who answers and when, with "Answer for it" (Force continue or
3
+ // Stop, in the agent's place; Keep waiting folds them back) folded away. Past its deadline it is the user's call, shown as a decision is: Force
4
+ // continue, Wait again (a new deadline), Stop. The notes other sessions leave show
5
+ // with the queue (`Queued`), never as a task.
6
+ import * as React from 'react';
7
+ import { Button, Icon, cn } from '@bridge/ui';
8
+
9
+ export interface Question {
10
+ request: string;
11
+ role: 'asker' | 'target';
12
+ other: string;
13
+ title: string;
14
+ text: string;
15
+ at: string;
16
+ expiresAt?: string;
17
+ expired: boolean;
18
+ delivered: boolean;
19
+ }
20
+
21
+ /** Minutes left until `iso`, shortly. */
22
+ const left = (iso: string, now: number) => {
23
+ const minutes = Math.max(0, Math.ceil((Date.parse(iso) - now) / 60_000));
24
+ return minutes <= 1 ? 'less than a minute left' : `${minutes} min left`;
25
+ };
26
+
27
+ export function Questions({
28
+ questions,
29
+ running,
30
+ onAnswer,
31
+ onExtend,
32
+ }: {
33
+ questions: Question[];
34
+ /** This session has a turn running. */
35
+ running: boolean;
36
+ onAnswer: (request: string, verdict: 'ok' | 'no') => Promise<unknown>;
37
+ onExtend: (request: string) => Promise<unknown>;
38
+ }) {
39
+ const [unfolded, setUnfolded] = React.useState<string>();
40
+ const [busy, setBusy] = React.useState<string>();
41
+ const [now, setNow] = React.useState(Date.now());
42
+ React.useEffect(() => {
43
+ const timer = setInterval(() => setNow(Date.now()), 30_000);
44
+ return () => clearInterval(timer);
45
+ }, []);
46
+ if (!questions.length) return null;
47
+ const run = (request: string, action: () => Promise<unknown>) => {
48
+ setBusy(request);
49
+ void action().finally(() => setBusy(undefined));
50
+ };
51
+ /** Who answers it, and when. */
52
+ const statusOf = ({ role, title, delivered }: Question) =>
53
+ role === 'asker'
54
+ ? `Waiting for the agent of ${title} to answer`
55
+ : running
56
+ ? 'Its agent answers when its current turn ends'
57
+ : delivered
58
+ ? 'Its agent has it'
59
+ : 'Its agent reads it at your next message here';
60
+ return (
61
+ <div
62
+ aria-label="Questions between sessions"
63
+ className="mx-auto box-border flex w-full max-w-[816px] shrink-0 flex-col gap-2 px-7 pb-2"
64
+ >
65
+ {questions.map((question) => {
66
+ const { request, role, title, text, expiresAt, expired } = question;
67
+ const disabled = busy === request;
68
+ return (
69
+ <div
70
+ key={request}
71
+ data-question={request}
72
+ data-expired={expired || undefined}
73
+ className={cn(
74
+ 'rounded-dialog border p-3 text-sm',
75
+ expired ? 'border-accent/40 bg-accent-subtle' : 'border-border',
76
+ )}
77
+ >
78
+ <p className={cn('text-xs', expired ? 'font-medium text-accent' : 'text-muted')}>
79
+ {role === 'asker' ? `Asked ${title}` : `Question from ${title}`}
80
+ {expired
81
+ ? ' · no answer in time: your call'
82
+ : expiresAt
83
+ ? ` · ${left(expiresAt, now)}`
84
+ : ''}
85
+ </p>
86
+ <p className="mt-0.5 whitespace-pre-wrap text-foreground">{text}</p>
87
+ {expired ? (
88
+ <div className="mt-2 flex flex-wrap justify-end gap-2">
89
+ <Button
90
+ size="sm"
91
+ variant="primary"
92
+ disabled={disabled}
93
+ onClick={() => run(request, () => onAnswer(request, 'ok'))}
94
+ >
95
+ Force continue
96
+ </Button>
97
+ <Button
98
+ size="sm"
99
+ variant="outline"
100
+ disabled={disabled}
101
+ onClick={() => run(request, () => onExtend(request))}
102
+ >
103
+ Wait again
104
+ </Button>
105
+ <Button
106
+ size="sm"
107
+ variant="outline"
108
+ disabled={disabled}
109
+ onClick={() => run(request, () => onAnswer(request, 'no'))}
110
+ >
111
+ Stop
112
+ </Button>
113
+ </div>
114
+ ) : (
115
+ <div className="mt-1.5 flex flex-wrap items-center gap-2 text-xs text-muted">
116
+ <Icon name="loader-circle" size={12} />
117
+ <span>{statusOf(question)}</span>
118
+ {unfolded === request ? (
119
+ <span className="ml-auto flex gap-2">
120
+ <Button
121
+ size="sm"
122
+ variant="outline"
123
+ disabled={disabled}
124
+ onClick={() => run(request, () => onAnswer(request, 'ok'))}
125
+ >
126
+ Force continue
127
+ </Button>
128
+ <Button
129
+ size="sm"
130
+ variant="outline"
131
+ disabled={disabled}
132
+ onClick={() => run(request, () => onAnswer(request, 'no'))}
133
+ >
134
+ Stop
135
+ </Button>
136
+ <Button size="sm" variant="ghost" onClick={() => setUnfolded(undefined)}>
137
+ Keep waiting
138
+ </Button>
139
+ </span>
140
+ ) : (
141
+ <button
142
+ type="button"
143
+ className="ml-auto cursor-pointer border-0 bg-transparent p-0 text-xs text-secondary underline-offset-2 hover:underline"
144
+ onClick={() => setUnfolded(request)}
145
+ >
146
+ Answer for it
147
+ </button>
148
+ )}
149
+ </div>
150
+ )}
151
+ </div>
152
+ );
153
+ })}
154
+ </div>
155
+ );
156
+ }
@@ -0,0 +1,203 @@
1
+ // The scheduled tasks bound to one session, in its header (research-040, revision): a badge saying when the next one
2
+ // runs, and its menu. The tasks live in the scheduler plugin (nothing is imported from it: plugins never import each
3
+ // other); the routes are the scheduler's, filtered by the sessions subject. The scheduler is optional (a new workspace
4
+ // installs it disabled): its routes are asked only while it is active on the node (`ctx.nodes.isActive`, followed live,
5
+ // so enabling it in Plugins shows the badge without a reload).
6
+ import * as React from 'react';
7
+ import {
8
+ Badge,
9
+ Button,
10
+ DropdownMenu,
11
+ DropdownMenuContent,
12
+ DropdownMenuItem,
13
+ DropdownMenuSub,
14
+ DropdownMenuSubContent,
15
+ DropdownMenuSubTrigger,
16
+ DropdownMenuTrigger,
17
+ Icon,
18
+ readJson,
19
+ snoozeWakeLabel,
20
+ useToast,
21
+ } from '@bridge/ui';
22
+ import type { Context } from 'cordis';
23
+
24
+ /** A task as the scheduler's `GET /scheduler/tasks` answers it. */
25
+ interface ScheduledTaskView {
26
+ scheduledTaskId: string;
27
+ title: string;
28
+ enabled: boolean;
29
+ scheduleText: string;
30
+ nextRunAt: string | null;
31
+ lastRunStatus: 'never' | 'succeeded' | 'failed' | 'timed_out';
32
+ lastRunError?: string;
33
+ }
34
+
35
+ interface SessionLite {
36
+ id: string;
37
+ title: string;
38
+ }
39
+
40
+ const messageOf = (error: unknown) => (error instanceof Error ? error.message : String(error));
41
+
42
+ /** The task that runs soonest among those that are on, or `undefined` when none is planned. */
43
+ const soonestOf = (tasks: ScheduledTaskView[]): ScheduledTaskView | undefined => {
44
+ let soonest: ScheduledTaskView | undefined;
45
+ for (const task of tasks) {
46
+ if (!task.enabled || task.nextRunAt === null) continue;
47
+ if (
48
+ soonest === undefined ||
49
+ soonest.nextRunAt === null ||
50
+ Date.parse(task.nextRunAt) < Date.parse(soonest.nextRunAt)
51
+ )
52
+ soonest = task;
53
+ }
54
+ return soonest;
55
+ };
56
+
57
+ /** The tasks of one session, in its header: a badge saying when the next one runs, and its menu. */
58
+ export function SessionScheduled({
59
+ ctx,
60
+ node,
61
+ session,
62
+ }: {
63
+ ctx: Context;
64
+ node: string;
65
+ session: SessionLite;
66
+ }) {
67
+ const { workspace } = ctx;
68
+ const { toast } = useToast();
69
+ const api = `/${workspace.slug}/api/scheduler`;
70
+ const headers = { 'x-bridge-node': node };
71
+ const postHeaders = { 'content-type': 'application/json', 'x-bridge-node': node };
72
+ const [tasks, setTasks] = React.useState<ScheduledTaskView[]>([]);
73
+ const scheduler = React.useSyncExternalStore(ctx.nodes.subscribe, () =>
74
+ ctx.nodes.isActive('scheduler', node),
75
+ );
76
+
77
+ const report = React.useCallback(
78
+ (what: string) => (cause: unknown) =>
79
+ toast({ title: what, description: messageOf(cause), variant: 'error' }),
80
+ [toast],
81
+ );
82
+
83
+ const load = React.useCallback(async () => {
84
+ const res = await workspace.fetch(
85
+ `${api}/scheduler/tasks?subjectDomain=sessions/sessions&subjectId=${encodeURIComponent(session.id)}`,
86
+ { headers },
87
+ );
88
+ const body = (await readJson(res)) as { tasks: ScheduledTaskView[] };
89
+ setTasks(body.tasks);
90
+ }, [workspace, api, node, session.id]);
91
+
92
+ React.useEffect(() => {
93
+ if (!scheduler) {
94
+ setTasks([]);
95
+ return;
96
+ }
97
+ let live = true;
98
+ const tick = () => {
99
+ // The scheduler gone meanwhile (404): nothing to show; another failure keeps what is shown.
100
+ void load().catch((cause: unknown) => {
101
+ if (!live) return;
102
+ if ((cause as { status?: unknown } | undefined)?.status === 404) setTasks([]);
103
+ });
104
+ };
105
+ tick();
106
+ const every = window.setInterval(tick, 30_000);
107
+ window.addEventListener('focus', tick);
108
+ return () => {
109
+ live = false;
110
+ window.clearInterval(every);
111
+ window.removeEventListener('focus', tick);
112
+ };
113
+ // `session` is the listing's object: it changes with a turn or a queue event, which lists again.
114
+ }, [load, session, scheduler]);
115
+
116
+ const apply = (updated: ScheduledTaskView) =>
117
+ setTasks((was) =>
118
+ was.map((task) => (task.scheduledTaskId === updated.scheduledTaskId ? updated : task)),
119
+ );
120
+
121
+ const run = async (task: ScheduledTaskView) => {
122
+ const res = await workspace.fetch(`${api}/scheduler/tasks/run`, {
123
+ method: 'POST',
124
+ headers: postHeaders,
125
+ body: JSON.stringify({ scheduledTaskId: task.scheduledTaskId }),
126
+ });
127
+ // The run starts; its outcome shows in Scheduled when it ends.
128
+ apply((await readJson(res)) as ScheduledTaskView);
129
+ toast({ title: 'Scheduled task started' });
130
+ };
131
+
132
+ const toggle = async (task: ScheduledTaskView) => {
133
+ const enabled = !task.enabled;
134
+ const was = { enabled: task.enabled, nextRunAt: task.nextRunAt };
135
+ setTasks((current) =>
136
+ current.map((each) =>
137
+ each.scheduledTaskId === task.scheduledTaskId
138
+ ? { ...each, enabled, nextRunAt: enabled ? each.nextRunAt : null }
139
+ : each,
140
+ ),
141
+ );
142
+ try {
143
+ const res = await workspace.fetch(`${api}/scheduler/tasks/update`, {
144
+ method: 'POST',
145
+ headers: postHeaders,
146
+ body: JSON.stringify({ scheduledTaskId: task.scheduledTaskId, enabled }),
147
+ });
148
+ apply((await readJson(res)) as ScheduledTaskView);
149
+ } catch (cause) {
150
+ setTasks((current) =>
151
+ current.map((each) =>
152
+ each.scheduledTaskId === task.scheduledTaskId ? { ...each, ...was } : each,
153
+ ),
154
+ );
155
+ report(
156
+ enabled ? 'Could not resume the scheduled task' : 'Could not pause the scheduled task',
157
+ )(cause);
158
+ }
159
+ };
160
+
161
+ if (!scheduler || tasks.length === 0) return null;
162
+
163
+ const paused = tasks.every((task) => !task.enabled);
164
+ const soonest = soonestOf(tasks);
165
+ const words = soonest?.nextRunAt ? snoozeWakeLabel(soonest.nextRunAt) : 'Not planned';
166
+
167
+ return (
168
+ <DropdownMenu>
169
+ <DropdownMenuTrigger
170
+ render={
171
+ <Button variant="ghost" size="sm" className="h-auto p-0" aria-label="Scheduled tasks" />
172
+ }
173
+ >
174
+ <Badge className="gap-1">
175
+ <Icon name="alarm-clock" size={12} />
176
+ {paused ? 'Paused' : `Scheduled · ${words}`}
177
+ </Badge>
178
+ </DropdownMenuTrigger>
179
+ <DropdownMenuContent align="end" className="min-w-[260px]">
180
+ {tasks.map((task) => (
181
+ <DropdownMenuSub key={task.scheduledTaskId}>
182
+ <DropdownMenuSubTrigger className="h-auto py-1.5">
183
+ <span className="flex min-w-0 flex-col">
184
+ <span className="truncate text-sm text-foreground">{task.title}</span>
185
+ <span className="truncate text-xs text-muted">{task.scheduleText}</span>
186
+ </span>
187
+ </DropdownMenuSubTrigger>
188
+ <DropdownMenuSubContent>
189
+ <DropdownMenuItem
190
+ onSelect={() => void run(task).catch(report('Could not run the scheduled task'))}
191
+ >
192
+ Run now
193
+ </DropdownMenuItem>
194
+ <DropdownMenuItem onSelect={() => void toggle(task).catch(() => {})}>
195
+ {task.enabled ? 'Pause' : 'Resume'}
196
+ </DropdownMenuItem>
197
+ </DropdownMenuSubContent>
198
+ </DropdownMenuSub>
199
+ ))}
200
+ </DropdownMenuContent>
201
+ </DropdownMenu>
202
+ );
203
+ }
@@ -0,0 +1,136 @@
1
+ // A sub-agent's view (bridge#212 S8, ./subagents.tsx): what one sub-agent of a session's agent did, read only, in the
2
+ // session's pane: its header (its title, the "Sub-agent" marker, a link to its session, its state, and Stop while it
3
+ // runs when its harness can stop it alone), and its lines as one turn of the conversation (its task as the message, its
4
+ // words and tool calls, its thought while it runs), from its session's stream (`events`, `live`) and its own older lines
5
+ // (`GET /sessions/events?id=&subagent=`, `load`). No prompt: a sub-agent takes no message.
6
+ import * as React from 'react';
7
+ import { Button, ScrollArea } from '@bridge/ui';
8
+ import { Conversation, Spinner, type Live, type Stored } from './conversation.tsx';
9
+ import { ChildStateMark, ParentLink } from './children.tsx';
10
+ import {
11
+ SubagentMarker,
12
+ subagentEvents,
13
+ subagentState,
14
+ subagentsOf,
15
+ type SubagentEntry,
16
+ } from './subagents.tsx';
17
+
18
+ /** Sub-agent `sub`'s part of its session's running turn: its words, thought and tool calls; `null` once it ended. */
19
+ export const subagentLive = (live: Live | null, sub: string, running: boolean): Live | null => {
20
+ if (!live || !running) return null;
21
+ const own = live.subagents?.[sub];
22
+ return {
23
+ seq: live.seq,
24
+ text: own?.text ?? '',
25
+ thought: own?.thought ?? '',
26
+ tools: Object.fromEntries(
27
+ Object.entries(live.tools).filter(([, each]) => each.subagent === sub),
28
+ ),
29
+ plan: [],
30
+ usage: null,
31
+ decisions: [],
32
+ };
33
+ };
34
+
35
+ export function SubagentView({
36
+ session,
37
+ sub,
38
+ entry,
39
+ events,
40
+ live,
41
+ sessionRunning,
42
+ load,
43
+ folder,
44
+ workspace,
45
+ listToggle,
46
+ onStop,
47
+ }: {
48
+ session: { id: string; title: string };
49
+ sub: string;
50
+ /** Its entry in its session's record, when listed there. */
51
+ entry: SubagentEntry | undefined;
52
+ /** Its session's lines as the page holds them (the stream's). */
53
+ events: readonly Stored[];
54
+ live: Live | null;
55
+ sessionRunning: boolean;
56
+ /** Reads its own lines from the whole history. */
57
+ load: () => Promise<Stored[]>;
58
+ folder?: string | undefined;
59
+ workspace: string;
60
+ /** The page's button showing or hiding the sessions list. */
61
+ listToggle: React.ReactNode;
62
+ /** Stops it through its harness; absent when its harness cannot. */
63
+ onStop?: (() => void) | undefined;
64
+ }) {
65
+ const [loaded, setLoaded] = React.useState<Stored[]>([]);
66
+ const [error, setError] = React.useState('');
67
+ React.useEffect(() => {
68
+ let current = true;
69
+ setLoaded([]);
70
+ setError('');
71
+ load().then(
72
+ (lines) => {
73
+ if (current) setLoaded(lines);
74
+ },
75
+ (cause: unknown) => {
76
+ if (current) setError(cause instanceof Error ? cause.message : String(cause));
77
+ },
78
+ );
79
+ return () => {
80
+ current = false;
81
+ };
82
+ }, [session.id, sub]);
83
+ const lines = React.useMemo(
84
+ () => [...loaded, ...events.filter((each) => each.subagent === sub)],
85
+ [loaded, events, sub],
86
+ );
87
+ const shown = React.useMemo(() => subagentEvents(lines, sub), [lines, sub]);
88
+ const card = React.useMemo(() => subagentsOf(lines).get(sub), [lines, sub]);
89
+ const status = card?.status ?? entry?.status ?? 'running';
90
+ const running = status === 'running' && sessionRunning;
91
+ const state = subagentState(status, sessionRunning);
92
+ const title = card?.title ?? entry?.title ?? 'Sub-agent';
93
+ const ownLive = React.useMemo(() => subagentLive(live, sub, running), [live, sub, running]);
94
+ return (
95
+ <div data-who="subagent-view" data-subagent={sub} className="flex h-full min-w-0 flex-col">
96
+ <header className="flex h-11 shrink-0 items-center gap-2 border-b border-border px-4">
97
+ {listToggle}
98
+ <h2 className="min-w-0 truncate text-sm font-semibold">{title}</h2>
99
+ <SubagentMarker agent={card?.agent ?? entry?.agent} />
100
+ <ParentLink parent={session.id} />
101
+ <span className="flex-1" />
102
+ {running ? (
103
+ <span className="flex items-center gap-1.5 text-xs text-secondary">
104
+ <Spinner />
105
+ Running…
106
+ </span>
107
+ ) : (
108
+ <ChildStateMark state={state} />
109
+ )}
110
+ {running && onStop && (
111
+ <Button variant="outline" size="sm" aria-label={`Stop ${title}`} onClick={onStop}>
112
+ Stop
113
+ </Button>
114
+ )}
115
+ </header>
116
+ {error && (
117
+ <p role="alert" className="px-4 py-2 text-xs text-destructive">
118
+ {error}
119
+ </p>
120
+ )}
121
+ <ScrollArea className="min-h-0 flex-1">
122
+ <Conversation
123
+ events={shown}
124
+ live={ownLive}
125
+ folder={folder}
126
+ workspace={workspace}
127
+ onReuse={() => {}}
128
+ onReview={() => {}}
129
+ />
130
+ {!shown.length && !error && (
131
+ <p className="px-7 py-6 text-sm text-muted">Nothing from this sub-agent yet.</p>
132
+ )}
133
+ </ScrollArea>
134
+ </div>
135
+ );
136
+ }