-
-
Notifications
You must be signed in to change notification settings - Fork 678
Expand file tree
/
Copy pathAgentSession.ts
More file actions
1740 lines (1643 loc) · 66.2 KB
/
Copy pathAgentSession.ts
File metadata and controls
1740 lines (1643 loc) · 66.2 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 { AI_SENDER, USER_SENDER, WEB_SELECTED_TEXT_TAG } from "@/constants";
import { logInfo, logWarn } from "@/logger";
import { AgentMessageStore } from "@/agentMode/session/AgentMessageStore";
import {
AgentChatMessage,
AgentMessagePart,
AgentQuestionAnswers,
AgentToolCallOutput,
AskUserQuestionPrompt,
BackendDescriptor,
BackendId,
BackendProcess,
BackendState,
CurrentPlan,
ModelSelection,
NewAgentChatMessage,
PERMISSION_ALLOW_KINDS,
PERMISSION_REJECT_KINDS,
PermissionDecision,
PermissionOptionKind,
PermissionPrompt,
PlanSummary,
PromptContent,
PromptInput,
SessionEvent,
SessionId,
StopReason,
ToolCallContent,
ToolCallDelta,
ToolCallSnapshot,
} from "@/agentMode/session/types";
import {
isNoteSelectedTextContext,
isWebSelectedTextContext,
MessageContext,
} from "@/types/message";
import { err2String, formatDateTime } from "@/utils";
import { MethodUnsupportedError } from "@/agentMode/session/errors";
import { resolveMcpServers } from "@/agentMode/session/mcpResolver";
import { deriveChatTitleFromMessages } from "@/agentMode/session/chatHistoryMerge";
import { getSettings } from "@/settings/model";
import { ContextProcessor } from "@/contextProcessor";
import { escapeXml } from "@/LLMProviders/chainRunner/utils/xmlParsing";
/**
* Prefix opencode uses for placeholder titles before its title-summarizer
* agent runs. Treating these as "no title" prevents the tab from briefly
* showing "New session - 2026-…" before the LLM-generated label arrives.
* Exported so the manager's `listSessions` history sweep applies the same
* "placeholder is not a real title" rule.
*/
export const DEFAULT_TITLE_PREFIX = "New session";
/**
* Memory backstop for tool output kept in long-lived React state — NOT a
* display cap. At ~256KB it sits far above any realistic command/search/file
* result (the chat renders output collapsed in a scrollable box, so normal and
* large outputs show in full), and only a runaway multi-hundred-KB blob is
* trimmed to stop the message store from holding it for the whole session. The
* agent's own context always receives the full output regardless.
*/
const MAX_TOOL_OUTPUT_TEXT_CHARS = 256_000;
// Shared sentinel so `getPendingToolPermissions()` returns a stable reference
// when nothing is pending — preserves React `useState` setter bail-out
// behavior on idle subscription ticks.
const EMPTY_PERMISSIONS: PermissionPrompt[] = [];
// Same idea for `getPendingAskUserQuestions()`.
const EMPTY_QUESTIONS: AskUserQuestionPrompt[] = [];
// Canonical "no answers" map. Resolving an in-flight question with this on
// cancel/dispose makes the bridge treat it as a user cancellation.
const EMPTY_ANSWERS: AgentQuestionAnswers = Object.freeze({});
/**
* Optimistically swap `state.model.current.baseModelId` for the persisted
* user selection so the picker's first paint matches what the user picked.
*
* Only `baseModelId` is seeded — `effort` is left as the backend reported.
* For descriptor-style backends (Claude) effort lives out-of-band and is
* applied via `applyInitialSessionConfig` → `setConfigOption`; seeding it
* here would make that step see a matching value and silently skip the
* real config write. For wire-effort backends (opencode-style) the
* subsequent `setModel` call carries the user's effort through the
* encoded id, and the backend's response replaces this seed entirely.
*
* Returns the input reference unchanged when no seed is possible.
*/
function seedSelectionIntoState(
state: BackendState | null,
selection: ModelSelection | undefined
): BackendState | null {
if (!state || !state.model || !selection) return state;
const entry = state.model.availableModels.find((m) => m.baseModelId === selection.baseModelId);
if (!entry) return state;
if (state.model.current.baseModelId === selection.baseModelId) return state;
return {
...state,
model: {
...state.model,
current: { ...state.model.current, baseModelId: selection.baseModelId },
},
};
}
export type AgentSessionStatus =
| "starting"
| "idle"
| "running"
| "awaiting_permission"
| "error"
| "closed";
/**
* Statuses that demand the user's eye when reached from `running` on a
* backgrounded tab. The manager uses this to decide when to flag
* `needsAttention`. Co-located with the union so adding a new status forces
* a deliberate decision about whether it belongs here.
*/
export const ATTENTION_TRIGGER_STATUSES: ReadonlySet<AgentSessionStatus> = new Set([
"idle",
"error",
"awaiting_permission",
]);
export interface AgentSessionListener {
onMessagesChanged(): void;
onStatusChanged(status: AgentSessionStatus): void;
/**
* Optional: fired when model, configOption, or mode state changes. The
* picker treats all three as one notification channel — they all cause it
* to rebuild and there's no value in fanning out separate callbacks.
*/
onModelChanged?(): void;
/** Optional: fired when the user-visible label changes. */
onLabelChanged?(): void;
/**
* Optional: fired when the singleton `currentPlan` changes (created,
* revised in place, or cleared). The floating plan card / preview tab
* subscribe to this channel.
*/
onCurrentPlanChanged?(): void;
/**
* Optional: fired when the "needs attention" flag flips. The tab strip
* subscribes to render an accent dot on the brand icon for backgrounded
* sessions that finished, errored, or paused for permission while the
* user was looking at a different tab.
*/
onNeedsAttentionChanged?(needsAttention: boolean): void;
}
export interface AgentSessionStartOptions {
backend: BackendProcess;
cwd: string;
internalId: string;
backendId: BackendId;
/**
* Persisted user preference to apply after the backend's initial session
* state. The session seeds it optimistically so the first picker paint
* shows the user's pick, then confirms with the backend via setModel
* (and, for descriptor-style backends, setConfigOption — handled by the
* manager's `applyInitialSessionConfig` hook).
*/
defaultModelSelection?: ModelSelection;
/**
* Snapshot from the preloader cache used to seed `currentState`
* synchronously so the picker doesn't flash the previous session's
* selection during the `backend.newSession` round-trip. Replaced by the
* agent's fresh `newSession` response inside `initialize()`.
*/
initialCachedState?: BackendState | null;
/**
* Optional descriptor accessor. The session uses it to resolve mode mappings
* without coupling to specific backends. Manager-supplied; tests omit it.
*/
getDescriptor?: () => BackendDescriptor | undefined;
}
/**
* Pre-resolved state used by tests and by `loadSessionFromHistory` to
* construct a session that bypasses the async backend startup.
*/
export interface AgentSessionStateOptions {
backend: BackendProcess;
backendSessionId: SessionId;
internalId: string;
backendId: BackendId;
initialState?: BackendState | null;
/**
* Optional persisted user preference applied to the warm/adopted session.
* Same role as `AgentSessionStartOptions.defaultModelSelection` — seeded
* optimistically on construction; setModel runs async and reverts the
* seed on failure.
*/
defaultModelSelection?: ModelSelection;
cwd?: string | null;
getDescriptor?: () => BackendDescriptor | undefined;
}
/**
* Per-chat Agent Mode session. Owns its `AgentMessageStore`, the lifecycle
* of one backend session id, and the `AbortController` that cancels in-flight
* turns.
*
* Construction is split: `AgentSession.start()` returns synchronously with
* status `"starting"` so the UI can swap to the new (empty) chat immediately.
* The backend `newSession` runs in the background; once it resolves the
* session transitions to `"idle"` and `sendPrompt` becomes usable. While
* starting, `sendPrompt` throws — the chat UI gates the send button on
* `getStatus() === "starting"`.
*/
export class AgentSession {
readonly store = new AgentMessageStore();
readonly internalId: string;
readonly backendId: BackendId;
/** Resolves when `newSession` succeeds; rejects when it fails. */
readonly ready: Promise<void>;
private backendSessionId: SessionId | null = null;
private readonly backend: BackendProcess;
private readonly cwd: string | null;
private readonly getDescriptor: (() => BackendDescriptor | undefined) | null;
// `status` is derived from the primitives below — see `getStatus()`.
// `cachedStatus` is a memo of the last value we fired through
// `onStatusChanged`, used purely for change detection. It is not the
// source of truth; never read it from anywhere except
// `recomputeStatusIfChanged()`.
private cachedStatus: AgentSessionStatus = "starting";
// Set in `initialize`'s catch when the backend's `newSession` rejects.
// Combined with `backendSessionId === null` this yields the startup
// `"error"` status.
private startupFailed = false;
// Set in `runTurn`'s catch; cleared at the top of `sendPrompt` once
// preconditions pass. Yields the per-turn `"error"` status while the
// session sits idle between a failed turn and the next prompt.
private lastTurnError = false;
private placeholderId: string | null = null;
// ACP `messageId`s seen on this turn's content chunks. Used to re-route
// trailing chunks that a backend flushes *after* the `session/prompt` result
// (observed with opencode + fast DeepSeek models) to the right message.
private currentMessageIds = new Set<string>();
// The most-recently-completed turn's placeholder plus the `messageId`s it
// owned. A grace window: late content chunks naming one of these still land
// on the finished message instead of being dropped — or, worse, appended to
// a newer turn's placeholder. Replaced on the next completion, cleared on
// cancel/dispose.
private settledStream: { placeholderId: string; messageIds: Set<string> } | null = null;
private abortController: AbortController | null = null;
private listeners = new Set<AgentSessionListener>();
private unregisterSessionHandler: (() => void) | null = null;
/**
* Cached normalized state — produced by the backend at session start /
* resume / load and refreshed via `state_changed` events or per-dimension
* `setSession*` responses.
*/
private currentState: BackendState | null = null;
private label: string | null = null;
// Tracks who set the current label so an agent-pushed `session_info_update`
// can't clobber a label the user explicitly chose via Rename.
private labelSource: "user" | "agent" | null = null;
private disposed = false;
// Pending permission resolvers keyed by toolCallId. Populated when an
// ExitPlanMode permission request arrives (via the wrapped prompter); the
// chat card resolves them through `resolvePlanProposalPermission`.
private pendingPlanResolvers = new Map<
string,
{
request: PermissionPrompt;
resolve: (resp: PermissionDecision) => void;
}
>();
// Pending permission resolvers for general (non-plan) tool calls. Populated
// by `handleToolPermission` when the wrapped prompter routes a request to
// this session; the inline `ToolPermissionCard` resolves them through
// `resolveToolPermission`.
private pendingToolResolvers = new Map<
string,
{
request: PermissionPrompt;
resolve: (resp: PermissionDecision) => void;
}
>();
// Pending AskUserQuestion resolvers keyed by requestId. Populated by
// `handleAskUserQuestion` when the wrapped ask-question prompter routes a
// request to this session; the inline `AskUserQuestionCard` resolves them
// through `resolveAskUserQuestion`.
private pendingQuestionResolvers = new Map<
string,
{
request: AskUserQuestionPrompt;
resolve: (answers: AgentQuestionAnswers) => void;
}
>();
// Singleton "current plan" for the floating card. At most one per session
// while in canonical plan mode and a plan has been proposed; cleared on a
// terminal user decision or when the canonical mode flips out of plan.
private currentPlan: CurrentPlan | null = null;
// Monotonic counter for `currentPlan.id` so the React tree can detect a
// *new* plan-mode review (vs. an in-place revision that bumps `revision`).
private planSeq = 0;
// Tool-call ids the user has already finalized a decision on.
private decidedPlanToolCallIds = new Set<string>();
// True when something happened (turn ended, error, permission prompt) while
// this session was not the active tab. The manager owns the policy for
// setting this; the session just exposes the flag and notification channel.
private needsAttention = false;
// Streaming backends emit `agent_message_chunk`/`agent_thought_chunk` and
// (for codex) `tool_call_update` at up to ~160 fps. We update the store
// immediately but coalesce the React-facing `onMessagesChanged` callback
// to one fire per animation frame so the trail doesn't rerender 200×/sec.
// Non-streaming callers use `notifyMessages()` directly for immediate
// flush on turn end / error / permission prompts.
private notifyScheduled = false;
private notifyHandle: ReturnType<typeof setTimeout> | number | null = null;
/** Prefer `AgentSession.start(...)` in production so backend startup runs async. */
constructor(opts: AgentSessionStateOptions | AgentSessionStartOptions) {
this.backend = opts.backend;
this.internalId = opts.internalId;
this.backendId = opts.backendId;
this.cwd = opts.cwd ?? null;
this.getDescriptor = opts.getDescriptor ?? null;
if ("backendSessionId" in opts) {
this.backendSessionId = opts.backendSessionId;
const originalState = opts.initialState ?? null;
this.currentState = seedSelectionIntoState(originalState, opts.defaultModelSelection);
this.unregisterSessionHandler = this.backend.registerSessionHandler(
opts.backendSessionId,
(event) => this.handleSessionEvent(event)
);
// Sync the status cache so the first recomputeStatusIfChanged doesn't
// fire a spurious "starting → idle" transition that no one observed.
this.cachedStatus = this.getStatus();
// Gate `ready` on the model confirmation round-trip so `sendPrompt`
// can't fire on the probe's model before the user's persisted
// selection is applied to the backend.
this.ready =
opts.defaultModelSelection && originalState
? this.confirmSeededSelection(opts.defaultModelSelection, originalState)
: Promise.resolve();
} else {
// Eagerly seed from the preloader cache so the picker doesn't fall
// back to the prior session's `current` while `backend.newSession` is
// in flight. `initialize()` replaces this with the agent's response.
this.currentState = seedSelectionIntoState(
opts.initialCachedState ?? null,
opts.defaultModelSelection
);
this.ready = this.initialize(opts);
}
}
/**
* Construct an `AgentSession` synchronously and kick off backend
* initialization in the background. The returned session is immediately
* registerable with the manager and renderable in the UI; `sendPrompt`
* is gated until `ready` resolves.
*/
static start(opts: AgentSessionStartOptions): AgentSession {
return new AgentSession(opts);
}
/** The backend session id, or null while still starting. */
getBackendSessionId(): SessionId | null {
return this.backendSessionId;
}
private async initialize(opts: AgentSessionStartOptions): Promise<void> {
const { backend, cwd, defaultModelSelection } = opts;
try {
const resp = await backend.newSession({
cwd,
mcpServers: resolveMcpServers(backend, getSettings().agentMode?.mcpServers),
});
if (this.disposed) return;
const modelLog = resp.state.model
? `model=${resp.state.model.current.baseModelId} (available: ${resp.state.model.availableModels
.map((m) => m.baseModelId)
.join(", ")})`
: "agent did not report model state";
logInfo(`[AgentMode] session ${resp.sessionId} ${modelLog}`);
this.backendSessionId = resp.sessionId;
this.currentState = seedSelectionIntoState(resp.state, defaultModelSelection);
this.unregisterSessionHandler = this.backend.registerSessionHandler(resp.sessionId, (event) =>
this.handleSessionEvent(event)
);
// dispose() may have run between newSession resolving and now.
if (this.disposed) {
this.unregisterSessionHandler();
this.unregisterSessionHandler = null;
return;
}
this.recomputeStatusIfChanged();
this.notifyModelChanged();
if (defaultModelSelection) {
await this.confirmSeededSelection(defaultModelSelection, resp.state);
}
} catch (err) {
if (this.disposed) return;
logWarn(`[AgentMode] session/new failed for ${this.internalId}`, err);
this.startupFailed = true;
this.recomputeStatusIfChanged();
throw err instanceof Error ? err : new Error(err2String(err));
}
}
/**
* Latest known unified picker state for this session — model catalog,
* canonical mode, canonical effort. `null` while the session is still
* starting and the agent hasn't reported anything yet.
*/
getState(): BackendState | null {
return this.currentState;
}
/**
* Switch the active model on this session. On success, replaces the
* cached `BackendState` with the freshly-translated one returned by the
* backend and notifies `onModelChanged` listeners.
*
* Throws `MethodUnsupportedError` if the backend does not support model
* switching. Callers should treat that as "model switching is not
* available" and degrade the UI accordingly.
*/
async setModel(modelId: string): Promise<void> {
if (this.getStatus() === "closed") throw new Error("Session is closed");
if (!this.backendSessionId) throw new Error("Session is still starting");
const next = await this.backend.setSessionModel({
sessionId: this.backendSessionId,
modelId,
});
this.currentState = next;
this.notifyModelChanged();
}
/**
* Apply an encoded model wire id through whichever channel the current model
* state declares. Backends whose catalog comes from a `category:"model"`
* config option (opencode ≥ 1.15.13) switch via `session/set_config_option`;
* everyone else via `session/set_model`. Falls back to `setModel` before any
* model state is known. The encoded wire id is identical for both channels.
*/
async applyModelWireId(wireId: string): Promise<void> {
const apply = this.currentState?.model?.apply;
if (apply?.kind === "setConfigOption") {
await this.setConfigOption(apply.configId, wireId);
return;
}
await this.setModel(wireId);
}
/**
* Apply the persisted user selection to the backend via `setModel`.
* Runs whenever `defaultModelSelection` is supplied — `setModel` is
* idempotent, and the wire-encoding short-circuit below makes it a
* pure no-op when the selection already matches the backend's report.
*
* On success the backend's response replaces `currentState`. On
* failure any optimistic baseModelId seed is reverted to `originalState`
* so the picker drops back to whatever the backend actually has.
*
* Skips the round-trip when the encoded form matches. For descriptor-
* style backends (Claude SDK) where effort lives outside the wire id,
* an effort-only change encodes the same and `setModel` is correctly
* skipped here — `applyInitialSessionConfig` dispatches the effort
* via `setConfigOption` instead.
*/
private async confirmSeededSelection(
selection: ModelSelection,
originalState: BackendState
): Promise<void> {
const descriptor = this.getDescriptor?.();
if (!descriptor) return;
const encoded = descriptor.wire.encode(selection);
const originalEncoded = originalState.model
? descriptor.wire.encode(originalState.model.current)
: null;
if (encoded === originalEncoded) return;
try {
await this.applyModelWireId(encoded);
} catch (e) {
logWarn(`[AgentMode] could not apply default model ${encoded}; reverting seed`, e);
this.currentState = originalState;
this.notifyModelChanged();
}
}
/**
* Set a session configuration option (e.g. effort). Reuses
* `notifyModelChanged` because the picker treats model and configOption
* changes as one channel.
*/
async setConfigOption(configId: string, value: string): Promise<void> {
if (this.getStatus() === "closed") throw new Error("Session is closed");
if (!this.backendSessionId) throw new Error("Session is still starting");
const next = await this.backend.setSessionConfigOption({
sessionId: this.backendSessionId,
configId,
value,
});
this.currentState = next;
this.notifyModelChanged();
this.clearCurrentPlanIfModeLeft();
}
/**
* Switch the active session mode (claude permission mode, codex
* sandbox preset, etc.). On success, replaces the cached state and
* notifies `onModelChanged` listeners.
*
* Throws `MethodUnsupportedError` when the backend doesn't support mode
* switching.
*/
async setMode(modeId: string): Promise<void> {
if (this.getStatus() === "closed") throw new Error("Session is closed");
if (!this.backendSessionId) throw new Error("Session is still starting");
const next = await this.backend.setSessionMode({
sessionId: this.backendSessionId,
modeId,
});
this.currentState = next;
this.notifyModelChanged();
this.clearCurrentPlanIfModeLeft();
}
/**
* Whether the user can swap the active model on this session. Config-option-
* backed catalogs (opencode ≥ 1.15.13) switch via `setConfigOption`; everyone
* else via `setModel`.
*/
canSwitchModel(): boolean | null {
if (this.getStatus() === "starting") return false;
return this.currentState?.model?.apply.kind === "setConfigOption"
? this.backend.isSetSessionConfigOptionSupported()
: this.backend.isSetSessionModelSupported();
}
/**
* Whether the user can swap effort. Descriptor-style backends (claude) and
* config-option-backed models (opencode ≥ 1.15.13) route effort via
* `setConfigOption`; suffix-style models that pack effort into the wire id
* (codex, older opencode) via `setModel`. The wire routing is encapsulated
* here — UI consumers ask intent only.
*/
canSwitchEffort(): boolean | null {
if (this.getStatus() === "starting") return false;
const descriptor = this.getDescriptor?.();
if (!descriptor) return null;
if (descriptor.wire.effortConfigFor) return this.backend.isSetSessionConfigOptionSupported();
return this.currentState?.model?.apply.kind === "setConfigOption"
? this.backend.isSetSessionConfigOptionSupported()
: this.backend.isSetSessionModelSupported();
}
/**
* Whether the user can swap modes. Each mode option carries its own
* apply spec (`setMode` or `setConfigOption`); within a single backend
* the dispatch path is consistent, so we sample the first option.
*/
canSwitchMode(): boolean | null {
if (this.getStatus() === "starting") return false;
const mode = this.currentState?.mode;
if (!mode) return null;
const sample = mode.options[0];
if (!sample) return null;
const spec = mode.apply[sample.value];
if (!spec) return null;
return spec.kind === "setConfigOption"
? this.backend.isSetSessionConfigOptionSupported()
: this.backend.isSetSessionModeSupported();
}
/**
* The status is derived from underlying primitives so it cannot drift
* from reality: any combination of `disposed`, `backendSessionId`,
* resolver-map sizes, `abortController`, `startupFailed`, and
* `lastTurnError` maps to exactly one status. Mutating any of those
* primitives implicitly transitions the status; consumers observe the
* change via `onStatusChanged` after `recomputeStatusIfChanged()` runs.
*/
getStatus(): AgentSessionStatus {
if (this.disposed) return "closed";
if (this.backendSessionId === null) {
return this.startupFailed ? "error" : "starting";
}
if (
this.pendingPlanResolvers.size +
this.pendingToolResolvers.size +
this.pendingQuestionResolvers.size >
0
) {
return "awaiting_permission";
}
if (this.abortController !== null) return "running";
if (this.lastTurnError) return "error";
return "idle";
}
getNeedsAttention(): boolean {
return this.needsAttention;
}
markNeedsAttention(): void {
if (this.needsAttention) return;
this.needsAttention = true;
this.notifyNeedsAttentionChanged();
}
clearNeedsAttention(): void {
if (!this.needsAttention) return;
this.needsAttention = false;
this.notifyNeedsAttentionChanged();
}
private notifyNeedsAttentionChanged(): void {
for (const l of this.listeners) {
try {
l.onNeedsAttentionChanged?.(this.needsAttention);
} catch (e) {
logWarn(`[AgentMode] needs-attention listener threw`, e);
}
}
}
/**
* Whether this session has at least one user-visible message. The model
* picker uses this to decide whether non-active backend entries should be
* hidden (mid-conversation) or shown (empty new tab).
*/
hasUserVisibleMessages(): boolean {
return this.store.getDisplayMessages().length > 0;
}
/**
* Replace the display transcript from persisted history (a markdown note or
* a backend's on-disk session store) and notify subscribers so an already-
* open chat view re-renders immediately. `store.loadMessages` alone mutates
* state without firing `onMessagesChanged`, so a freshly-activated tab would
* otherwise render blank until the next backend-identity change (e.g. the
* user switching tabs and back).
*/
loadDisplayMessages(messages: AgentChatMessage[]): void {
this.store.loadMessages(messages);
this.notifyMessages();
}
/**
* User-supplied label for this session (shown in the tab strip). `null`
* means "no label" — the UI falls back to a positional default like
* "Session N".
*/
getLabel(): string | null {
return this.label;
}
/**
* Who set the current label: `"user"` (Rename), `"agent"`
* (`session_info_update` / title poll), or `null` when unlabeled. The
* session index records this so a user rename survives native
* `listSessions` sweeps the same way it survives agent retitles here.
*/
getLabelSource(): "user" | "agent" | null {
return this.labelSource;
}
setLabel(label: string | null): void {
const next = label?.trim() ? label.trim() : null;
if (next === this.label) return;
this.label = next;
this.labelSource = next ? "user" : null;
this.notifyLabelChanged();
}
/**
* Apply a label pushed by the backend agent (via `session_info_update`).
* No-op when the user has already renamed this session — Rename wins so
* later agent-side title revisions don't blow away the user's choice.
*/
/**
* Apply a label restored from persisted history with its original source.
* A user-renamed title is reapplied as a sticky user rename; an agent or
* derived title is applied agent-sourced, so a resumed opencode/codex
* session can still refresh its title from later `session_info_update` /
* title-poll updates instead of being frozen as if the user had renamed it.
*/
restoreLabel(label: string, source: "user" | "agent"): void {
if (source === "user") this.setLabel(label);
else this.applyAgentLabel(label);
}
/**
* Whether this backend produces its own clean session titles (opencode). When
* false (codex, Claude Code) the session derives the tab label client-side and
* ignores any backend-provided title. Defaults to `true` when no descriptor is
* wired (legacy/test construction), preserving the prior trust-the-backend
* behavior.
*/
private backendSummarizesTitle(): boolean {
return this.getDescriptor?.()?.summarizesSessionTitle ?? true;
}
private applyAgentLabel(label: string | null | undefined): void {
if (this.labelSource === "user") return;
const next = label?.trim() ? label.trim() : null;
if (next === this.label) return;
this.label = next;
this.labelSource = next ? "agent" : null;
this.notifyLabelChanged();
}
private notifyLabelChanged(): void {
for (const l of this.listeners) {
try {
l.onLabelChanged?.();
} catch (e) {
logWarn(`[AgentMode] label listener threw`, e);
}
}
}
subscribe(listener: AgentSessionListener): () => void {
this.listeners.add(listener);
return () => this.listeners.delete(listener);
}
/**
* Submit a user prompt. Synchronously appends the user message + an empty
* assistant placeholder to the store and kicks off the backend prompt.
* Streaming session events mutate the placeholder in place. Returns:
* - `userMessageId`: id of the appended user message.
* - `turn`: promise that resolves with `StopReason` when the turn
* completes, or rejects on transport errors.
*/
sendPrompt(
displayText: string,
context?: MessageContext,
promptContent?: PromptContent[]
): { userMessageId: string; turn: Promise<StopReason> } {
const status = this.getStatus();
if (status === "starting") {
throw new Error("Session is still starting");
}
if (status === "running" || status === "awaiting_permission") {
throw new Error("Session already has a turn in flight");
}
if (status === "closed") {
throw new Error("Session is closed");
}
const userMessage: NewAgentChatMessage = {
message: displayText,
sender: USER_SENDER,
timestamp: formatDateTime(new Date()),
isVisible: true,
context,
};
const userMessageId = this.store.addMessage(userMessage);
const placeholder: NewAgentChatMessage = {
message: "",
sender: AI_SENDER,
timestamp: formatDateTime(new Date()),
isVisible: true,
parts: [],
};
this.placeholderId = this.store.addMessage(placeholder);
this.currentMessageIds = new Set();
this.notifyMessages();
// Backends without a title summarizer (codex, Claude Code) have no usable
// backend-provided title, so derive the tab label from the first user
// message. Recorded agent-sourced (not "user"), so a later Rename still wins.
if (this.label === null && !this.backendSummarizesTitle()) {
this.applyAgentLabel(deriveChatTitleFromMessages(this.store.getDisplayMessages()));
}
this.abortController = new AbortController();
// Clear any prior terminal error before the new turn starts so the
// derived status reflects the fresh `"running"` state. Both flips
// are recomputed together so listeners see one transition.
this.lastTurnError = false;
this.recomputeStatusIfChanged();
const turn = this.runTurn(displayText, context, promptContent);
return { userMessageId, turn };
}
private async runTurn(
displayText: string,
context: MessageContext | undefined,
promptContent?: PromptContent[]
): Promise<StopReason> {
const placeholderId = this.placeholderId;
const sessionId = this.backendSessionId!;
const turnStartedAt = Date.now();
try {
// Extract live Web Viewer content (reader-mode markdown, YouTube
// transcripts) just before the prompt is built so it reflects the page
// at send/flush time, not at compose time. Only take the async hop when
// there are web tabs — otherwise `backend.prompt` must be invoked
// synchronously within this turn (callers rely on that timing).
const hasWebTabs = (context?.webTabs?.length ?? 0) > 0;
const webTabBlock = hasWebTabs ? await serializeWebTabContext(context) : "";
const promptBlocks = buildPromptBlocks(displayText, context, promptContent, webTabBlock);
const req: PromptInput = {
sessionId,
prompt: promptBlocks,
};
const resp = await this.backend.prompt(req);
if (
placeholderId &&
resp.stopReason !== "cancelled" &&
!this.store.hasAssistantActivity(placeholderId)
) {
const message = buildEmptyTurnMessage(this.backendId, resp.stopReason);
logWarn(
`[AgentMode] ${this.backendId} completed a turn without assistant text or tool activity (stopReason=${resp.stopReason})`
);
this.store.markMessageError(placeholderId, message);
}
if (
placeholderId &&
this.store.markTurnComplete(placeholderId, resp.stopReason, Date.now() - turnStartedAt)
) {
this.notifyMessages();
}
// Some backends flush the prompt result before the turn's last content
// chunks (opencode + fast DeepSeek). Keep this placeholder reachable by
// `messageId` so those trailing chunks still land — except on an explicit
// cancel, where further output should stay suppressed.
if (placeholderId && resp.stopReason !== "cancelled") {
this.settledStream = { placeholderId, messageIds: this.currentMessageIds };
} else if (resp.stopReason === "cancelled") {
this.settledStream = null;
}
this.currentMessageIds = new Set();
if (this.placeholderId === placeholderId) this.placeholderId = null;
if (resp.stopReason === "end_turn") void this.pollSessionTitle();
return resp.stopReason;
} catch (err) {
logWarn(`[AgentMode] prompt failed`, err);
if (placeholderId) {
this.store.markMessageError(placeholderId, formatPromptFailure(err));
this.notifyMessages();
}
this.lastTurnError = true;
this.currentMessageIds = new Set();
if (this.placeholderId === placeholderId) this.placeholderId = null;
throw err;
} finally {
// Clearing `abortController` flips the derived status off `"running"`
// (to `"error"` if `lastTurnError`, else `"idle"`). Recompute after
// both the success path (no error) and the catch path (error set) so
// listeners see the single transition out of the in-flight state.
this.abortController = null;
this.recomputeStatusIfChanged();
}
}
/**
* Cancel any in-flight turn. The backend may still emit a few trailing
* session events before the prompt promise resolves with
* `stopReason: "cancelled"` — that's expected.
*
* Flushes any pending tool-permission and AskUserQuestion resolvers (rejects
* / empty answers respectively) so the inline cards disappear immediately
* (and the SDK sees a deny rather than a dangling promise) instead of waiting
* for the user to click them.
*/
async cancel(): Promise<void> {
const status = this.getStatus();
if (status !== "running" && status !== "awaiting_permission") return;
if (!this.backendSessionId) return;
if (this.pendingToolResolvers.size > 0) {
this.flushResolvers(this.pendingToolResolvers);
this.notifyMessages();
}
if (this.pendingQuestionResolvers.size > 0) {
this.flushQuestionResolvers();
this.notifyMessages();
}
try {
await this.backend.cancel({ sessionId: this.backendSessionId });
} catch (e) {
logWarn(`[AgentMode] cancel notification failed`, e);
}
this.abortController?.abort();
}
/** Detach from the backend. Does not cancel — call `cancel()` first. */
async dispose(): Promise<void> {
this.disposed = true;
this.unregisterSessionHandler?.();
this.unregisterSessionHandler = null;
this.flushResolvers(this.pendingPlanResolvers);
this.flushResolvers(this.pendingToolResolvers);
this.flushQuestionResolvers();
this.decidedPlanToolCallIds.clear();
this.currentPlan = null;
this.settledStream = null;
this.currentMessageIds = new Set();
// Fire the `"closed"` transition before clearing listeners so
// subscribers still observe it. `disposed = true` above guarantees
// `getStatus()` returns `"closed"` regardless of the other primitives.
this.recomputeStatusIfChanged();
this.cancelScheduledNotify();
this.listeners.clear();
}
/**
* Called by the wrapped permission prompter when an ExitPlanMode permission
* request arrives. Returns a promise the backend will await for the
* outcome; resolved by the chat card via `resolvePlanProposalPermission`.
*/
handlePlanProposalPermission(request: PermissionPrompt): Promise<PermissionDecision> {
const toolCallId = request.toolCall.toolCallId;
const exitPlan = tryReadExitPlanModeCall({
kind: request.toolCall.kind,
rawInput: request.toolCall.rawInput,
isPlanProposal: request.toolCall.isPlanProposal,
});
if (exitPlan) {
this.publishGatedPlan(toolCallId, exitPlan);
}
return new Promise<PermissionDecision>((resolve) => {
this.pendingPlanResolvers.set(toolCallId, { request, resolve });
this.recomputeStatusIfChanged();
this.notifyMessages();
});
}
/**
* Resolve a pending ExitPlanMode permission. `allow: true` selects the
* first allow_once option; `false` selects the first reject option (or
* cancels when no reject option is offered). When denying, an optional
* `denyMessage` is forwarded as the agent-visible deny reason — used by
* the plan card to ride user feedback through the same `canUseTool` deny
* instead of as a separate follow-up turn. No-op when no permission is
* pending for the given id (e.g. non-gated OpenCode proposals).
*/
resolvePlanProposalPermission(toolCallId: string, allow: boolean, denyMessage?: string): void {
const entry = this.pendingPlanResolvers.get(toolCallId);
if (!entry) return;
this.pendingPlanResolvers.delete(toolCallId);
const base = decisionFor(
entry.request,
allow ? PERMISSION_ALLOW_KINDS : PERMISSION_REJECT_KINDS
);
const decision: PermissionDecision = !allow && denyMessage ? { ...base, denyMessage } : base;
entry.resolve(decision);
this.recomputeStatusIfChanged();
this.notifyMessages();
}
/** Snapshot of the singleton plan, or `null` if there's nothing to review. */
getCurrentPlan(): CurrentPlan | null {
return this.currentPlan;
}
/**
* Drop the current plan once the user has decided. The UI gates the card
* render on `decision === "pending"`, so a terminal state is never visible
* to the user — clearing synchronously is fine.
*/
finalizePlanDecision(proposalId: string): boolean {
if (!this.currentPlan || this.currentPlan.id !== proposalId) return false;
if (this.currentPlan.pendingToolCallId) {
this.decidedPlanToolCallIds.add(this.currentPlan.pendingToolCallId);
}
this.currentPlan = null;
this.notifyCurrentPlanChanged();
return true;
}
private setCurrentPlan(next: Omit<CurrentPlan, "id" | "revision" | "decision">): void {
if (!this.currentPlan) {
this.planSeq += 1;
this.currentPlan = {
...next,
id: `plan-${this.internalId}-${this.planSeq}`,
revision: 1,
decision: "pending",
};
this.notifyCurrentPlanChanged();
return;
}
// Bump revision only when the body actually changed. Gating /
// pendingToolCallId / sourceFilePath flips are control-flow signals,
// not "the plan was revised in place" — they must propagate without
// resetting the per-tab `decided` state in `PlanPreviewView`, which
// keys on revision. MarkdownRenderer perf for body-identical
// republishes is already handled by React's primitive equality on
// the `planMarkdown` string in the consumer's effect deps.
const prev = this.currentPlan;
const bodyChanged = prev.body !== next.body;
const changed =
bodyChanged ||
prev.title !== next.title ||
prev.sourceFilePath !== next.sourceFilePath ||
prev.permissionGated !== next.permissionGated ||
prev.pendingToolCallId !== next.pendingToolCallId ||
prev.decision !== "pending";
if (!changed) return;