-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathchatStore.ts
More file actions
1744 lines (1634 loc) · 57.5 KB
/
Copy pathchatStore.ts
File metadata and controls
1744 lines (1634 loc) · 57.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
DEFAULT_SESSION_TITLE,
appendDeletedSessionId,
resolveActiveSessionOnHydrate,
createUntitledSessionMeta,
insertSessionAfterActive,
renameSessionInList,
applySessionWorkspaceTarget,
removeSessionFromList,
nextActiveIdAfterDelete,
maybeDeriveSessionTitleList,
cutThroughNthUserMessage,
joinMessageTextParts,
} from "@altai/agent-ui";
import type { UIMessage } from "ai";
import { native } from "../lib/native";
import { create } from "zustand";
import {
DEFAULT_MODEL_ID,
getModel,
listAvailableModels,
providerNeedsKey,
type ModelId,
type ProviderId,
} from "../config";
import { usePreferencesStore } from "@/modules/settings/preferences";
import { setAutoModelEnabled as persistAutoModelEnabled } from "@/modules/settings/store";
import { useAgentsStore } from "./agentsStore";
import { useTodosStore } from "./todoStore";
import type { AgentUsage } from "../lib/provider";
import {
resolveCompactionSpec,
resolveFallbackSpec,
resolveIsanAgentTarget,
} from "../lib/isanagentTarget";
import { EMPTY_PROVIDER_KEYS, type ProviderKeys } from "../lib/keyring";
import {
deleteSessionData,
deriveTitle,
loadAll,
loadMessages,
mergeBackendSessions,
newSessionId,
saveActiveId,
saveDeletedIds,
saveMessages,
saveSessionsList,
type SessionMeta,
} from "../lib/sessions";
import { pushRecentModel } from "../lib/modelPrefs";
import { pickAutoModel } from "../lib/modelRouting";
import type { Agent } from "../lib/agents";
import { appendBackgroundMessage } from "../lib/backgroundTranscript";
import {
combineAgentInstructions,
readProjectInstructions,
} from "../lib/projectInstructions";
import { effectivePermissionMode, setDefaultModel } from "@/modules/settings/store";
import type { AssignmentRunConfig } from "@/modules/github/lib/assignments";
import type { RunOutcome } from "../lib/agentEventBridge";
import {
describeTerminalOutcomeAttention,
dismissRunAttention,
resetBudgetSegmentAutoContinues,
} from "../lib/agentEventBridge";
import { useAgentRunsStore, type RunState } from "./agentRunsStore";
type Live = {
getCwd: () => string | null;
getTerminalContext: () => string | null;
isActiveTerminalPrivate: () => boolean;
injectIntoActivePty: (text: string) => boolean;
getWorkspaceRoot: () => string | null;
getActiveFile: () => string | null;
openPreview: (url: string) => boolean;
};
export type AgentRunStatus =
| "idle"
| "thinking"
| "streaming"
| "awaiting-approval"
| "cancelling"
| "error";
/** A subagent task currently dispatched by the main agent. */
export type SubagentTask = {
taskId: string;
childChatId: string;
/** Human-facing label (e.g. "Researcher"), if the agent provided one. */
displayName: string | null;
/** Named agent the task runs as (e.g. "researcher", "coder"), if any. */
agentName: string | null;
};
/** An action awaiting a user decision, mirrored from the native event stream. */
export type PendingApproval = {
id: string;
action: string;
payload: unknown;
};
/** A compact, current-session audit trail for the task inspector. */
export type AgentActivity = {
id: string;
label: string;
detail?: string;
kind?: "tool" | "research" | "mcp" | "execution" | "agent" | "approval" | "system";
tone?: "default" | "success" | "warning" | "error";
createdAt: number;
};
/** A file or result emitted by a runtime experiment, available to inspect. */
export type AgentArtifact = {
id: string;
path: string;
experimentId: string;
createdAt: number;
};
export type AgentMeta = {
status: AgentRunStatus;
step: string | null;
approvalsPending: number;
pendingApprovals: PendingApproval[];
activity: AgentActivity[];
artifacts: AgentArtifact[];
error: string | null;
tokens: AgentUsage;
lastInputTokens: number;
lastCachedTokens: number;
/** Subagent tasks running right now, surfaced as a live indicator. */
activeSubagents: SubagentTask[];
};
const ZERO_USAGE: AgentUsage = {
inputTokens: 0,
outputTokens: 0,
cachedInputTokens: 0,
};
const IDLE_META: AgentMeta = {
status: "idle",
step: null,
approvalsPending: 0,
pendingApprovals: [],
activity: [],
artifacts: [],
error: null,
tokens: ZERO_USAGE,
lastInputTokens: 0,
lastCachedTokens: 0,
activeSubagents: [],
};
function agentMetaForRun(run: RunState | undefined): AgentMeta {
if (!run) return IDLE_META;
const error = describeTerminalOutcomeAttention(run.outcome);
return {
...IDLE_META,
status:
run.completed && run.outcome?.kind === "failed"
? "error"
: run.completed
? "idle"
: run.status,
step: run.completed ? null : run.step,
error,
tokens: {
inputTokens: run.tokens.input,
outputTokens: run.tokens.output,
cachedInputTokens: run.tokens.cached,
},
activeSubagents: run.subagents,
};
}
export type MiniState = {
open: boolean;
/**
* Element that had focus when the panel was opened. Focus is restored to
* it on close so keyboard/AT users aren't orphaned to <body> (a11y D4).
*/
opener?: HTMLElement | null;
};
export type PendingSelection = {
id: string;
text: string;
source: "terminal" | "editor";
};
export type PendingEditDiff = {
file: string;
diff: string;
truncated: boolean;
};
export type PendingClarification = {
choices: string[];
editDiff: PendingEditDiff | null;
};
type StoreState = {
live: Live;
setLive: (live: Live) => void;
/**
* Resolve a pending tool approval. Routes directly to the native
* IsanAgent runtime; surfaces anywhere (chat transcript, AI diff tab in
* the editor area) call this with the approval id.
*/
respondToApproval: (approvalId: string, approved: boolean) => void;
apiKeys: ProviderKeys;
setApiKeys: (keys: ProviderKeys) => void;
setApiKey: (provider: ProviderId, key: string | null) => void;
selectedModelId: ModelId;
setSelectedModelId: (id: ModelId) => void;
autoModelEnabled: boolean;
setAutoModelEnabled: (enabled: boolean) => void;
mini: MiniState;
openMini: () => void;
closeMini: () => void;
toggleMini: () => void;
panelOpen: boolean;
openPanel: () => void;
closePanel: () => void;
togglePanel: () => void;
focusSignal: number;
pendingPrefill: string | null;
focusInput: (prefill?: string | null) => void;
consumePrefill: () => string | null;
pendingSelections: PendingSelection[];
attachSelection: (text: string, source: "terminal" | "editor") => void;
consumeSelections: () => PendingSelection[];
agentMeta: AgentMeta;
patchAgentMeta: (patch: Partial<AgentMeta>) => void;
resetAgentMeta: () => void;
/** Track a newly spawned subagent task (de-duplicated by taskId). */
addSubagentTask: (task: SubagentTask) => void;
/** Drop a subagent task once it reaches a terminal state. */
removeSubagentTask: (taskId: string) => void;
/** Mirror a native approval request so it can be actioned outside the transcript. */
addApproval: (approval: PendingApproval) => void;
removeApproval: (approvalId: string) => void;
/** Add a bounded item to the focused task's in-memory activity timeline. */
addActivity: (activity: Omit<AgentActivity, "id" | "createdAt">) => void;
addArtifacts: (input: { experimentId: string; paths: string[] }) => void;
/** Messages from the IsanAgent runtime, rendered as UIMessage parts. */
nativeMessages: UIMessage[];
appendNativeMessage: (content: string, role: string) => void;
clearNativeMessages: () => void;
/**
* Preset answers for a pending `ask_user` clarification, surfaced as
* clickable chips. `null` when no clarification is open. Cleared when the
* user sends any message (a reply resolves the clarification) or switches
* sessions.
*/
pendingChoices: string[] | null;
setPendingChoices: (choices: string[] | null) => void;
/**
* Structured file-edit diff attached to a clarification when the agent's
* edit gate requests approval (crate `interactive_edit_mode = Ask`). When
* present, the chat renders a diff-review card instead of the plain choice
* chips. The reply path is identical to a normal clarification — the user
* sends `approve` / `deny` as a message and the `ClarificationHub` routes it
* back to the waiting tool.
*/
pendingEditDiff: PendingEditDiff | null;
setPendingEditDiff: (diff: PendingEditDiff | null) => void;
pendingClarificationsBySession: Record<string, PendingClarification>;
setPendingClarificationForSession: (
sessionId: string,
clarification: PendingClarification | null,
) => void;
/** Clear BOTH `pendingChoices` and `pendingEditDiff` in one step. The two
* are always set together from a clarification event and resolve together
* when the user replies — this is the single chokepoint so every reset
* site (session switch, rewind, send) clears both atomically instead of
* each site re-stating the two-field reset by hand (drift-prone). */
resetPendingClarification: () => void;
/**
* Id of the assistant `UIMessage` that is currently accumulating parts
* for the in-flight turn. Tool calls + interleaved text from the native
* runtime collapse into this message so the UI renders one bubble with
* inline tool entries instead of fragmenting per event.
*
* `null` when no turn is in flight — the next assistant event opens a
* fresh message.
*/
currentAssistantTurnId: string | null;
startNativeToolCall: (
toolCallId: string,
toolName: string,
input: unknown,
) => void;
endNativeToolCall: (
toolCallId: string,
output: unknown,
errorText?: string,
) => void;
closeAssistantTurn: () => void;
/** Whether the Paper Import panel is open in the input bar. */
paperImportOpen: boolean;
setPaperImportOpen: (open: boolean) => void;
// Sessions
sessionsHydrated: boolean;
sessions: SessionMeta[];
activeSessionId: string | null;
hydrateSessions: () => Promise<void>;
newSession: () => string;
/** Create a titled session WITHOUT focusing it (no active-session change,
* no transcript reset) — for background agent dispatch from operations. */
createBackgroundSession: (title: string) => string;
switchSession: (id: string) => void;
/** Move a session immediately before or after another session. */
reorderSessions: (id: string, targetId: string, after: boolean) => void;
deleteSession: (id: string) => void;
renameSession: (id: string, title: string) => void;
setSessionWorkspace: (
id: string,
target: {
path: string | null;
kind: "local" | "github" | null;
repositoryUrl?: string | null;
},
) => void;
};
const NOOP_LIVE: Live = {
getCwd: () => null,
getTerminalContext: () => null,
isActiveTerminalPrivate: () => false,
injectIntoActivePty: () => false,
getWorkspaceRoot: () => null,
getActiveFile: () => null,
openPreview: () => false,
};
// Trailing debounce for per-token message persistence. Streaming mutates
// `nativeMessages` on every event; without this we'd JSON-serialize the
// full message array and round-trip to the store plugin per event, which
// stalls the UI. Flush on idle (status transition) via `flushPersist`.
const PERSIST_DEBOUNCE_MS = 300;
const pendingPersist = new Map<
string,
{ latest: UIMessage[]; timer: ReturnType<typeof setTimeout> }
>();
// Message arrays freshly hydrated from disk. The persistence subscription
// skips these once — re-writing a thread we just read back is pure waste.
const loadedMessagesRefs = new WeakSet<UIMessage[]>();
// Sessions the user permanently deleted. Kept out of the history list and
// used to suppress backend recovery so a deleted chat doesn't resurrect.
const deletedSessionIds = new Set<string>();
// Fingerprint of the runtime config we last successfully started. Lets us skip
// the per-message `agent_start` IPC when nothing changed (the Rust side no-ops
// on an identical fingerprint anyway). Reset to null on any start/send failure
// so a dead runtime is always restarted on the next attempt.
let lastStartFingerprint: string | null = null;
function flushPersistEntry(id: string) {
const entry = pendingPersist.get(id);
if (!entry) return;
clearTimeout(entry.timer);
pendingPersist.delete(id);
void saveMessages(id, entry.latest);
}
export function flushPersist(id?: string): void {
if (id) {
flushPersistEntry(id);
return;
}
for (const key of Array.from(pendingPersist.keys())) flushPersistEntry(key);
}
/**
* Persist a session's native message thread (debounced) and refresh its
* derived title. This is the replacement for the former Vercel-SDK
* `Chat`-instance persistence: `nativeMessages` is now the single source of
* truth, so we save it directly whenever it changes (see the store
* subscription below).
*/
function persistNativeMessages(id: string, messages: UIMessage[]): void {
const existing = pendingPersist.get(id);
if (existing) clearTimeout(existing.timer);
const timer = setTimeout(() => {
const entry = pendingPersist.get(id);
if (!entry) return;
pendingPersist.delete(id);
void saveMessages(id, entry.latest);
}, PERSIST_DEBOUNCE_MS);
pendingPersist.set(id, { latest: messages, timer });
// Update the session list only when the derived title actually changes —
// otherwise we'd rewrite the sessions array (and trigger re-renders + a
// store write) on every streamed event.
const state = useChatStore.getState();
const nextTitle = deriveTitle(messages);
const next = maybeDeriveSessionTitleList(state.sessions, id, nextTitle);
if (!next) return;
useChatStore.setState({ sessions: next });
void saveSessionsList(next);
}
export const useChatStore = create<StoreState>((set, get) => ({
live: NOOP_LIVE,
setLive: (live) => set({ live }),
respondToApproval: (approvalId, approved) => {
const approval = get().agentMeta.pendingApprovals.find(
(item) => item.id === approvalId,
);
get().removeApproval(approvalId);
const sessionId = get().activeSessionId;
if (sessionId) {
// Approving/denying is an explicit acknowledgment — drop the sticky
// "needs attention" banner so it doesn't outlive the user's response.
dismissRunAttention(sessionId);
}
get().addActivity({
label: approved ? "Approved action" : "Denied action",
detail: approval?.action,
tone: approved ? "success" : "warning",
});
void native.agentApprove(approvalId, approved).catch((cause) => {
if (approval) {
get().addApproval(approval);
}
get().addActivity({
label: "Approval response failed",
detail: cause instanceof Error ? cause.message : String(cause),
tone: "error",
});
get().patchAgentMeta({
status: "error",
error: cause instanceof Error ? cause.message : String(cause),
});
});
},
apiKeys: { ...EMPTY_PROVIDER_KEYS },
setApiKeys: (keys) => set({ apiKeys: keys }),
setApiKey: (provider, key) => {
set({ apiKeys: { ...get().apiKeys, [provider]: key } });
},
selectedModelId: DEFAULT_MODEL_ID,
setSelectedModelId: (id) => {
const prev = get().selectedModelId;
if (prev === id) return;
set({ selectedModelId: id });
void pushRecentModel(id);
// Persist the picked model so it survives an app restart. The dedup
// guard above keeps the App.tsx hydrate path (which mirrors
// preferences → chatStore on boot and on cross-window events) from
// writing the same value back through `setDefaultModel`.
void setDefaultModel(id);
},
autoModelEnabled: true,
setAutoModelEnabled: (enabled) => {
if (get().autoModelEnabled === enabled) return;
set({ autoModelEnabled: enabled });
void persistAutoModelEnabled(enabled);
},
mini: { open: false },
openMini: () =>
set((s) => {
// Capture the opener so we can restore focus on close (a11y D4).
// Only record on a real open transition; ignore re-opens.
if (s.mini.open) return s;
const opener =
typeof document !== "undefined"
? (document.activeElement as HTMLElement | null)
: null;
return { mini: { open: true, opener } };
}),
closeMini: () =>
set((s) => {
const { opener } = s.mini;
// Restore focus to the element that opened the panel, if it's still
// in the document; otherwise leave focus where it is (a11y D4).
if (opener && document.contains(opener)) {
opener.focus?.();
}
return { mini: { open: false, opener: null } };
}),
toggleMini: () => {
const s = get();
if (s.mini.open) s.closeMini();
else s.openMini();
},
panelOpen: false,
openPanel: () => set({ panelOpen: true }),
closePanel: () => set({ panelOpen: false }),
togglePanel: () => set((s) => ({ panelOpen: !s.panelOpen })),
focusSignal: 0,
pendingPrefill: null,
focusInput: (prefill = null) =>
set((s) => ({
panelOpen: true,
focusSignal: s.focusSignal + 1,
pendingPrefill: prefill ?? null,
})),
consumePrefill: () => {
const v = get().pendingPrefill;
if (v != null) set({ pendingPrefill: null });
return v;
},
pendingSelections: [],
attachSelection: (text, source) => {
const trimmed = text.trim();
if (!trimmed) return;
const id = `sel-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
set((s) => ({
panelOpen: true,
focusSignal: s.focusSignal + 1,
pendingSelections: [...s.pendingSelections, { id, text: trimmed, source }],
}));
},
consumeSelections: () => {
const v = get().pendingSelections;
if (v.length > 0) set({ pendingSelections: [] });
return v;
},
agentMeta: IDLE_META,
patchAgentMeta: (patch) =>
set((s) => ({ agentMeta: { ...s.agentMeta, ...patch } })),
resetAgentMeta: () => set({ agentMeta: IDLE_META }),
addSubagentTask: (task) =>
set((s) => {
if (s.agentMeta.activeSubagents.some((t) => t.taskId === task.taskId)) {
return {};
}
return {
agentMeta: {
...s.agentMeta,
activeSubagents: [...s.agentMeta.activeSubagents, task],
},
};
}),
removeSubagentTask: (taskId) =>
set((s) => ({
agentMeta: {
...s.agentMeta,
activeSubagents: s.agentMeta.activeSubagents.filter(
(t) => t.taskId !== taskId,
),
},
})),
addApproval: (approval) =>
set((s) => {
if (s.agentMeta.pendingApprovals.some((item) => item.id === approval.id)) {
return {};
}
const pendingApprovals = [...s.agentMeta.pendingApprovals, approval];
return {
agentMeta: {
...s.agentMeta,
status: "awaiting-approval",
pendingApprovals,
approvalsPending: pendingApprovals.length,
},
};
}),
removeApproval: (approvalId) =>
set((s) => {
const pendingApprovals = s.agentMeta.pendingApprovals.filter(
(item) => item.id !== approvalId,
);
return {
agentMeta: {
...s.agentMeta,
pendingApprovals,
approvalsPending: pendingApprovals.length,
status:
pendingApprovals.length === 0 && s.agentMeta.status === "awaiting-approval"
? "thinking"
: s.agentMeta.status,
},
};
}),
addActivity: (activity) =>
set((s) => {
const next = [
...s.agentMeta.activity,
{
...activity,
id: `activity-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
createdAt: Date.now(),
},
].slice(-80);
return { agentMeta: { ...s.agentMeta, activity: next } };
}),
addArtifacts: ({ experimentId, paths }) =>
set((s) => {
const existing = new Set(s.agentMeta.artifacts.map((item) => item.id));
const additions = paths
.filter((path) => path.trim().length > 0)
.map((path, index) => ({
id: `${experimentId}:${path}:${index}`,
path,
experimentId,
createdAt: Date.now(),
}))
.filter((item) => !existing.has(item.id));
if (!additions.length) return {};
return {
agentMeta: {
...s.agentMeta,
artifacts: [...s.agentMeta.artifacts, ...additions].slice(-80),
},
};
}),
nativeMessages: [],
currentAssistantTurnId: null,
appendNativeMessage: (content, role) => {
const validRole = (role === "user" || role === "assistant")
? role
: "assistant";
// User turn closes any in-flight assistant turn so the next assistant
// event begins a fresh bubble. New user messages are always appended
// as their own UIMessage.
if (validRole === "user") {
const id = `native-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
const msg: UIMessage = {
id,
role: "user",
parts: [{ type: "text", text: content }],
};
set((s) => ({
nativeMessages: [...s.nativeMessages, msg],
currentAssistantTurnId: null,
}));
return;
}
// Assistant content folds into the current turn so text emitted
// before/after tool calls stays inside the same bubble. If no turn
// is open we mint a new assistant UIMessage and remember its id.
set((s) => {
const turnId = s.currentAssistantTurnId;
if (turnId) {
const next = s.nativeMessages.map((m) =>
m.id === turnId
? {
...m,
parts: [
...m.parts,
{ type: "text" as const, text: content },
],
}
: m,
);
return { nativeMessages: next };
}
const id = `native-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
const msg: UIMessage = {
id,
role: "assistant",
parts: [{ type: "text", text: content }],
};
return {
nativeMessages: [...s.nativeMessages, msg],
currentAssistantTurnId: id,
};
});
},
startNativeToolCall: (toolCallId, toolName, input) => {
// Cast to the loose UIMessagePart shape — `dynamic-tool` lives in
// the ai-sdk type space and isn't worth importing through here just
// for one assignment. AiChat.tsx renders any part whose `type`
// starts with "tool-" or equals "dynamic-tool", so the shape below
// matches what `RenderedTool` expects.
const toolPart = {
type: "dynamic-tool" as const,
toolName,
toolCallId,
state: "input-available" as const,
input,
} as unknown as UIMessage["parts"][number];
set((s) => {
const turnId = s.currentAssistantTurnId;
if (turnId) {
const next = s.nativeMessages.map((m) =>
m.id === turnId
? { ...m, parts: [...m.parts, toolPart] }
: m,
);
return { nativeMessages: next };
}
const id = `native-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
const msg: UIMessage = {
id,
role: "assistant",
parts: [toolPart],
};
return {
nativeMessages: [...s.nativeMessages, msg],
currentAssistantTurnId: id,
};
});
},
endNativeToolCall: (toolCallId, output, errorText) => {
set((s) => {
// Walk from the end — the part we just completed is almost always
// on the most recent assistant message. Bail out untouched if no
// match (shouldn't happen, but the bridge is best-effort).
let touched = false;
const nextMessages = s.nativeMessages.map((m) => {
if (touched) return m;
const idx = m.parts.findIndex(
(p) =>
(p as { toolCallId?: string }).toolCallId === toolCallId,
);
if (idx === -1) return m;
touched = true;
const updatedPart = {
...(m.parts[idx] as object),
state: errorText ? "output-error" : "output-available",
...(errorText ? { errorText } : { output }),
} as unknown as UIMessage["parts"][number];
const nextParts = [...m.parts];
nextParts[idx] = updatedPart;
return { ...m, parts: nextParts };
});
return touched ? { nativeMessages: nextMessages } : {};
});
},
closeAssistantTurn: () => set({ currentAssistantTurnId: null }),
clearNativeMessages: () =>
set({ nativeMessages: [], currentAssistantTurnId: null }),
pendingChoices: null,
setPendingChoices: (choices) => {
const next = choices && choices.length > 0 ? choices : null;
const sessionId = get().activeSessionId;
if (!sessionId) {
set({
pendingChoices: next,
...(next === null ? { pendingEditDiff: null } : {}),
});
return;
}
if (next === null) {
get().setPendingClarificationForSession(sessionId, null);
return;
}
const current = get().pendingClarificationsBySession[sessionId];
get().setPendingClarificationForSession(sessionId, {
choices: next,
editDiff: current?.editDiff ?? get().pendingEditDiff,
});
},
pendingEditDiff: null,
setPendingEditDiff: (diff) => {
const sessionId = get().activeSessionId;
if (!sessionId) {
set({ pendingEditDiff: diff });
return;
}
const current = get().pendingClarificationsBySession[sessionId];
get().setPendingClarificationForSession(sessionId, {
choices: current?.choices ?? get().pendingChoices ?? [],
editDiff: diff,
});
},
pendingClarificationsBySession: {},
setPendingClarificationForSession: (sessionId, clarification) =>
set((state) => {
const pendingClarificationsBySession = {
...state.pendingClarificationsBySession,
};
if (clarification) {
pendingClarificationsBySession[sessionId] = {
choices: clarification.choices.filter(
(choice) => choice.trim().length > 0,
),
editDiff: clarification.editDiff,
};
} else {
delete pendingClarificationsBySession[sessionId];
}
const activeProjection =
state.activeSessionId === sessionId
? {
pendingChoices:
clarification && clarification.choices.length > 0
? clarification.choices
: null,
pendingEditDiff: clarification?.editDiff ?? null,
}
: {};
return { pendingClarificationsBySession, ...activeProjection };
}),
resetPendingClarification: () => {
const sessionId = get().activeSessionId;
if (sessionId) {
get().setPendingClarificationForSession(sessionId, null);
} else {
set({ pendingChoices: null, pendingEditDiff: null });
}
},
paperImportOpen: false,
setPaperImportOpen: (open) => set({ paperImportOpen: open }),
sessionsHydrated: false,
sessions: [],
activeSessionId: null,
hydrateSessions: async () => {
if (get().sessionsHydrated) return;
let { sessions, activeId, deletedIds } = await loadAll();
deletedSessionIds.clear();
for (const id of deletedIds) deletedSessionIds.add(id);
// Reconcile with the backend memory DB — the durable source of truth.
// Chats that were closed (dropped from this ephemeral store) but still
// exist in the agent's history are recovered here so they reappear in the
// chat-history list (Claude Code / Cursor behavior). Best-effort:
// a backend error must not block hydration. Permanently-deleted ids are
// suppressed so they don't come back.
const { merged, recoveredIds } = await mergeBackendSessions(
sessions,
[...deletedSessionIds],
);
sessions = merged;
if (recoveredIds.length > 0) {
void saveSessionsList(merged);
}
// Pick the session to land on after restart. Prefer the last-used one
// (persisted activeId) if it still exists, so the user returns to their
// most recent conversation instead of an empty "New chat". Else reuse the
// most recent untitled "New chat" (no point stacking empty placeholders
// every launch), else create a fresh one.
const resolved = resolveActiveSessionOnHydrate(
sessions,
activeId,
() =>
createUntitledSessionMeta(newSessionId()) as SessionMeta,
);
const active = resolved.active;
const nextSessions = resolved.nextSessions as SessionMeta[];
if (resolved.created) {
void saveSessionsList(nextSessions);
}
const activeSessionId = active.id;
void saveActiveId(activeSessionId);
set({
sessions: nextSessions,
activeSessionId,
sessionsHydrated: true,
});
// Restore the active session's thread so the conversation reappears on
// reopen instead of an empty transcript. Guarded so a manual switch that
// lands elsewhere before this resolves wins (same shape as switchSession).
void loadMessages(activeSessionId).then((m) => {
if (get().activeSessionId !== activeSessionId) return;
const loaded = m ?? [];
loadedMessagesRefs.add(loaded);
set({ nativeMessages: loaded });
});
},
newSession: () => {
const id = newSessionId();
const meta: SessionMeta = {
id,
title: DEFAULT_SESSION_TITLE,
createdAt: Date.now(),
updatedAt: Date.now(),
};
const current = get().sessions;
const next = insertSessionAfterActive(
current,
get().activeSessionId,
meta,
);
set({
sessions: next,
activeSessionId: id,
agentMeta: IDLE_META,
nativeMessages: [],
currentAssistantTurnId: null,
pendingChoices: null,
pendingEditDiff: null,
});
void saveSessionsList(next);
void saveActiveId(id);
return id;
},
createBackgroundSession: (title) => {
const id = newSessionId();
const meta: SessionMeta = {
id,
title,
createdAt: Date.now(),
updatedAt: Date.now(),
};
const next = [...get().sessions, meta];
set({ sessions: next });
void saveSessionsList(next);
return id;
},
switchSession: (id) => {
const prevId = get().activeSessionId;
if (prevId === id) return;
if (!get().sessions.some((s) => s.id === id)) return;
// Persist the tail of the session we're leaving before swapping in the
// target session's thread, so a debounced write in flight isn't lost.
if (prevId) flushPersist(prevId);
// Switch synchronously so the UI reflects the active session immediately.
// The message thread loads asynchronously and is applied only if we're
// still on this session — rapid A→B→A switches must not cross-populate.
const pending = get().pendingClarificationsBySession[id];
const run = useAgentRunsStore.getState().runs[id];
set({
activeSessionId: id,
agentMeta: agentMetaForRun(run),
nativeMessages: [],
currentAssistantTurnId: null,
pendingChoices:
pending && pending.choices.length > 0 ? pending.choices : null,
pendingEditDiff: pending?.editDiff ?? null,
});
void saveActiveId(id);
void loadMessages(id).then((m) => {
if (get().activeSessionId !== id) return;
const loaded = m ?? [];
loadedMessagesRefs.add(loaded);
set({ nativeMessages: loaded });
});
},
reorderSessions: (id, targetId, after) => {
if (id === targetId) return;
const current = get().sessions;
const moved = current.find((session) => session.id === id);
if (!moved || !current.some((session) => session.id === targetId)) return;
const withoutMoved = current.filter((session) => session.id !== id);
const targetIndex = withoutMoved.findIndex(
(session) => session.id === targetId,
);
const next = [...withoutMoved];
next.splice(targetIndex + (after ? 1 : 0), 0, moved);
set({ sessions: next });
void saveSessionsList(next);
},
deleteSession: (id) => {
const currentState = get();
const deletingRun = useAgentRunsStore.getState().runs[id];
if (deletingRun?.runId && !deletingRun.completed) {
currentState.addActivity({
label: "Stopping the run before deleting its chat",
detail: "Delete the chat again after cancellation completes",
kind: "agent",
tone: "warning",
});
void requestStop(id).catch(() => undefined);
return;
}
const remaining = removeSessionFromList(currentState.sessions, id);
const pendingClarificationsBySession = {