@causyne/agent 1.20.124 → 1.20.128

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 (254) hide show
  1. package/bin/causyne.js +1 -1
  2. package/docs/THIRD_PARTY_NOTICES.md +36 -2
  3. package/package.json +6 -4
  4. package/src/acp/protocol.ts +19 -1
  5. package/src/acp/server.js +282 -8
  6. package/src/acp/server.ts +284 -8
  7. package/src/agent/abortableDelay.js +2 -2
  8. package/src/agent/abortableDelay.ts +2 -2
  9. package/src/agent/errorClassifier.js +9 -1
  10. package/src/agent/errorClassifier.ts +8 -1
  11. package/src/agentLoop.js +142 -53
  12. package/src/agentLoop.ts +151 -50
  13. package/src/approvalPolicy.js +34 -10
  14. package/src/approvalPolicy.ts +42 -11
  15. package/src/browser/causyneBrowser.js +61 -3
  16. package/src/browser/causyneBrowser.ts +65 -3
  17. package/src/browser/urlPolicy.js +14 -1
  18. package/src/browser/urlPolicy.ts +12 -1
  19. package/src/cliMode.js +21 -9
  20. package/src/cliMode.ts +20 -8
  21. package/src/commands.js +365 -45
  22. package/src/commands.ts +403 -45
  23. package/src/config.js +19 -4
  24. package/src/config.ts +18 -4
  25. package/src/core/contextCompactor.js +54 -7
  26. package/src/core/contextCompactor.ts +63 -7
  27. package/src/core/goalLoop.js +257 -0
  28. package/src/core/goalLoop.ts +310 -0
  29. package/src/entrypoint.js +135 -3
  30. package/src/entrypoint.ts +136 -3
  31. package/src/game/causyneCoreBridge.js +686 -0
  32. package/src/game/causyneCoreBridge.ts +702 -0
  33. package/src/game/gameLauncher.js +287 -0
  34. package/src/game/gameLauncher.ts +352 -0
  35. package/src/game/gameProvisioner.js +425 -0
  36. package/src/game/gameProvisioner.ts +488 -0
  37. package/src/headlessCli.js +19 -12
  38. package/src/headlessCli.ts +22 -8
  39. package/src/infra/atomicWriter.js +40 -4
  40. package/src/infra/atomicWriter.ts +36 -4
  41. package/src/launchIntent.js +73 -3
  42. package/src/launchIntent.ts +76 -3
  43. package/src/lsp/lspClient.js +83 -12
  44. package/src/lsp/lspClient.ts +75 -12
  45. package/src/mcp/mcpRegistry.js +75 -8
  46. package/src/mcp/mcpRegistry.ts +70 -7
  47. package/src/memory/contextBudget.js +2 -0
  48. package/src/memory/contextBudget.ts +1 -0
  49. package/src/memory/episodicStore.js +40 -0
  50. package/src/memory/episodicStore.ts +46 -0
  51. package/src/memory.js +67 -0
  52. package/src/memory.ts +65 -0
  53. package/src/modelVariants.js +45 -0
  54. package/src/modelVariants.ts +54 -0
  55. package/src/outputRecovery.js +3 -2
  56. package/src/outputRecovery.ts +4 -2
  57. package/src/permissionPresets.js +327 -0
  58. package/src/permissionPresets.ts +361 -0
  59. package/src/personalization.js +365 -0
  60. package/src/personalization.ts +471 -0
  61. package/src/projectInstructions.js +30 -10
  62. package/src/projectInstructions.ts +31 -12
  63. package/src/providers/acp.js +3 -2
  64. package/src/providers/acp.ts +3 -2
  65. package/src/providers/antigravity.js +64 -9
  66. package/src/providers/antigravity.ts +75 -9
  67. package/src/providers/byokHttp.js +7 -1
  68. package/src/providers/byokHttp.ts +6 -1
  69. package/src/providers/byokStream.js +21 -8
  70. package/src/providers/byokStream.ts +17 -7
  71. package/src/providers/dashscope-byok.js +21 -5
  72. package/src/providers/dashscope-byok.ts +29 -11
  73. package/src/providers/moonshot.js +26 -7
  74. package/src/providers/moonshot.ts +34 -13
  75. package/src/providers/muse.js +6 -0
  76. package/src/providers/muse.ts +8 -0
  77. package/src/providers/ollama.js +39 -7
  78. package/src/providers/ollama.ts +36 -7
  79. package/src/providers/openai-compatible.js +16 -3
  80. package/src/providers/openai-compatible.ts +13 -3
  81. package/src/providers/openai.js +62 -4
  82. package/src/providers/openai.ts +50 -4
  83. package/src/providers/openrouter.js +19 -4
  84. package/src/providers/openrouter.ts +21 -4
  85. package/src/providers/qwen-byok.js +21 -5
  86. package/src/providers/qwen-byok.ts +29 -11
  87. package/src/providers/xai.js +26 -10
  88. package/src/providers/xai.ts +34 -16
  89. package/src/reporting.js +4 -2
  90. package/src/reporting.ts +4 -2
  91. package/src/sandbox.js +34 -0
  92. package/src/sandbox.ts +43 -0
  93. package/src/scheduler/scheduler.js +372 -0
  94. package/src/scheduler/scheduler.ts +433 -0
  95. package/src/sessionSearchIndex.js +267 -0
  96. package/src/sessionSearchIndex.ts +311 -0
  97. package/src/skillsManager.js +2 -3
  98. package/src/skillsManager.ts +2 -3
  99. package/src/toolPacks.js +6 -0
  100. package/src/toolPacks.ts +6 -0
  101. package/src/tools/applyPatch.js +1 -1
  102. package/src/tools/applyPatch.ts +1 -1
  103. package/src/tools/generateMediaViaApi.js +4 -3
  104. package/src/tools/generateMediaViaApi.ts +4 -3
  105. package/src/tools/memoryWrite.js +15 -1
  106. package/src/tools/memoryWrite.ts +16 -1
  107. package/src/tools/nativeEngine.js +2 -2
  108. package/src/tools/nativeEngine.ts +2 -2
  109. package/src/tools/openSourceToolProvisioner.js +2 -2
  110. package/src/tools/openSourceToolProvisioner.ts +2 -2
  111. package/src/tools/osSandbox.js +1 -1
  112. package/src/tools/osSandbox.ts +1 -1
  113. package/src/tools/payloadSanitizer.js +0 -1
  114. package/src/tools/payloadSanitizer.ts +0 -1
  115. package/src/tools/pdfReader.js +122 -20
  116. package/src/tools/pdfReader.ts +111 -20
  117. package/src/tools/presentDeliverable.js +103 -0
  118. package/src/tools/presentDeliverable.ts +127 -0
  119. package/src/tools/ptcRuntime.js +444 -0
  120. package/src/tools/ptcRuntime.ts +490 -0
  121. package/src/tools/ptyTerminal.js +1108 -0
  122. package/src/tools/ptyTerminal.ts +1245 -0
  123. package/src/tools/registry.js +21 -12
  124. package/src/tools/registry.ts +21 -12
  125. package/src/tools/toolOutputStore.js +26 -4
  126. package/src/tools/toolOutputStore.ts +22 -4
  127. package/src/tools/webFetch.js +158 -11
  128. package/src/tools/webFetch.ts +145 -11
  129. package/src/tools/webSearch.js +123 -36
  130. package/src/tools/webSearch.ts +124 -33
  131. package/src/tui/banner.js +5 -1
  132. package/src/tui/banner.ts +6 -1
  133. package/src/tui/chatRenderer.js +1 -2
  134. package/src/tui/chatRenderer.ts +1 -2
  135. package/src/tui/completion.js +1 -0
  136. package/src/tui/completion.ts +1 -0
  137. package/src/tui/composerControls.js +111 -27
  138. package/src/tui/composerControls.ts +124 -28
  139. package/src/tui/dialogs.js +3 -16
  140. package/src/tui/dialogs.ts +3 -16
  141. package/src/tui/home.js +1 -0
  142. package/src/tui/home.ts +1 -0
  143. package/src/tui/invocation.js +1 -2
  144. package/src/tui/invocation.ts +1 -2
  145. package/src/tui/modelPicker.js +22 -12
  146. package/src/tui/modelPicker.ts +22 -12
  147. package/src/tui/overlay.js +2 -5
  148. package/src/tui/overlay.ts +2 -5
  149. package/src/tui/prompt.js +6 -4
  150. package/src/tui/prompt.ts +6 -4
  151. package/src/tui/selectList.js +4 -12
  152. package/src/tui/selectList.ts +4 -12
  153. package/src/tui/setup.js +22 -9
  154. package/src/tui/setup.ts +26 -9
  155. package/src/tui/statusLine.ts +2 -0
  156. package/src/web/client/browserPanel.js +905 -0
  157. package/src/web/client/browserPanel.ts +872 -0
  158. package/src/web/client/chatStream.js +321 -0
  159. package/src/web/client/chatStream.ts +297 -0
  160. package/src/web/client/cliPanel.js +165 -0
  161. package/src/web/client/cliPanel.ts +171 -0
  162. package/src/web/client/composer.js +204 -0
  163. package/src/web/client/composer.ts +209 -0
  164. package/src/web/client/diffPanel.js +176 -0
  165. package/src/web/client/diffPanel.ts +203 -0
  166. package/src/web/client/dom.js +271 -0
  167. package/src/web/client/dom.ts +272 -0
  168. package/src/web/client/filesAndCanvas.js +233 -0
  169. package/src/web/client/filesAndCanvas.ts +240 -0
  170. package/src/web/client/gameLauncherUi.js +78 -0
  171. package/src/web/client/gameLauncherUi.ts +78 -0
  172. package/src/web/client/main.js +316 -0
  173. package/src/web/client/main.ts +391 -0
  174. package/src/web/client/markdown.js +364 -0
  175. package/src/web/client/markdown.ts +373 -0
  176. package/src/web/client/modelPicker.js +455 -0
  177. package/src/web/client/modelPicker.ts +451 -0
  178. package/src/web/client/permissionPresetsUi.js +307 -0
  179. package/src/web/client/permissionPresetsUi.ts +333 -0
  180. package/src/web/client/sessions.js +353 -0
  181. package/src/web/client/sessions.ts +372 -0
  182. package/src/web/client/settingsModal.js +824 -0
  183. package/src/web/client/settingsModal.ts +959 -0
  184. package/src/web/client/state.js +280 -0
  185. package/src/web/client/state.ts +259 -0
  186. package/src/web/client/streamSmoother.js +127 -0
  187. package/src/web/client/streamSmoother.ts +119 -0
  188. package/src/web/client/studioLayout.js +89 -0
  189. package/src/web/client/studioLayout.ts +103 -0
  190. package/src/web/client/studioShell.js +660 -0
  191. package/src/web/client/studioShell.ts +672 -0
  192. package/src/web/client/studioStart.js +77 -0
  193. package/src/web/client/studioStart.ts +89 -0
  194. package/src/web/client/terminalPanel.js +606 -0
  195. package/src/web/client/terminalPanel.ts +632 -0
  196. package/src/web/client/terminalTheme.js +249 -0
  197. package/src/web/client/terminalTheme.ts +258 -0
  198. package/src/web/client/turnView.js +934 -0
  199. package/src/web/client/turnView.ts +981 -0
  200. package/src/web/client/types.js +1 -0
  201. package/src/web/client/types.ts +322 -0
  202. package/src/web/client/validators.js +147 -0
  203. package/src/web/client/validators.ts +140 -0
  204. package/src/web/server/activeRuns.js +152 -0
  205. package/src/web/server/activeRuns.ts +171 -0
  206. package/src/web/server/routesBrowser.js +409 -0
  207. package/src/web/server/routesBrowser.ts +435 -0
  208. package/src/web/server/routesChat.js +304 -0
  209. package/src/web/server/routesChat.ts +347 -0
  210. package/src/web/server/routesCore.js +472 -0
  211. package/src/web/server/routesCore.ts +522 -0
  212. package/src/web/server/routesSettings.js +344 -0
  213. package/src/web/server/routesSettings.ts +397 -0
  214. package/src/web/server/routesTerminal.js +162 -0
  215. package/src/web/server/routesTerminal.ts +182 -0
  216. package/src/web/server/routesWorkspace.js +510 -0
  217. package/src/web/server/routesWorkspace.ts +546 -0
  218. package/src/web/server/security.js +98 -0
  219. package/src/web/server/security.ts +108 -0
  220. package/src/web/server/sessionTranscript.js +586 -0
  221. package/src/web/server/sessionTranscript.ts +566 -0
  222. package/src/web/server/staticAssets.js +104 -0
  223. package/src/web/server/staticAssets.ts +116 -0
  224. package/src/web/server/types.js +1 -0
  225. package/src/web/server/types.ts +135 -0
  226. package/src/web/server/workspaceFiles.js +368 -0
  227. package/src/web/server/workspaceFiles.ts +363 -0
  228. package/src/web/skybridgeServer.js +78 -2448
  229. package/src/web/skybridgeServer.ts +120 -2600
  230. package/src/web/skybridgeUi.js +20 -450
  231. package/src/web/skybridgeUi.ts +24 -455
  232. package/src/web/styles/agent.css +380 -0
  233. package/src/web/styles/composer.css +193 -0
  234. package/src/web/styles/overlays.css +935 -0
  235. package/src/web/styles/shell.css +387 -0
  236. package/src/web/styles/studio.css +951 -0
  237. package/src/web/styles/thread.css +221 -0
  238. package/src/web/styles/tokens.css +94 -0
  239. package/src/web/ui/brandMark.js +73 -0
  240. package/src/web/ui/brandMark.ts +82 -0
  241. package/src/web/ui/modalsTemplate.js +388 -0
  242. package/src/web/ui/modalsTemplate.ts +388 -0
  243. package/src/web/ui/sidebarTemplate.js +63 -0
  244. package/src/web/ui/sidebarTemplate.ts +64 -0
  245. package/src/web/ui/studioTemplate.js +256 -0
  246. package/src/web/ui/studioTemplate.ts +256 -0
  247. package/src/web/ui/workspaceTemplate.js +72 -0
  248. package/src/web/ui/workspaceTemplate.ts +73 -0
  249. package/src/worktreeManager.js +16 -1
  250. package/src/worktreeManager.ts +22 -1
  251. package/src/web/skybridgeClientScript.js +0 -3951
  252. package/src/web/skybridgeClientScript.ts +0 -3952
  253. package/src/web/skybridgeStyles.js +0 -827
  254. package/src/web/skybridgeStyles.ts +0 -828
@@ -0,0 +1,372 @@
1
+ import { dom } from './dom.js';
2
+ import {
3
+ apiUrl,
4
+ authHeaders,
5
+ scrollToBottom,
6
+ setLiveness,
7
+ setStageMode,
8
+ state,
9
+ syncUsagePill,
10
+ updateComposerMetrics
11
+ } from './state.js';
12
+ import { renderAttachmentChips } from './composer.js';
13
+ import { loadFiles, setCanvasPreviewMode, syncArtifactVersionSelect } from './filesAndCanvas.js';
14
+ import { loadDiff, syncDiffControlsUi } from './diffPanel.js';
15
+ import { refreshLiveBrowserState, setBrowserEngine, startLiveBrowserStream } from './browserPanel.js';
16
+ import { loadCliOverview } from './cliPanel.js';
17
+ import { appendUserTurn, createAssistantTurn, resetThreadSpacer } from './turnView.js';
18
+ import { loadPermissionPresets, syncPermissionPresetLock } from './permissionPresetsUi.js';
19
+ import type { RestoredBlock, RestoredStep, SessionSummary } from './types.js';
20
+
21
+ export interface SessionsCallbacks {
22
+ attachToActiveSessionStream(sessionId: string, promptForRetry: string, runSeq: number): Promise<void>;
23
+ }
24
+
25
+ let callbacks: SessionsCallbacks = {
26
+ attachToActiveSessionStream: async () => {}
27
+ };
28
+
29
+ export function configureSessionsCallbacks(cbs: SessionsCallbacks): void {
30
+ callbacks = cbs;
31
+ }
32
+
33
+ function sessionKey(id: string | null): string {
34
+ return id || '__draft__';
35
+ }
36
+
37
+ function bucketLabel(ts: number): string {
38
+ const now = new Date();
39
+ const startToday = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
40
+ const dayMs = 86400000;
41
+ if (ts >= startToday) return 'Today';
42
+ if (ts >= startToday - dayMs) return 'Yesterday';
43
+ if (ts >= startToday - 7 * dayMs) return 'Previous 7 days';
44
+ return 'Older';
45
+ }
46
+
47
+ function updateActiveSessionRow(activeId: string | null): void {
48
+ dom.sessionListEl.querySelectorAll<HTMLElement>('.session-item').forEach((elItem) => {
49
+ elItem.classList.toggle('active', Boolean(activeId && elItem.dataset.sessionId === activeId));
50
+ });
51
+ }
52
+
53
+ export function startInlineSessionRename(
54
+ item: HTMLElement,
55
+ titleBtn: HTMLButtonElement,
56
+ s: SessionSummary
57
+ ): void {
58
+ const input = document.createElement('input');
59
+ input.type = 'text';
60
+ input.className = 'session-rename-input';
61
+ input.value = s.title || '';
62
+ input.maxLength = 80;
63
+ titleBtn.style.display = 'none';
64
+ item.insertBefore(input, titleBtn);
65
+ input.focus();
66
+ input.select();
67
+ let finished = false;
68
+ const finish = async (save: boolean): Promise<void> => {
69
+ if (finished) return;
70
+ finished = true;
71
+ const next = (input.value || '').trim();
72
+ input.remove();
73
+ titleBtn.style.display = '';
74
+ if (!save || !next || next === s.title) return;
75
+ s.title = next;
76
+ titleBtn.textContent = next;
77
+ await fetch(apiUrl(`/api/sessions/${encodeURIComponent(s.id)}`), {
78
+ method: 'PATCH',
79
+ headers: authHeaders({ 'Content-Type': 'application/json' }),
80
+ body: JSON.stringify({ title: next })
81
+ }).catch(() => {});
82
+ };
83
+ input.addEventListener('click', (ev) => ev.stopPropagation());
84
+ input.addEventListener('keydown', (ev) => {
85
+ if (ev.key === 'Enter') { ev.preventDefault(); ev.stopPropagation(); void finish(true); }
86
+ else if (ev.key === 'Escape') { ev.preventDefault(); ev.stopPropagation(); void finish(false); }
87
+ });
88
+ input.addEventListener('blur', () => { void finish(true); });
89
+ }
90
+
91
+ export function renderSessionList(): void {
92
+ const prevScroll = dom.sessionListEl.scrollTop;
93
+ const q = (dom.sessionSearchEl.value || '').trim().toLowerCase();
94
+ const filtered = state.sessions.filter((s) => !q || String(s.title || '').toLowerCase().includes(q));
95
+ dom.sessionListEl.textContent = '';
96
+ if (filtered.length === 0) {
97
+ const empty = document.createElement('div');
98
+ empty.className = 'session-empty';
99
+ empty.textContent = q ? 'No matching chats.' : 'No saved workspace chats yet.';
100
+ dom.sessionListEl.appendChild(empty);
101
+ return;
102
+ }
103
+ let currentGroup = '';
104
+ for (const s of filtered) {
105
+ const grp = bucketLabel(s.updatedAt || s.createdAt || 0);
106
+ if (grp !== currentGroup) {
107
+ currentGroup = grp;
108
+ const gl = document.createElement('div');
109
+ gl.className = 'session-group-label';
110
+ gl.textContent = grp;
111
+ dom.sessionListEl.appendChild(gl);
112
+ }
113
+ const item = document.createElement('div');
114
+ item.dataset.sessionId = s.id;
115
+ item.className = `session-item${s.id === state.sessionId ? ' active' : ''}`;
116
+ item.addEventListener('click', () => { void loadSessionTranscript(s.id); });
117
+ if (s.running) {
118
+ const dot = document.createElement('span');
119
+ dot.className = `session-run-dot${s.awaitingClient ? ' awaiting' : ''}`;
120
+ dot.title = s.awaitingClient ? 'Waiting for your input' : 'Running in background';
121
+ item.appendChild(dot);
122
+ }
123
+ const titleBtn = document.createElement('button');
124
+ titleBtn.type = 'button';
125
+ titleBtn.className = 'session-title';
126
+ titleBtn.textContent = s.title || 'Untitled';
127
+ titleBtn.title = s.title || 'Untitled';
128
+
129
+ const actions = document.createElement('div');
130
+ actions.className = 'session-actions';
131
+ const renBtn = document.createElement('button');
132
+ renBtn.type = 'button';
133
+ renBtn.className = 'mini-icon-btn';
134
+ renBtn.textContent = 'R';
135
+ renBtn.title = 'Rename';
136
+ renBtn.addEventListener('click', (e) => {
137
+ e.stopPropagation();
138
+ startInlineSessionRename(item, titleBtn, s);
139
+ });
140
+ const delBtn = document.createElement('button');
141
+ delBtn.type = 'button';
142
+ delBtn.className = 'mini-icon-btn';
143
+ delBtn.textContent = 'x';
144
+ delBtn.title = 'Delete';
145
+ delBtn.addEventListener('click', async (e) => {
146
+ e.stopPropagation();
147
+ await fetch(apiUrl(`/api/sessions/${encodeURIComponent(s.id)}`), {
148
+ method: 'DELETE',
149
+ headers: authHeaders()
150
+ }).catch(() => {});
151
+ state.sessionWorkspaces.delete(s.id);
152
+ if (state.sessionId === s.id) void startFreshChat();
153
+ void loadSessions();
154
+ });
155
+ actions.appendChild(renBtn);
156
+ actions.appendChild(delBtn);
157
+ item.appendChild(titleBtn);
158
+ item.appendChild(actions);
159
+ dom.sessionListEl.appendChild(item);
160
+ }
161
+ dom.sessionListEl.scrollTop = prevScroll;
162
+ }
163
+
164
+ export async function loadSessions(): Promise<void> {
165
+ const res = await fetch(apiUrl('/api/sessions'), { headers: authHeaders() });
166
+ if (!res.ok) return;
167
+ const data = await res.json() as { sessions?: SessionSummary[] };
168
+ state.sessions = data.sessions || [];
169
+ renderSessionList();
170
+ }
171
+
172
+ export function saveCurrentSessionWorkspace(): void {
173
+ const key = sessionKey(state.sessionId);
174
+ state.sessionWorkspaces.set(key, {
175
+ studioOpen: dom.appEl.classList.contains('studio-open'),
176
+ studioTab: state.studioTab,
177
+ canvasPath: dom.filePathInput.value || '',
178
+ canvasContent: dom.fileContentInput.value || '',
179
+ canvasPreviewMode: Boolean(state.canvasPreviewMode),
180
+ canvasStatus: dom.fileStatusEl.textContent || 'Ready',
181
+ canvasDirty: Boolean(state.canvasDirty),
182
+ diffScope: state.diffScope,
183
+ diffStaged: Boolean(state.diffStaged),
184
+ attachments: state.attachments.slice(),
185
+ draftPrompt: dom.promptInput.value || '',
186
+ usageTokens: state.usageTokens,
187
+ browserEngine: state.browserEngine,
188
+ browserMode: state.browserMode,
189
+ browserUrl: state.browserUrl,
190
+ browserSrcdoc: state.browserSrcdoc,
191
+ cliConsoleText: dom.cliConsoleEl.textContent || 'Select a command above or type /help.',
192
+ cliStatusText: dom.cliStatusEl.textContent || 'Ready'
193
+ });
194
+ }
195
+
196
+ export function applySessionWorkspace(nextSessionId: string | null): void {
197
+ const key = sessionKey(nextSessionId);
198
+ const saved = state.sessionWorkspaces.get(key) || null;
199
+ state.attachments = saved ? saved.attachments.slice() : [];
200
+ renderAttachmentChips();
201
+ dom.promptInput.value = saved ? saved.draftPrompt : '';
202
+ updateComposerMetrics();
203
+ syncUsagePill(saved ? saved.usageTokens : 0);
204
+ dom.filePathInput.value = saved ? saved.canvasPath : '';
205
+ dom.fileContentInput.value = saved ? saved.canvasContent : '';
206
+ state.canvasDirty = saved ? Boolean(saved.canvasDirty) : false;
207
+ dom.fileStatusEl.textContent = saved ? saved.canvasStatus : 'Ready';
208
+ dom.canvasHtmlFrame.removeAttribute('srcdoc');
209
+ dom.canvasPreviewEl.textContent = '';
210
+ syncArtifactVersionSelect(dom.filePathInput.value.trim());
211
+ setCanvasPreviewMode(saved ? Boolean(saved.canvasPreviewMode) : false);
212
+ state.diffScope = saved ? saved.diffScope : (nextSessionId ? 'session' : 'workspace');
213
+ state.diffStaged = saved ? Boolean(saved.diffStaged) : false;
214
+ syncDiffControlsUi();
215
+ dom.diffListEl.textContent = '';
216
+ dom.diffSummaryEl.textContent = 'Loading...';
217
+ dom.cliConsoleEl.textContent = saved ? saved.cliConsoleText : 'Select a command above or type /help.';
218
+ dom.cliStatusEl.textContent = saved ? saved.cliStatusText : 'Ready';
219
+ if (saved && saved.browserEngine === 'frame') {
220
+ state.browserMode = saved.browserMode || 'empty';
221
+ state.browserUrl = saved.browserUrl || '';
222
+ state.browserSrcdoc = saved.browserSrcdoc || '';
223
+ if (state.browserMode === 'srcdoc' && state.browserSrcdoc) {
224
+ dom.browserFrame.removeAttribute('src');
225
+ dom.browserFrame.srcdoc = state.browserSrcdoc;
226
+ } else if (state.browserMode === 'url' && state.browserUrl) {
227
+ dom.browserFrame.removeAttribute('srcdoc');
228
+ dom.browserFrame.src = state.browserUrl;
229
+ } else {
230
+ dom.browserFrame.removeAttribute('srcdoc');
231
+ dom.browserFrame.removeAttribute('src');
232
+ }
233
+ setBrowserEngine('frame');
234
+ } else {
235
+ state.browserMode = 'empty';
236
+ state.browserUrl = '';
237
+ state.browserSrcdoc = '';
238
+ dom.browserFrame.removeAttribute('srcdoc');
239
+ dom.browserFrame.removeAttribute('src');
240
+ if (state.browserEngine === 'frame') setBrowserEngine('agent');
241
+ }
242
+ if (dom.appEl.classList.contains('studio-open')) {
243
+ if (state.studioTab === 'diff') void loadDiff();
244
+ else if (state.studioTab === 'files') void loadFiles(state.currentDir, dom.fileFilterEl.value || '');
245
+ else if (state.studioTab === 'cli') void loadCliOverview();
246
+ else if (state.studioTab === 'browser' && state.browserEngine === 'agent') {
247
+ void refreshLiveBrowserState(false);
248
+ startLiveBrowserStream();
249
+ }
250
+ }
251
+ }
252
+
253
+ export function detachLocalStreamReader(): void {
254
+ if (state.activeController) {
255
+ try { state.activeController.abort(); } catch { /* ignore */ }
256
+ state.activeController = null;
257
+ }
258
+ state.activeTurn = null;
259
+ state.activePrompt = '';
260
+ setLiveness(false, '');
261
+ syncPermissionPresetLock(false);
262
+ updateComposerMetrics();
263
+ }
264
+
265
+ interface SessionDetailResponse {
266
+ session?: {
267
+ id: string;
268
+ title?: string;
269
+ running?: boolean;
270
+ activeRun?: { prompt?: string } | null;
271
+ messages?: Array<{
272
+ role: 'user' | 'assistant';
273
+ content?: string;
274
+ reasoning?: string;
275
+ steps?: RestoredStep[];
276
+ blocks?: RestoredBlock[];
277
+ }>;
278
+ };
279
+ }
280
+
281
+ export async function loadSessionTranscript(id: string): Promise<void> {
282
+ if (!id) return;
283
+ detachLocalStreamReader();
284
+ saveCurrentSessionWorkspace();
285
+ const seq = ++state.sessionSwitchSeq;
286
+ state.sessionId = id;
287
+ updateActiveSessionRow(id);
288
+ applySessionWorkspace(id);
289
+ void loadPermissionPresets(id);
290
+ if (window.innerWidth <= 960) dom.appEl.classList.add('sidebar-collapsed');
291
+ const res = await fetch(apiUrl(`/api/sessions/${encodeURIComponent(id)}`), { headers: authHeaders() }).catch(() => null);
292
+ if (seq !== state.sessionSwitchSeq) return;
293
+ if (!res || !res.ok) {
294
+ dom.threadEl.textContent = '';
295
+ resetThreadSpacer();
296
+ setStageMode(true);
297
+ const errTurn = createAssistantTurn('');
298
+ errTurn.addError(
299
+ res && res.status === 401
300
+ ? 'Session authentication expired. Reopen the URL printed by `causyne web`.'
301
+ : `Could not load conversation (HTTP ${res ? res.status : 'network error'}).`
302
+ );
303
+ return;
304
+ }
305
+ const data = await res.json().catch(() => null) as SessionDetailResponse | null;
306
+ const sess = data?.session;
307
+ if (!sess || seq !== state.sessionSwitchSeq) return;
308
+ dom.threadEl.textContent = '';
309
+ resetThreadSpacer();
310
+ dom.threadEl.classList.remove('chat-fade-in');
311
+ void dom.threadEl.offsetWidth;
312
+ dom.threadEl.classList.add('chat-fade-in');
313
+ const msgs = sess.messages || [];
314
+ setStageMode(msgs.length > 0 || Boolean(sess.running));
315
+ let lastUserPrompt = '';
316
+ for (const m of msgs) {
317
+ if (m.role === 'user') {
318
+ lastUserPrompt = m.content || '';
319
+ appendUserTurn(lastUserPrompt, [], false);
320
+ } else {
321
+ const t = createAssistantTurn(lastUserPrompt, { restored: true });
322
+ if (Array.isArray(m.blocks) && m.blocks.length > 0) {
323
+ t.renderRestoredBlocks(m.blocks);
324
+ } else {
325
+ if (m.reasoning) t.updateReasoning({ content: m.reasoning, streaming: false });
326
+ if (Array.isArray(m.steps)) {
327
+ for (const st of m.steps) {
328
+ t.addNativeStep(
329
+ { actionName: st.tool || '', detail: st.target || st.output || '', message: st.tool || '' },
330
+ st.status === 'failed'
331
+ );
332
+ }
333
+ }
334
+ if (m.content) t.setText(m.content, false);
335
+ }
336
+ t.finish();
337
+ }
338
+ }
339
+ if (sess.running && sess.activeRun) {
340
+ const runPrompt = sess.activeRun.prompt || lastUserPrompt;
341
+ const lastMsg = msgs[msgs.length - 1];
342
+ if (runPrompt && (!lastMsg || lastMsg.role !== 'user' || lastMsg.content !== runPrompt)) {
343
+ appendUserTurn(runPrompt, [], false);
344
+ }
345
+ scrollToBottom(true);
346
+ void callbacks.attachToActiveSessionStream(id, runPrompt, seq);
347
+ return;
348
+ }
349
+ const tailMsg = msgs[msgs.length - 1];
350
+ if (tailMsg && tailMsg.role === 'user') {
351
+ const interruptedTurn = createAssistantTurn(lastUserPrompt, { restored: true });
352
+ interruptedTurn.addInterrupted('Causyne\u2019s response was interrupted.', lastUserPrompt);
353
+ interruptedTurn.finish();
354
+ }
355
+ scrollToBottom(true);
356
+ }
357
+
358
+ export async function startFreshChat(): Promise<void> {
359
+ detachLocalStreamReader();
360
+ saveCurrentSessionWorkspace();
361
+ state.sessionSwitchSeq += 1;
362
+ state.sessionWorkspaces.delete('__draft__');
363
+ state.sessionId = null;
364
+ dom.threadEl.textContent = '';
365
+ resetThreadSpacer();
366
+ setStageMode(false);
367
+ applySessionWorkspace(null);
368
+ updateActiveSessionRow(null);
369
+ void loadPermissionPresets(null);
370
+ dom.promptInput.focus();
371
+ if (window.innerWidth <= 960) dom.appEl.classList.add('sidebar-collapsed');
372
+ }