@schlessera/brain-ui-react 0.34.0 → 0.35.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.
- package/README.md +12 -0
- package/dist/components/activity/activity-page.d.ts.map +1 -1
- package/dist/components/activity/activity-page.js +8 -149
- package/dist/components/activity/activity-page.js.map +1 -1
- package/dist/components/activity/activity-rollups.d.ts +5 -0
- package/dist/components/activity/activity-rollups.d.ts.map +1 -0
- package/dist/components/activity/activity-rollups.js +39 -0
- package/dist/components/activity/activity-rollups.js.map +1 -0
- package/dist/components/activity/activity-run-detail.d.ts +11 -0
- package/dist/components/activity/activity-run-detail.d.ts.map +1 -0
- package/dist/components/activity/activity-run-detail.js +111 -0
- package/dist/components/activity/activity-run-detail.js.map +1 -0
- package/dist/components/activity/activity-run-list.d.ts +15 -0
- package/dist/components/activity/activity-run-list.d.ts.map +1 -0
- package/dist/components/activity/activity-run-list.js +25 -0
- package/dist/components/activity/activity-run-list.js.map +1 -0
- package/dist/components/chat/brain-markdown-code.d.ts +4 -0
- package/dist/components/chat/brain-markdown-code.d.ts.map +1 -0
- package/dist/components/chat/brain-markdown-code.js +47 -0
- package/dist/components/chat/brain-markdown-code.js.map +1 -0
- package/dist/components/chat/brain-markdown-entities.d.ts +14 -0
- package/dist/components/chat/brain-markdown-entities.d.ts.map +1 -0
- package/dist/components/chat/brain-markdown-entities.js +93 -0
- package/dist/components/chat/brain-markdown-entities.js.map +1 -0
- package/dist/components/chat/brain-markdown-links.d.ts +36 -0
- package/dist/components/chat/brain-markdown-links.d.ts.map +1 -0
- package/dist/components/chat/brain-markdown-links.js +176 -0
- package/dist/components/chat/brain-markdown-links.js.map +1 -0
- package/dist/components/chat/brain-markdown-share.d.ts +15 -0
- package/dist/components/chat/brain-markdown-share.d.ts.map +1 -0
- package/dist/components/chat/brain-markdown-share.js +40 -0
- package/dist/components/chat/brain-markdown-share.js.map +1 -0
- package/dist/components/chat/brain-markdown.d.ts +1 -34
- package/dist/components/chat/brain-markdown.d.ts.map +1 -1
- package/dist/components/chat/brain-markdown.js +9 -402
- package/dist/components/chat/brain-markdown.js.map +1 -1
- package/dist/components/chat/composer.d.ts.map +1 -1
- package/dist/components/chat/composer.js +14 -1
- package/dist/components/chat/composer.js.map +1 -1
- package/dist/components/chat/session-drawer.d.ts.map +1 -1
- package/dist/components/chat/session-drawer.js +25 -10
- package/dist/components/chat/session-drawer.js.map +1 -1
- package/dist/components/chat/tool-views.d.ts +2 -2
- package/dist/components/chat/tool-views.d.ts.map +1 -1
- package/dist/components/chat/tool-views.js +2 -16
- package/dist/components/chat/tool-views.js.map +1 -1
- package/dist/components/chat/use-markdown-highlight.d.ts +12 -0
- package/dist/components/chat/use-markdown-highlight.d.ts.map +1 -0
- package/dist/components/chat/use-markdown-highlight.js +56 -0
- package/dist/components/chat/use-markdown-highlight.js.map +1 -0
- package/dist/components/connectivity/connection-gate.d.ts.map +1 -1
- package/dist/components/connectivity/connection-gate.js +94 -8
- package/dist/components/connectivity/connection-gate.js.map +1 -1
- package/dist/components/connectivity/connection-state.d.ts +12 -0
- package/dist/components/connectivity/connection-state.d.ts.map +1 -0
- package/dist/components/connectivity/connection-state.js +23 -0
- package/dist/components/connectivity/connection-state.js.map +1 -0
- package/dist/components/graph/graph-canvas-lazy.d.ts +2 -0
- package/dist/components/graph/graph-canvas-lazy.d.ts.map +1 -0
- package/dist/components/graph/graph-canvas-lazy.js +4 -0
- package/dist/components/graph/graph-canvas-lazy.js.map +1 -0
- package/dist/components/graph/graph-controls.js +4 -1
- package/dist/components/graph/graph-controls.js.map +1 -1
- package/dist/components/graph/graph-maintenance.d.ts +8 -0
- package/dist/components/graph/graph-maintenance.d.ts.map +1 -0
- package/dist/components/graph/graph-maintenance.js +115 -0
- package/dist/components/graph/graph-maintenance.js.map +1 -0
- package/dist/components/graph/graph-page.d.ts.map +1 -1
- package/dist/components/graph/graph-page.js +11 -306
- package/dist/components/graph/graph-page.js.map +1 -1
- package/dist/components/graph/graph-scene.d.ts +8 -0
- package/dist/components/graph/graph-scene.d.ts.map +1 -0
- package/dist/components/graph/graph-scene.js +208 -0
- package/dist/components/graph/graph-scene.js.map +1 -0
- package/dist/components/graph/graph-spinner.d.ts +2 -0
- package/dist/components/graph/graph-spinner.d.ts.map +1 -0
- package/dist/components/graph/graph-spinner.js +6 -0
- package/dist/components/graph/graph-spinner.js.map +1 -0
- package/dist/components/layout/app-shell.d.ts.map +1 -1
- package/dist/components/layout/app-shell.js +2 -1
- package/dist/components/layout/app-shell.js.map +1 -1
- package/dist/components/quick-actions/add-modal.d.ts.map +1 -1
- package/dist/components/quick-actions/add-modal.js +47 -4
- package/dist/components/quick-actions/add-modal.js.map +1 -1
- package/dist/components/quick-actions/search-modal.d.ts.map +1 -1
- package/dist/components/quick-actions/search-modal.js +46 -18
- package/dist/components/quick-actions/search-modal.js.map +1 -1
- package/dist/components/quick-actions/streaming-modal.d.ts.map +1 -1
- package/dist/components/quick-actions/streaming-modal.js +4 -1
- package/dist/components/quick-actions/streaming-modal.js.map +1 -1
- package/dist/components/settings/devices-agents-tab.d.ts +5 -0
- package/dist/components/settings/devices-agents-tab.d.ts.map +1 -0
- package/dist/components/settings/devices-agents-tab.js +96 -0
- package/dist/components/settings/devices-agents-tab.js.map +1 -0
- package/dist/components/settings/one-time-agent-credential.d.ts +3 -0
- package/dist/components/settings/one-time-agent-credential.d.ts.map +1 -0
- package/dist/components/settings/one-time-agent-credential.js +55 -0
- package/dist/components/settings/one-time-agent-credential.js.map +1 -0
- package/dist/components/settings/settings-panel.d.ts.map +1 -1
- package/dist/components/settings/settings-panel.js +16 -3
- package/dist/components/settings/settings-panel.js.map +1 -1
- package/dist/hooks/use-vpn-status.d.ts +6 -1
- package/dist/hooks/use-vpn-status.d.ts.map +1 -1
- package/dist/hooks/use-vpn-status.js +67 -30
- package/dist/hooks/use-vpn-status.js.map +1 -1
- package/dist/hooks/use-websocket.d.ts +3 -2
- package/dist/hooks/use-websocket.d.ts.map +1 -1
- package/dist/hooks/use-websocket.js +65 -254
- package/dist/hooks/use-websocket.js.map +1 -1
- package/dist/hooks/websocket-handlers/activity.d.ts +5 -0
- package/dist/hooks/websocket-handlers/activity.d.ts.map +1 -0
- package/dist/hooks/websocket-handlers/activity.js +10 -0
- package/dist/hooks/websocket-handlers/activity.js.map +1 -0
- package/dist/hooks/websocket-handlers/chat.d.ts +17 -0
- package/dist/hooks/websocket-handlers/chat.d.ts.map +1 -0
- package/dist/hooks/websocket-handlers/chat.js +175 -0
- package/dist/hooks/websocket-handlers/chat.js.map +1 -0
- package/dist/hooks/websocket-handlers/connection.d.ts +6 -0
- package/dist/hooks/websocket-handlers/connection.d.ts.map +1 -0
- package/dist/hooks/websocket-handlers/connection.js +27 -0
- package/dist/hooks/websocket-handlers/connection.js.map +1 -0
- package/dist/hooks/websocket-handlers/index.d.ts +4 -0
- package/dist/hooks/websocket-handlers/index.d.ts.map +1 -0
- package/dist/hooks/websocket-handlers/index.js +19 -0
- package/dist/hooks/websocket-handlers/index.js.map +1 -0
- package/dist/hooks/websocket-handlers/mask.d.ts +4 -0
- package/dist/hooks/websocket-handlers/mask.d.ts.map +1 -0
- package/dist/hooks/websocket-handlers/mask.js +14 -0
- package/dist/hooks/websocket-handlers/mask.js.map +1 -0
- package/dist/hooks/websocket-handlers/provider.d.ts +4 -0
- package/dist/hooks/websocket-handlers/provider.d.ts.map +1 -0
- package/dist/hooks/websocket-handlers/provider.js +31 -0
- package/dist/hooks/websocket-handlers/provider.js.map +1 -0
- package/dist/hooks/websocket-handlers/types.d.ts +24 -0
- package/dist/hooks/websocket-handlers/types.d.ts.map +1 -0
- package/dist/hooks/websocket-handlers/types.js +2 -0
- package/dist/hooks/websocket-handlers/types.js.map +1 -0
- package/dist/lib/api-client.d.ts +32 -0
- package/dist/lib/api-client.d.ts.map +1 -1
- package/dist/lib/api-client.js +11 -0
- package/dist/lib/api-client.js.map +1 -1
- package/dist/lib/format-time.d.ts +3 -0
- package/dist/lib/format-time.d.ts.map +1 -0
- package/dist/lib/format-time.js +25 -0
- package/dist/lib/format-time.js.map +1 -0
- package/dist/lib/push-registration.d.ts +7 -0
- package/dist/lib/push-registration.d.ts.map +1 -0
- package/dist/lib/push-registration.js +26 -0
- package/dist/lib/push-registration.js.map +1 -0
- package/dist/stores/activity-store-helpers.d.ts +50 -0
- package/dist/stores/activity-store-helpers.d.ts.map +1 -0
- package/dist/stores/activity-store-helpers.js +143 -0
- package/dist/stores/activity-store-helpers.js.map +1 -0
- package/dist/stores/activity-store-types.d.ts +48 -0
- package/dist/stores/activity-store-types.d.ts.map +1 -0
- package/dist/stores/activity-store-types.js +2 -0
- package/dist/stores/activity-store-types.js.map +1 -0
- package/dist/stores/activity-store.d.ts +2 -78
- package/dist/stores/activity-store.d.ts.map +1 -1
- package/dist/stores/activity-store.js +22 -142
- package/dist/stores/activity-store.js.map +1 -1
- package/dist/stores/connection-store.d.ts +14 -2
- package/dist/stores/connection-store.d.ts.map +1 -1
- package/dist/stores/connection-store.js +17 -0
- package/dist/stores/connection-store.js.map +1 -1
- package/dist/stores/file-store.d.ts.map +1 -1
- package/dist/stores/file-store.js +54 -18
- package/dist/stores/file-store.js.map +1 -1
- package/dist/stores/principal-store.d.ts +16 -0
- package/dist/stores/principal-store.d.ts.map +1 -0
- package/dist/stores/principal-store.js +29 -0
- package/dist/stores/principal-store.js.map +1 -0
- package/dist/stores/ui-store.d.ts +1 -1
- package/dist/stores/ui-store.d.ts.map +1 -1
- package/dist/styles.css +1 -1
- package/package.json +2 -2
- package/src/components/activity/activity-page.tsx +6 -477
- package/src/components/activity/activity-rollups.tsx +94 -0
- package/src/components/activity/activity-run-detail.tsx +301 -0
- package/src/components/activity/activity-run-list.tsx +97 -0
- package/src/components/chat/brain-markdown-code.tsx +60 -0
- package/src/components/chat/brain-markdown-entities.tsx +116 -0
- package/src/components/chat/brain-markdown-links.tsx +247 -0
- package/src/components/chat/brain-markdown-share.ts +47 -0
- package/src/components/chat/brain-markdown.tsx +27 -535
- package/src/components/chat/composer.tsx +14 -1
- package/src/components/chat/session-drawer.tsx +29 -10
- package/src/components/chat/tool-views.tsx +2 -13
- package/src/components/chat/use-markdown-highlight.ts +63 -0
- package/src/components/connectivity/connection-gate.tsx +128 -14
- package/src/components/connectivity/connection-state.ts +37 -0
- package/src/components/graph/graph-canvas-lazy.tsx +4 -0
- package/src/components/graph/graph-controls.tsx +4 -1
- package/src/components/graph/graph-maintenance.tsx +304 -0
- package/src/components/graph/graph-page.tsx +11 -840
- package/src/components/graph/graph-scene.tsx +548 -0
- package/src/components/graph/graph-spinner.tsx +9 -0
- package/src/components/layout/app-shell.tsx +2 -0
- package/src/components/quick-actions/add-modal.tsx +49 -4
- package/src/components/quick-actions/search-modal.tsx +46 -18
- package/src/components/quick-actions/streaming-modal.tsx +3 -1
- package/src/components/settings/devices-agents-tab.tsx +231 -0
- package/src/components/settings/one-time-agent-credential.tsx +131 -0
- package/src/components/settings/settings-panel.tsx +20 -5
- package/src/hooks/use-vpn-status.ts +71 -31
- package/src/hooks/use-websocket.ts +74 -275
- package/src/hooks/websocket-handlers/activity.ts +13 -0
- package/src/hooks/websocket-handlers/chat.ts +210 -0
- package/src/hooks/websocket-handlers/connection.ts +30 -0
- package/src/hooks/websocket-handlers/index.ts +59 -0
- package/src/hooks/websocket-handlers/mask.ts +17 -0
- package/src/hooks/websocket-handlers/provider.ts +35 -0
- package/src/hooks/websocket-handlers/types.ts +27 -0
- package/src/lib/api-client.ts +40 -1
- package/src/lib/format-time.ts +20 -0
- package/src/lib/push-registration.ts +29 -0
- package/src/stores/activity-store-helpers.ts +164 -0
- package/src/stores/activity-store-types.ts +55 -0
- package/src/stores/activity-store.ts +21 -217
- package/src/stores/connection-store.ts +33 -2
- package/src/stores/file-store.ts +42 -12
- package/src/stores/principal-store.ts +38 -0
- package/src/stores/ui-store.ts +1 -1
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
import { activeChat, useChatStore } from "../../stores/chat-store.js";
|
|
2
|
+
import type { ChatMessage, ToolCall, AskUserExchange } from "../../stores/chat-store.js";
|
|
3
|
+
import type {
|
|
4
|
+
AskUserQuestion,
|
|
5
|
+
ServerMessage,
|
|
6
|
+
SessionHistoryMessage,
|
|
7
|
+
} from "@schlessera/brain-ui-sdk/protocol";
|
|
8
|
+
import { isAskUserTool } from "../../lib/tool-names.js";
|
|
9
|
+
import type { ServerMessageHandlerMap } from "./types.js";
|
|
10
|
+
|
|
11
|
+
type ChatFrame =
|
|
12
|
+
| "text_delta"
|
|
13
|
+
| "thinking_delta"
|
|
14
|
+
| "tool_use_start"
|
|
15
|
+
| "tool_input_delta"
|
|
16
|
+
| "tool_use_complete"
|
|
17
|
+
| "tool_approval_request"
|
|
18
|
+
| "tool_result"
|
|
19
|
+
| "ask_user_request"
|
|
20
|
+
| "result"
|
|
21
|
+
| "session_history"
|
|
22
|
+
| "status";
|
|
23
|
+
|
|
24
|
+
let historyMessageCounter = 0;
|
|
25
|
+
function historyId() {
|
|
26
|
+
return `hist-${++historyMessageCounter}-${Date.now()}`;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function convertHistoryMessage(msg: SessionHistoryMessage): ChatMessage {
|
|
30
|
+
// Fallback for history without chronological parts: synthesize the legacy
|
|
31
|
+
// grouped order (thinking, tools, text).
|
|
32
|
+
const parts =
|
|
33
|
+
msg.parts ??
|
|
34
|
+
[
|
|
35
|
+
...(msg.thinking ? [{ kind: "thinking", text: msg.thinking } as const] : []),
|
|
36
|
+
...msg.toolCalls.map((_, i) => ({ kind: "tool", toolIndex: i }) as const),
|
|
37
|
+
...(msg.content ? [{ kind: "text", text: msg.content } as const] : []),
|
|
38
|
+
];
|
|
39
|
+
const askUserExchanges = reconstructAskUserExchanges(msg.toolCalls);
|
|
40
|
+
return {
|
|
41
|
+
id: historyId(),
|
|
42
|
+
role: msg.role,
|
|
43
|
+
content: msg.content,
|
|
44
|
+
thinking: msg.thinking,
|
|
45
|
+
toolCalls: msg.toolCalls.map((tc): ToolCall => ({
|
|
46
|
+
id: tc.id,
|
|
47
|
+
name: tc.name,
|
|
48
|
+
input: tc.input,
|
|
49
|
+
inputJson: JSON.stringify(tc.input, null, 2),
|
|
50
|
+
output: tc.output,
|
|
51
|
+
isError: tc.isError,
|
|
52
|
+
status: "complete",
|
|
53
|
+
})),
|
|
54
|
+
parts,
|
|
55
|
+
isStreaming: false,
|
|
56
|
+
timestamp: Date.now(),
|
|
57
|
+
...(askUserExchanges ? { askUserExchanges } : {}),
|
|
58
|
+
...(msg.attachmentCount ? { attachmentCount: msg.attachmentCount } : {}),
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Rebuild ask_user exchanges from a resumed message's tool calls. */
|
|
63
|
+
function isBareAnswersMap(v: unknown): v is Record<string, string> {
|
|
64
|
+
return (
|
|
65
|
+
!!v &&
|
|
66
|
+
typeof v === "object" &&
|
|
67
|
+
!Array.isArray(v) &&
|
|
68
|
+
Object.values(v).every((x) => typeof x === "string")
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function reconstructAskUserExchanges(
|
|
73
|
+
toolCalls: SessionHistoryMessage["toolCalls"]
|
|
74
|
+
): AskUserExchange[] | undefined {
|
|
75
|
+
const exchanges: AskUserExchange[] = [];
|
|
76
|
+
for (const tc of toolCalls) {
|
|
77
|
+
if (!isAskUserTool(tc.name)) continue;
|
|
78
|
+
const questions = (tc.input?.questions as AskUserQuestion[]) ?? [];
|
|
79
|
+
const exchange: AskUserExchange = { requestId: tc.id, questions };
|
|
80
|
+
if (tc.output) {
|
|
81
|
+
try {
|
|
82
|
+
const payload = JSON.parse(tc.output) as {
|
|
83
|
+
answers?: Record<string, string>;
|
|
84
|
+
annotations?: AskUserExchange["annotations"];
|
|
85
|
+
};
|
|
86
|
+
if (payload && typeof payload === "object" && payload.answers) {
|
|
87
|
+
exchange.answers = payload.answers;
|
|
88
|
+
exchange.annotations = payload.annotations;
|
|
89
|
+
} else if (isBareAnswersMap(payload)) {
|
|
90
|
+
// The pi backend persists the bare answers map, without the
|
|
91
|
+
// `{answers}` envelope the Claude tool writes.
|
|
92
|
+
exchange.answers = payload;
|
|
93
|
+
}
|
|
94
|
+
} catch {
|
|
95
|
+
// Non-JSON output means the question was dismissed or errored out.
|
|
96
|
+
exchange.cancelled = true;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
if (tc.isError && !exchange.answers) exchange.cancelled = true;
|
|
100
|
+
exchanges.push(exchange);
|
|
101
|
+
}
|
|
102
|
+
return exchanges.length ? exchanges : undefined;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Map a frame to the run-state its session should show in the session list. */
|
|
106
|
+
export function runStateForFrame(msg: ServerMessage): "streaming" | "queued" | "idle" {
|
|
107
|
+
if (msg.type === "result" || msg.type === "error") return "idle";
|
|
108
|
+
if (msg.type === "status") {
|
|
109
|
+
if (msg.status === "queued") return "queued";
|
|
110
|
+
if (msg.status === "idle" || msg.status === "cancelled") return "idle";
|
|
111
|
+
}
|
|
112
|
+
return "streaming";
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export const chatFrameHandlers = {
|
|
116
|
+
text_delta: (msg, context) => {
|
|
117
|
+
// Opening the bubble stays immediate — the first token should show a
|
|
118
|
+
// message starting, and every later delta needs isStreaming to be true.
|
|
119
|
+
if (!context.buffer()?.isStreaming) {
|
|
120
|
+
context.state.startAssistantMessage(context.key);
|
|
121
|
+
}
|
|
122
|
+
context.enqueueDelta(context.key, "text", msg.text);
|
|
123
|
+
},
|
|
124
|
+
thinking_delta: (msg, context) => {
|
|
125
|
+
if (!context.buffer()?.isStreaming) {
|
|
126
|
+
context.state.startAssistantMessage(context.key);
|
|
127
|
+
}
|
|
128
|
+
context.enqueueDelta(context.key, "thinking", msg.text);
|
|
129
|
+
},
|
|
130
|
+
tool_use_start: (msg, context) => {
|
|
131
|
+
// A tool call INSIDE a subagent nests under its Agent entry, rendered
|
|
132
|
+
// from the activity stream — putting it in the flat transcript would
|
|
133
|
+
// interleave fan-out work with the main turn's steps.
|
|
134
|
+
if (msg.parentToolUseId) return;
|
|
135
|
+
context.state.startToolCall(context.key, msg.toolUseId, msg.toolName);
|
|
136
|
+
},
|
|
137
|
+
tool_input_delta: (msg, context) => {
|
|
138
|
+
context.state.appendToolInput(context.key, msg.partialJson);
|
|
139
|
+
},
|
|
140
|
+
tool_use_complete: (msg, context) => {
|
|
141
|
+
// Subagent tool calls render nested (activity stream), and the flat
|
|
142
|
+
// store's name-based fallback match must never see them.
|
|
143
|
+
if (msg.parentToolUseId) return;
|
|
144
|
+
context.state.completeToolCall(context.key, msg.toolUseId, msg.toolName, msg.input);
|
|
145
|
+
},
|
|
146
|
+
tool_approval_request: (msg, context) => {
|
|
147
|
+
context.state.requestToolApproval(
|
|
148
|
+
context.key,
|
|
149
|
+
msg.toolUseId,
|
|
150
|
+
msg.toolName,
|
|
151
|
+
msg.input,
|
|
152
|
+
msg.description,
|
|
153
|
+
msg.kind
|
|
154
|
+
);
|
|
155
|
+
},
|
|
156
|
+
tool_result: (msg, context) => {
|
|
157
|
+
context.state.setToolResult(context.key, msg.toolUseId, msg.output, msg.isError);
|
|
158
|
+
// Once the agent receives the ask_user tool result, the exchange is
|
|
159
|
+
// complete — drop any leftover ask_user UI state.
|
|
160
|
+
const chat = context.buffer();
|
|
161
|
+
if (chat?.askUser?.answers || chat?.askUser?.cancelled) {
|
|
162
|
+
context.state.clearAskUser(context.key);
|
|
163
|
+
}
|
|
164
|
+
},
|
|
165
|
+
ask_user_request: (msg, context) => {
|
|
166
|
+
context.state.setAskUserRequest(context.key, msg.requestId, msg.questions);
|
|
167
|
+
},
|
|
168
|
+
result: (msg, context) => {
|
|
169
|
+
context.state.finishAssistantMessage(context.key);
|
|
170
|
+
context.resyncIfNeeded(msg.sessionId);
|
|
171
|
+
},
|
|
172
|
+
session_history: (msg, context) => {
|
|
173
|
+
const converted = msg.messages.map(convertHistoryMessage);
|
|
174
|
+
if (msg.append) {
|
|
175
|
+
context.state.appendMessages(context.key, converted);
|
|
176
|
+
} else {
|
|
177
|
+
// First (replacing) chunk = fresh authoritative transcript. Cancel any
|
|
178
|
+
// pending reconnect resync so we don't redundantly re-fetch it, and
|
|
179
|
+
// mark this session cold-resumed so idle-status handling doesn't loop.
|
|
180
|
+
context.state.setMessages(context.key, converted);
|
|
181
|
+
context.markHistoryReplaced(context.key);
|
|
182
|
+
}
|
|
183
|
+
},
|
|
184
|
+
status: (msg, context) => {
|
|
185
|
+
// Only finish streaming if this buffer actually started it
|
|
186
|
+
if (
|
|
187
|
+
(msg.status === "idle" || msg.status === "cancelled") &&
|
|
188
|
+
context.buffer()?.isStreaming
|
|
189
|
+
) {
|
|
190
|
+
context.state.finishAssistantMessage(context.key);
|
|
191
|
+
}
|
|
192
|
+
// A session that finished while we were offline never delivers its
|
|
193
|
+
// `result` — the idle status on reconnect is the cue to resync. Keyed to
|
|
194
|
+
// THIS frame's session: a background session settling must not consume
|
|
195
|
+
// (or trigger) the active session's pending resync.
|
|
196
|
+
if (msg.status === "idle" || msg.status === "cancelled") {
|
|
197
|
+
const current = useChatStore.getState();
|
|
198
|
+
context.resyncIfNeeded(context.frameSessionId ?? current.activeSessionId);
|
|
199
|
+
// Cold load: we hold a stored session id but an empty transcript and
|
|
200
|
+
// the server is idle (so it sent no snapshot). Fetch the history.
|
|
201
|
+
// Only the active session's own (or an unscoped legacy) idle counts.
|
|
202
|
+
if (!context.frameSessionId || context.frameSessionId === current.activeSessionId) {
|
|
203
|
+
context.coldResumeIfNeeded(
|
|
204
|
+
current.activeSessionId,
|
|
205
|
+
activeChat(current).messages.length
|
|
206
|
+
);
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
},
|
|
210
|
+
} satisfies ServerMessageHandlerMap<ChatFrame>;
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { useActivityStore } from "../../stores/activity-store.js";
|
|
2
|
+
import { useConnectionStore } from "../../stores/connection-store.js";
|
|
3
|
+
import type { ServerMessageHandlerMap } from "./types.js";
|
|
4
|
+
|
|
5
|
+
type ConnectionFrame = "server_hello" | "location_request" | "error";
|
|
6
|
+
|
|
7
|
+
export const connectionFrameHandlers = {
|
|
8
|
+
server_hello: (msg, context) => {
|
|
9
|
+
useActivityStore.getState().setSupported(msg.capabilities?.activity === true);
|
|
10
|
+
// A new hello means a new connection: server-side subscriptions are gone.
|
|
11
|
+
useActivityStore.getState().resetSubscriptions();
|
|
12
|
+
// …and view-owned subscriptions (the Activity index) must re-send too.
|
|
13
|
+
useActivityStore.getState().bumpConnectionEpoch();
|
|
14
|
+
context.ensureActivitySubscription(context.state.activeSessionId);
|
|
15
|
+
},
|
|
16
|
+
location_request: (msg, context) => {
|
|
17
|
+
context.requestBrowserLocation(msg);
|
|
18
|
+
},
|
|
19
|
+
error: (msg, context) => {
|
|
20
|
+
// ALWAYS recorded. Appending to the transcript only works while a
|
|
21
|
+
// message is streaming, and this used to be the whole handler — so an
|
|
22
|
+
// error arriving between turns (a rejected frame, a failed resume) was
|
|
23
|
+
// dropped as silently on the client as it was on the server.
|
|
24
|
+
useConnectionStore.getState().reportError(msg.code, msg.message);
|
|
25
|
+
if (context.buffer()?.isStreaming) {
|
|
26
|
+
context.state.appendText(context.key, `\n\n**Error:** ${msg.message}`);
|
|
27
|
+
context.state.finishAssistantMessage(context.key);
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
} satisfies ServerMessageHandlerMap<ConnectionFrame>;
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import type { ServerMessage } from "@schlessera/brain-ui-sdk/protocol";
|
|
2
|
+
import { activityFrameHandlers } from "./activity.js";
|
|
3
|
+
import { chatFrameHandlers } from "./chat.js";
|
|
4
|
+
import { connectionFrameHandlers } from "./connection.js";
|
|
5
|
+
import { maskFrameHandlers } from "./mask.js";
|
|
6
|
+
import { providerFrameHandlers } from "./provider.js";
|
|
7
|
+
import type {
|
|
8
|
+
DispatchContext,
|
|
9
|
+
ServerMessageHandlerMap,
|
|
10
|
+
ServerMessageType,
|
|
11
|
+
} from "./types.js";
|
|
12
|
+
|
|
13
|
+
type HandlerKeys<T> = T extends unknown ? keyof T : never;
|
|
14
|
+
type ClaimedFrame = HandlerKeys<
|
|
15
|
+
| typeof chatFrameHandlers
|
|
16
|
+
| typeof activityFrameHandlers
|
|
17
|
+
| typeof maskFrameHandlers
|
|
18
|
+
| typeof providerFrameHandlers
|
|
19
|
+
| typeof connectionFrameHandlers
|
|
20
|
+
>;
|
|
21
|
+
type DuplicateFrame =
|
|
22
|
+
| Extract<
|
|
23
|
+
keyof typeof chatFrameHandlers,
|
|
24
|
+
| keyof typeof activityFrameHandlers
|
|
25
|
+
| keyof typeof maskFrameHandlers
|
|
26
|
+
| keyof typeof providerFrameHandlers
|
|
27
|
+
| keyof typeof connectionFrameHandlers
|
|
28
|
+
>
|
|
29
|
+
| Extract<
|
|
30
|
+
keyof typeof activityFrameHandlers,
|
|
31
|
+
| keyof typeof maskFrameHandlers
|
|
32
|
+
| keyof typeof providerFrameHandlers
|
|
33
|
+
| keyof typeof connectionFrameHandlers
|
|
34
|
+
>
|
|
35
|
+
| Extract<
|
|
36
|
+
keyof typeof maskFrameHandlers,
|
|
37
|
+
keyof typeof providerFrameHandlers | keyof typeof connectionFrameHandlers
|
|
38
|
+
>
|
|
39
|
+
| Extract<keyof typeof providerFrameHandlers, keyof typeof connectionFrameHandlers>;
|
|
40
|
+
|
|
41
|
+
type Assert<T extends true> = T;
|
|
42
|
+
type Equal<A, B> = [A, B] extends [B, A] ? true : false;
|
|
43
|
+
type _EveryFrameClaimed = Assert<Equal<ClaimedFrame, ServerMessageType>>;
|
|
44
|
+
type _NoFrameClaimedTwice = Assert<Equal<DuplicateFrame, never>>;
|
|
45
|
+
|
|
46
|
+
const serverMessageHandlers = {
|
|
47
|
+
...chatFrameHandlers,
|
|
48
|
+
...activityFrameHandlers,
|
|
49
|
+
...maskFrameHandlers,
|
|
50
|
+
...providerFrameHandlers,
|
|
51
|
+
...connectionFrameHandlers,
|
|
52
|
+
} satisfies ServerMessageHandlerMap<ServerMessageType>;
|
|
53
|
+
|
|
54
|
+
export function dispatchServerMessage(msg: ServerMessage, context: DispatchContext): void {
|
|
55
|
+
// The mapped type preserves the message/handler correlation. TypeScript
|
|
56
|
+
// loses that correlation at an indexed union access, so restore it only at
|
|
57
|
+
// this single composition boundary.
|
|
58
|
+
serverMessageHandlers[msg.type](msg as never, context);
|
|
59
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { useMaskStore } from "../../stores/mask-store.js";
|
|
2
|
+
import type { ServerMessageHandlerMap } from "./types.js";
|
|
3
|
+
|
|
4
|
+
type MaskFrame = "mask_request";
|
|
5
|
+
|
|
6
|
+
export const maskFrameHandlers = {
|
|
7
|
+
mask_request: (msg) => {
|
|
8
|
+
// Opens the editor; the answer travels back from the component, because
|
|
9
|
+
// only the user can say which part of the picture they meant.
|
|
10
|
+
useMaskStore.getState().open({
|
|
11
|
+
requestId: msg.requestId,
|
|
12
|
+
imagePath: msg.imagePath,
|
|
13
|
+
...(msg.instruction ? { instruction: msg.instruction } : {}),
|
|
14
|
+
...(msg.turnId ? { turnId: msg.turnId } : {}),
|
|
15
|
+
});
|
|
16
|
+
},
|
|
17
|
+
} satisfies ServerMessageHandlerMap<MaskFrame>;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { useChatStore } from "../../stores/chat-store.js";
|
|
2
|
+
import { useProviderStore } from "../../stores/provider-store.js";
|
|
3
|
+
import type { ServerMessageHandlerMap } from "./types.js";
|
|
4
|
+
|
|
5
|
+
type ProviderFrame = "session_info";
|
|
6
|
+
|
|
7
|
+
export const providerFrameHandlers = {
|
|
8
|
+
session_info: (msg, context) => {
|
|
9
|
+
context.ensureActivitySubscription(msg.sessionId);
|
|
10
|
+
// Record backend ownership for renderer scoping — for ANY session, since
|
|
11
|
+
// background sessions keep their own transcript buffers. Older servers
|
|
12
|
+
// omit backendId; derive it from the pinned profile when still possible
|
|
13
|
+
// (fails only for since-hidden profiles, which then use the default).
|
|
14
|
+
const ownerBackendId =
|
|
15
|
+
msg.backendId ??
|
|
16
|
+
useProviderStore
|
|
17
|
+
.getState()
|
|
18
|
+
.available.find((p) => p.id === msg.providerId)?.backendId;
|
|
19
|
+
if (ownerBackendId) {
|
|
20
|
+
useChatStore.getState().setSessionBackend(msg.sessionId, ownerBackendId);
|
|
21
|
+
}
|
|
22
|
+
// bindDraftSession in the dispatcher handled draft adoption; an info frame
|
|
23
|
+
// may still re-pin the provider picker when it concerns the session in view.
|
|
24
|
+
const current = useChatStore.getState();
|
|
25
|
+
if (context.frameSessionId && context.frameSessionId === current.activeSessionId) {
|
|
26
|
+
useProviderStore.getState().setPinned(msg.providerId ?? null);
|
|
27
|
+
// Reattachment on a fresh connection: enter streaming mode so deltas
|
|
28
|
+
// append to a live assistant message instead of vanishing.
|
|
29
|
+
const chat = current.buffers[context.frameSessionId];
|
|
30
|
+
if (chat && !chat.isStreaming && chat.messages.length === 0) {
|
|
31
|
+
current.startAssistantMessage(context.frameSessionId);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
},
|
|
35
|
+
} satisfies ServerMessageHandlerMap<ProviderFrame>;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { ServerMessage } from "@schlessera/brain-ui-sdk/protocol";
|
|
2
|
+
import type { ChatKey, SessionChat } from "../../stores/chat-store.js";
|
|
3
|
+
import { useChatStore } from "../../stores/chat-store.js";
|
|
4
|
+
|
|
5
|
+
export type ServerMessageType = ServerMessage["type"];
|
|
6
|
+
|
|
7
|
+
export interface DispatchContext {
|
|
8
|
+
state: ReturnType<typeof useChatStore.getState>;
|
|
9
|
+
frameSessionId: string | undefined;
|
|
10
|
+
key: ChatKey;
|
|
11
|
+
buffer: () => SessionChat | null | undefined;
|
|
12
|
+
enqueueDelta: (key: ChatKey, kind: "text" | "thinking", text: string) => void;
|
|
13
|
+
ensureActivitySubscription: (sessionId: string | null | undefined) => void;
|
|
14
|
+
requestBrowserLocation: (
|
|
15
|
+
msg: Extract<ServerMessage, { type: "location_request" }>
|
|
16
|
+
) => void;
|
|
17
|
+
resyncIfNeeded: (sessionId: string | null) => void;
|
|
18
|
+
coldResumeIfNeeded: (sessionId: string | null, messageCount: number) => void;
|
|
19
|
+
markHistoryReplaced: (key: ChatKey) => void;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export type ServerMessageHandlerMap<T extends ServerMessageType> = {
|
|
23
|
+
[K in T]: (
|
|
24
|
+
msg: Extract<ServerMessage, { type: K }>,
|
|
25
|
+
context: DispatchContext
|
|
26
|
+
) => void;
|
|
27
|
+
};
|
package/src/lib/api-client.ts
CHANGED
|
@@ -81,6 +81,26 @@ export interface BackendInfo {
|
|
|
81
81
|
};
|
|
82
82
|
}
|
|
83
83
|
|
|
84
|
+
/** One active browser/device or delegated agent credential. */
|
|
85
|
+
export interface PrincipalSummary {
|
|
86
|
+
id: string;
|
|
87
|
+
kind: "owner" | "agent" | "ambient" | "system";
|
|
88
|
+
auth_method: "password" | "passkey" | "delegated" | "ambient";
|
|
89
|
+
label: string;
|
|
90
|
+
created_at: number;
|
|
91
|
+
expires_at: number;
|
|
92
|
+
last_seen_at: number | null;
|
|
93
|
+
is_own: boolean;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** The response to minting an agent. `cookie` is intentionally returned once. */
|
|
97
|
+
export interface MintedAgent {
|
|
98
|
+
id: string;
|
|
99
|
+
label: string;
|
|
100
|
+
expiresAt: number;
|
|
101
|
+
cookie: string;
|
|
102
|
+
}
|
|
103
|
+
|
|
84
104
|
/** Auth status of one configured pi provider (mirror of the server view). */
|
|
85
105
|
export interface PiAuthProviderStatus {
|
|
86
106
|
providerId: string;
|
|
@@ -242,13 +262,18 @@ export const api = {
|
|
|
242
262
|
}),
|
|
243
263
|
|
|
244
264
|
brainAdd: (content: string, opts?: { type?: string; title?: string; tags?: string[] }) =>
|
|
245
|
-
fetchJson<{ success: boolean }>("/brain/add", {
|
|
265
|
+
fetchJson<{ success: boolean; path?: string; indexed?: boolean; indexError?: string }>("/brain/add", {
|
|
246
266
|
method: "POST",
|
|
247
267
|
body: JSON.stringify({ content, ...opts }),
|
|
248
268
|
}),
|
|
249
269
|
|
|
270
|
+
brainIndex: () => fetchJson<{ success: boolean }>("/brain/index", {
|
|
271
|
+
method: "POST", body: "{}",
|
|
272
|
+
}),
|
|
273
|
+
|
|
250
274
|
sessions: () =>
|
|
251
275
|
fetchJson<{
|
|
276
|
+
unavailableBackends?: string[];
|
|
252
277
|
sessions: Array<{
|
|
253
278
|
id: string;
|
|
254
279
|
title: string | null;
|
|
@@ -448,6 +473,20 @@ export const api = {
|
|
|
448
473
|
logout: () =>
|
|
449
474
|
fetchJson<{ ok: true }>("/auth/logout", { method: "POST" }),
|
|
450
475
|
|
|
476
|
+
principals: () =>
|
|
477
|
+
fetchJson<{ principals: PrincipalSummary[] }>("/auth/principals"),
|
|
478
|
+
|
|
479
|
+
principalMint: (label: string, ttlDays: number) =>
|
|
480
|
+
fetchJson<MintedAgent>("/auth/principals", {
|
|
481
|
+
method: "POST",
|
|
482
|
+
body: JSON.stringify({ label, ttlDays }),
|
|
483
|
+
}),
|
|
484
|
+
|
|
485
|
+
principalRevoke: (id: string) =>
|
|
486
|
+
fetchJson<{ ok: true }>(`/auth/principals/${encodeURIComponent(id)}`, {
|
|
487
|
+
method: "DELETE",
|
|
488
|
+
}),
|
|
489
|
+
|
|
451
490
|
/** Which login methods the server offers (public; drives the login screen). */
|
|
452
491
|
authMethods: () =>
|
|
453
492
|
fetchJson<{ password: boolean; passkey: boolean }>("/auth/methods"),
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/** Relative timestamp for list rows ("3m ago"); dates beyond a week. */
|
|
2
|
+
export function formatRelativeTime(ms: number): string {
|
|
3
|
+
const diff = Date.now() - ms;
|
|
4
|
+
const future = diff < 0;
|
|
5
|
+
const distance = Math.abs(diff);
|
|
6
|
+
if (distance < 60_000) return future ? "in less than a minute" : "just now";
|
|
7
|
+
const minutes = future
|
|
8
|
+
? Math.ceil(distance / 60_000)
|
|
9
|
+
: Math.floor(distance / 60_000);
|
|
10
|
+
if (minutes < 60) return future ? `in ${minutes}m` : `${minutes}m ago`;
|
|
11
|
+
const hours = future
|
|
12
|
+
? Math.ceil(distance / 3_600_000)
|
|
13
|
+
: Math.floor(distance / 3_600_000);
|
|
14
|
+
if (hours < 24) return future ? `in ${hours}h` : `${hours}h ago`;
|
|
15
|
+
const days = future
|
|
16
|
+
? Math.ceil(distance / 86_400_000)
|
|
17
|
+
: Math.floor(distance / 86_400_000);
|
|
18
|
+
if (days < 7) return future ? `in ${days}d` : `${days}d ago`;
|
|
19
|
+
return new Date(ms).toLocaleDateString();
|
|
20
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { api } from "./api-client.js";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Re-assert an existing browser subscription after authentication changes.
|
|
5
|
+
* This does not request permission or create a subscription: it only binds an
|
|
6
|
+
* already-enabled endpoint to the newly issued server principal.
|
|
7
|
+
*/
|
|
8
|
+
export async function rebindPushSubscriptionAfterLogin(): Promise<void> {
|
|
9
|
+
if (
|
|
10
|
+
typeof Notification === "undefined" ||
|
|
11
|
+
Notification.permission !== "granted" ||
|
|
12
|
+
typeof navigator === "undefined" ||
|
|
13
|
+
!("serviceWorker" in navigator)
|
|
14
|
+
) {
|
|
15
|
+
return;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// Capture before awaiting: the page may begin navigating immediately after
|
|
19
|
+
// login while the service-worker readiness promise settles.
|
|
20
|
+
const serviceWorker = navigator.serviceWorker;
|
|
21
|
+
const label =
|
|
22
|
+
typeof navigator.userAgent === "string"
|
|
23
|
+
? navigator.userAgent.slice(0, 100)
|
|
24
|
+
: undefined;
|
|
25
|
+
const registration = await serviceWorker.ready;
|
|
26
|
+
const subscription = await registration.pushManager.getSubscription();
|
|
27
|
+
if (!subscription) return;
|
|
28
|
+
await api.pushSubscribe(subscription.toJSON(), label);
|
|
29
|
+
}
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
import type { ActivitySpan, ActivitySpanEvent } from "@schlessera/brain-ui-sdk/protocol";
|
|
2
|
+
import type { ActivityState, MirrorMaps } from "./activity-store-types.js";
|
|
3
|
+
|
|
4
|
+
/** Bound on the mirror: how many TERMINAL runs stay held. Live runs never count. */
|
|
5
|
+
const MAX_TERMINAL_RUNS = 50;
|
|
6
|
+
|
|
7
|
+
export function rootSpanOf(byId: Record<string, ActivitySpan>): ActivitySpan | undefined {
|
|
8
|
+
return Object.values(byId).find((span) => span.parentSpanId === undefined);
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** Drop a whole run from the mirror — spans, events, high-water, reverse index. */
|
|
12
|
+
export function evictRun(maps: MirrorMaps, runId: string): void {
|
|
13
|
+
for (const spanId of Object.keys(maps.spans[runId] ?? {})) {
|
|
14
|
+
delete maps.events[spanId];
|
|
15
|
+
delete maps.spanRun[spanId];
|
|
16
|
+
}
|
|
17
|
+
delete maps.spans[runId];
|
|
18
|
+
delete maps.highWater[runId];
|
|
19
|
+
delete maps.deltaSeq[runId];
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Enforce the terminal-run bound in place. Returns whether anything was
|
|
24
|
+
* evicted. Runs whose root span is still open (or unknown) are never touched.
|
|
25
|
+
*/
|
|
26
|
+
export function pruneTerminalRuns(maps: MirrorMaps): boolean {
|
|
27
|
+
const terminal: Array<{ runId: string; startedAt: number }> = [];
|
|
28
|
+
for (const [runId, byId] of Object.entries(maps.spans)) {
|
|
29
|
+
const root = rootSpanOf(byId);
|
|
30
|
+
if (root && root.outcome !== undefined) {
|
|
31
|
+
terminal.push({ runId, startedAt: root.startedAt });
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
if (terminal.length <= MAX_TERMINAL_RUNS) return false;
|
|
35
|
+
terminal.sort((a, b) => a.startedAt - b.startedAt);
|
|
36
|
+
for (const { runId } of terminal.slice(0, terminal.length - MAX_TERMINAL_RUNS)) {
|
|
37
|
+
evictRun(maps, runId);
|
|
38
|
+
}
|
|
39
|
+
return true;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function insertEvent(
|
|
43
|
+
list: ActivitySpanEvent[] | undefined,
|
|
44
|
+
event: ActivitySpanEvent
|
|
45
|
+
): ActivitySpanEvent[] {
|
|
46
|
+
const existing = list ?? [];
|
|
47
|
+
if (existing.some((e) => e.eventIndex === event.eventIndex)) return existing;
|
|
48
|
+
const next = [...existing, event];
|
|
49
|
+
next.sort((a, b) => a.eventIndex - b.eventIndex);
|
|
50
|
+
return next;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// --- Selectors (plain functions over the state, like activeChat) ---
|
|
54
|
+
|
|
55
|
+
/** All spans of a run, roots first, then by start time. */
|
|
56
|
+
export function runSpans(state: ActivityState, runId: string): ActivitySpan[] {
|
|
57
|
+
const byId = state.spans[runId];
|
|
58
|
+
if (!byId) return [];
|
|
59
|
+
return Object.values(byId).sort(
|
|
60
|
+
(a, b) =>
|
|
61
|
+
(a.parentSpanId ? 1 : 0) - (b.parentSpanId ? 1 : 0) || a.startedAt - b.startedAt
|
|
62
|
+
);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Direct children of a span (e.g. the tool calls inside a subagent). */
|
|
66
|
+
export function childSpans(state: ActivityState, parentSpanId: string): ActivitySpan[] {
|
|
67
|
+
const runId = state.spanRun[parentSpanId];
|
|
68
|
+
if (!runId) return [];
|
|
69
|
+
return Object.values(state.spans[runId] ?? {})
|
|
70
|
+
.filter((s) => s.parentSpanId === parentSpanId)
|
|
71
|
+
.sort((a, b) => a.startedAt - b.startedAt);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** The subagent spans spawned by a turn's Agent tool calls, live status included. */
|
|
75
|
+
export function subagentSpans(state: ActivityState, sessionId: string): ActivitySpan[] {
|
|
76
|
+
const out: ActivitySpan[] = [];
|
|
77
|
+
for (const byId of Object.values(state.spans)) {
|
|
78
|
+
for (const span of Object.values(byId)) {
|
|
79
|
+
if (span.kind === "subagent" && span.sessionId === sessionId) out.push(span);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
return out.sort((a, b) => a.startedAt - b.startedAt);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Stable empty result for `eventsFor` — a fresh `[]` per call would defeat
|
|
86
|
+
* reference-equality checks in zustand selectors. */
|
|
87
|
+
export const EMPTY_EVENTS: ActivitySpanEvent[] = Object.freeze(
|
|
88
|
+
[] as ActivitySpanEvent[]
|
|
89
|
+
) as ActivitySpanEvent[];
|
|
90
|
+
|
|
91
|
+
/** Ordered events of a span; the shared frozen empty array when none. */
|
|
92
|
+
export function eventsFor(state: ActivityState, spanId: string): ActivitySpanEvent[] {
|
|
93
|
+
return state.events[spanId] ?? EMPTY_EVENTS;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Payload event types the tool expander owns — every OTHER type belongs to
|
|
97
|
+
* the narrative stream (`narrativeEventsFor`) so nothing recorded is
|
|
98
|
+
* rendered nowhere. */
|
|
99
|
+
const TOOL_PAYLOAD_TYPES = new Set(["tool_input", "tool_output"]);
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* The recorded input/output payload events of a tool span (AE7). Returns a
|
|
103
|
+
* fresh array per call — subscribe through `useShallow` (like `childSpans`).
|
|
104
|
+
*/
|
|
105
|
+
export function payloadEventsFor(state: ActivityState, spanId: string): ActivitySpanEvent[] {
|
|
106
|
+
const events = state.events[spanId];
|
|
107
|
+
if (!events) return EMPTY_EVENTS;
|
|
108
|
+
const payloads = events.filter((e) => TOOL_PAYLOAD_TYPES.has(e.eventType));
|
|
109
|
+
return payloads.length > 0 ? payloads : EMPTY_EVENTS;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Everything recorded against a span that is NOT a tool input/output payload:
|
|
114
|
+
* transcript excerpts, job output, and any span-sink event type a producer
|
|
115
|
+
* invents. Rendered as the span's narrative so an unknown type degrades to a
|
|
116
|
+
* labelled block rather than to invisibility.
|
|
117
|
+
*/
|
|
118
|
+
export function narrativeEventsFor(
|
|
119
|
+
state: ActivityState,
|
|
120
|
+
spanId: string
|
|
121
|
+
): ActivitySpanEvent[] {
|
|
122
|
+
const events = state.events[spanId];
|
|
123
|
+
if (!events) return EMPTY_EVENTS;
|
|
124
|
+
const rest = events.filter((e) => !TOOL_PAYLOAD_TYPES.has(e.eventType));
|
|
125
|
+
return rest.length > 0 ? rest : EMPTY_EVENTS;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** Every event recorded under a run, ordered by time — the run detail's
|
|
129
|
+
* narrative stream and the raw-trace dump both read through this. */
|
|
130
|
+
export function runEvents(state: ActivityState, runId: string): ActivitySpanEvent[] {
|
|
131
|
+
const byId = state.spans[runId];
|
|
132
|
+
if (!byId) return EMPTY_EVENTS;
|
|
133
|
+
const out: ActivitySpanEvent[] = [];
|
|
134
|
+
for (const spanId of Object.keys(byId)) {
|
|
135
|
+
const events = state.events[spanId];
|
|
136
|
+
if (events) out.push(...events);
|
|
137
|
+
}
|
|
138
|
+
if (out.length === 0) return EMPTY_EVENTS;
|
|
139
|
+
return out.sort((a, b) => a.ts - b.ts || a.eventIndex - b.eventIndex);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** The span behind one tool call (span ids ARE toolUseIds), if streamed. */
|
|
143
|
+
export function spanForTool(state: ActivityState, toolUseId: string): ActivitySpan | null {
|
|
144
|
+
const runId = state.spanRun[toolUseId];
|
|
145
|
+
return runId ? (state.spans[runId]?.[toolUseId] ?? null) : null;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Server-stamped timing for a tool call. One clock for live and reloaded
|
|
150
|
+
* views: when the activity stream carries the span, its timestamps win over
|
|
151
|
+
* client stamps (AE2 — live and revisit must render identical timings).
|
|
152
|
+
* `waitUntil` marks the approval-wait/execution boundary.
|
|
153
|
+
*/
|
|
154
|
+
export function timingFor(
|
|
155
|
+
state: ActivityState,
|
|
156
|
+
toolUseId: string
|
|
157
|
+
): { startedAt: number; endedAt?: number } | null {
|
|
158
|
+
const span = spanForTool(state, toolUseId);
|
|
159
|
+
if (!span) return null;
|
|
160
|
+
return {
|
|
161
|
+
startedAt: span.waitUntil ?? span.startedAt,
|
|
162
|
+
...(span.endedAt !== undefined ? { endedAt: span.endedAt } : {}),
|
|
163
|
+
};
|
|
164
|
+
}
|