cli-jaw 2.17.75 → 2.17.77

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 (43) hide show
  1. package/dist/src/code-mode/manager.js +51 -7
  2. package/dist/src/code-mode/manager.js.map +1 -1
  3. package/dist/src/code-mode/normalize.js +3 -2
  4. package/dist/src/code-mode/normalize.js.map +1 -1
  5. package/dist/src/code-mode/session.js +10 -2
  6. package/dist/src/code-mode/session.js.map +1 -1
  7. package/dist/src/code-mode/store.js +265 -27
  8. package/dist/src/code-mode/store.js.map +1 -1
  9. package/dist/src/code-mode/wire.js +4 -1
  10. package/dist/src/code-mode/wire.js.map +1 -1
  11. package/dist/src/messaging/redact.js +8 -5
  12. package/dist/src/messaging/redact.js.map +1 -1
  13. package/dist/src/routes/code-native.js +56 -5
  14. package/dist/src/routes/code-native.js.map +1 -1
  15. package/dist/src/slack/blocks.js +22 -3
  16. package/dist/src/slack/blocks.js.map +1 -1
  17. package/dist/src/slack/bot.js +239 -26
  18. package/dist/src/slack/bot.js.map +1 -1
  19. package/dist/src/slack/events.js +99 -2
  20. package/dist/src/slack/events.js.map +1 -1
  21. package/dist/src/slack/identity.js +30 -0
  22. package/dist/src/slack/identity.js.map +1 -1
  23. package/dist/src/slack/ingress.js +5 -4
  24. package/dist/src/slack/ingress.js.map +1 -1
  25. package/package.json +1 -1
  26. package/public/dist/.vite/manifest.json +3 -3
  27. package/public/dist/assets/CodeCanvas-DLXPccm9.js +3 -0
  28. package/public/dist/assets/manager-CZcR8tfs.css +1 -0
  29. package/public/dist/assets/{manager-DIaOU2Vf.js → manager-HCkO4cai.js} +1 -1
  30. package/public/dist/manager/index.html +2 -2
  31. package/public/manager/src/code/CodeWorkbench.tsx +48 -4
  32. package/public/manager/src/code/ComposerFooter.tsx +21 -7
  33. package/public/manager/src/code/code-composer.css +1 -0
  34. package/public/manager/src/code/code-controller-draft-storage.ts +45 -6
  35. package/public/manager/src/code/code-controller-drafts.ts +14 -2
  36. package/public/manager/src/code/code-controller-runtime.ts +312 -17
  37. package/public/manager/src/code/code-controller-types.ts +43 -0
  38. package/public/manager/src/code/code-session-client.ts +22 -3
  39. package/public/manager/src/code/code-session-state.ts +1 -0
  40. package/public/manager/src/code/code-ulid.ts +19 -0
  41. package/public/manager/src/code/code-workbench.css +3 -0
  42. package/public/dist/assets/CodeCanvas-Ba7ROkA8.js +0 -3
  43. package/public/dist/assets/manager-DQjyj2aO.css +0 -1
@@ -2,13 +2,14 @@ import type {
2
2
  CodeContextUsage, CodeCreateSessionRequest, CodeModelCatalog, CodePatchSessionRequest,
3
3
  CodePermissionRequest, CodePromptReceipt, CodeSessionInfo, CodeWireEvent,
4
4
  } from '../../../../src/code-mode/wire';
5
- import type { CodeControllerModel, CodeControllerOptions, CodeSessionFilter, CodeTransportState } from './code-controller-types';
5
+ import type { CodeControllerModel, CodeControllerOptions, CodeSessionFilter, CodeTransportState, CodeSettingsField, CodeSettingsValue } from './code-controller-types';
6
6
  import { CodeClientError, codeBaseOrigin, createCodeSessionClient, type CodeGitInfo, type CodeSessionClient } from './code-session-client';
7
7
  import { emptyCodeSession, reduceCodeSession, codeSessionBusy, type CodeSessionState } from './code-session-state';
8
8
  import {
9
9
  acknowledgeCodeSend, acknowledgeCodeSteer, catalogSelection, codeDraftBook, createCodeDraft, persistCodeDraftBook, sessionSelection,
10
- type CodeDraft, type CodeDraftBook,
10
+ type CodeDraft, type CodeDraftBook, type CodePendingSettings,
11
11
  } from './code-controller-drafts';
12
+ import { ulid } from './code-ulid';
12
13
  import { loadCodeDraftStorage } from './code-controller-draft-storage';
13
14
  import { withPendingUserItem } from './pending-user-item';
14
15
  import { codeCanResume, codeCanRollback, codeCanStop, codeOperationId, codeResendCopy, type CodeResendReason } from './code-types';
@@ -51,7 +52,23 @@ const spent = (status: CodePromptReceipt['status']): boolean => status === 'fail
51
52
 
52
53
  /** A session draft the user is working on, whitespace included; recovery and late creates never overwrite it. */
53
54
  const meaningfulDraft = (draft: CodeDraft | undefined): boolean => !!draft && (draft.input.length > 0 || !!draft.retry
54
- || !!draft.stopTarget || !!draft.steer || draft.operation.kind !== 'idle');
55
+ || !!draft.stopTarget || !!draft.steer || !!draft.settings || draft.operation.kind !== 'idle');
56
+ const settingFields: CodeSettingsField[] = ['model', 'effort', 'permissionMode', 'thinking'];
57
+ /** Claude reads an unset thinking switch as on (the server stores it that way), so both sides compare as true. */
58
+ const settingValue = (source: CodeCreateSessionRequest | CodeSessionInfo, field: CodeSettingsField): CodeSettingsValue =>
59
+ field === 'thinking' && source.provider === 'claude' ? source.thinking ?? true : source[field] ?? null;
60
+ function overlay(selection: CodeCreateSessionRequest, settings: CodePendingSettings | null): CodeCreateSessionRequest {
61
+ const result = { ...selection };
62
+ for (const row of settings?.fields ?? []) {
63
+ if (row.field === 'thinking') { if (typeof row.value === 'boolean') result.thinking = row.value; else delete result.thinking; }
64
+ else if (row.field === 'model' && typeof row.value === 'string') result.model = row.value;
65
+ else if (row.field === 'effort' && (typeof row.value === 'string' || row.value === null)) result.effort = row.value;
66
+ else if (row.field === 'permissionMode' && typeof row.value === 'string') result.permissionMode = row.value as CodeCreateSessionRequest['permissionMode'];
67
+ }
68
+ return result;
69
+ }
70
+ /** The higher of two mutation ids; ULIDs order as strings. */
71
+ const maxId = (a: string | null, b: string | null): string | null => a === null ? b : b === null ? a : a > b ? a : b;
55
72
 
56
73
  /**
57
74
  * Did the transcript already settle the turn this send belongs to?
@@ -125,6 +142,9 @@ export class CodeController {
125
142
  private listeners = new Set<() => void>();
126
143
  private model: CodeControllerModel;
127
144
  private draftSyncQueued = false;
145
+ private settingsToken = 0;
146
+ private settingsTimers = new Map<CodeDraft, ReturnType<typeof setTimeout>>();
147
+ private settingsDelays = new Map<CodeDraft, number>();
128
148
 
129
149
  constructor(options: CodeControllerOptions) {
130
150
  this.client = createCodeSessionClient(options.port);
@@ -159,9 +179,14 @@ export class CodeController {
159
179
  this.book.listeners.add(this.changed);
160
180
  void this.refresh();
161
181
  return () => {
162
- persistCodeDraftBook(this.book);
163
182
  this.active = false;
164
183
  this.lifetime++;
184
+ for (const draft of [this.book.fresh, ...this.book.sessions.values()]) {
185
+ if (draft.settings?.op) { draft.settings.op = null; if (draft.settings.state === 'sent') draft.settings.state = 'unknown'; }
186
+ }
187
+ for (const timer of this.settingsTimers.values()) clearTimeout(timer);
188
+ this.settingsTimers.clear(); this.settingsDelays.clear();
189
+ persistCodeDraftBook(this.book);
165
190
  this.abort.abort();
166
191
  this.syncing.clear();
167
192
  for (const read of this.detailReads.values()) read.abort();
@@ -404,7 +429,7 @@ export class CodeController {
404
429
  selectedId: id, session, items: withPendingUserItem(draft, detail?.items ?? []),
405
430
  hasUnsentDraft: !!this.book.fresh.input.trim() || this.book.fresh.createUnknown || !!this.book.fresh.retry,
406
431
  permissions: detail?.permissions ?? [],
407
- input: draft.input, selection: session ? sessionSelection(session) : draft.selection,
432
+ input: draft.input, selection: overlay(session ? sessionSelection(session) : draft.selection, draft.settings),
408
433
  gitInfo: this.gitInfo, loading: this.indexLoading || !!detail?.hydrating || (!!id && !detail?.hydrated && !detail?.error),
409
434
  pending, busy: codeSessionBusy(session), working: !!draft.awaitingTurn || codeSessionBusy(session),
410
435
  workingIds: new Set([...this.rows, ...this.pinnedOverlay.map(row => row.sessionId)].filter(rowId => {
@@ -413,11 +438,17 @@ export class CodeController {
413
438
  })), followUp, followUpSent, steering: draft.steer?.state === 'sending', synced, transport: this.transport, workspacePicking: this.workspacePicking,
414
439
  error: [operation.error ?? unconfirmed ?? detail?.error ?? this.indexError ?? this.catalogError ?? this.gitError ?? session?.error?.message, persistenceWarning].filter(Boolean).join(' ') || null,
415
440
  operation: { ...operation, error: operation.error && persistenceWarning ? `${operation.error} ${persistenceWarning}` : operation.error }, retryText: draft.retry?.text ?? null,
416
- canRetrySameSend: !!id && operation.kind === 'unknown-send' && !!draft.retry && synced && session?.archivedAt === null,
441
+ canRetrySameSend: !!id && !draft.settings && operation.kind === 'unknown-send' && !!draft.retry && synced && session?.archivedAt === null,
417
442
  resendRequired: !!draft.retry?.resend, resendReason: draft.retry?.resend ? draft.retry.resendReason ?? null : null,
418
443
  permissionOperations: { ...draft.permissionOperations }, hasMoreSessions: this.moreSessions,
419
444
  hasOlderHistory: detail?.hasOlder ?? false, filter: this.filter,
420
- creationUnknown: id === null && draft.createUnknown, restoring: id !== null && !!draft.restore && !draft.restore.stopRequested,
445
+ creationUnknown: id === null && draft.createUnknown, creationPending: id === null && (draft.createUnknown || draft.operation.kind === 'creating'),
446
+ settings: draft.settings ? { state: draft.settings.state, fields: draft.settings.fields.map(row => ({ field: row.field, baseline: row.baseline, value: row.value,
447
+ ...(row.conflict ? { theirs: row.conflict.theirs, ...(row.conflict.resolution ? { resolution: row.conflict.resolution } : {}) } : {}) })),
448
+ expired: draft.settings.expired, busy: !!draft.settings.op, waitingForSession: id === null, error: draft.settings.error } : null,
449
+ restoring: id !== null && !!draft.restore && !draft.restore.stopRequested,
450
+ checkSettings: this.checkSettings, reapplySettings: this.reapplySettings, discardSettings: this.discardSettings,
451
+ resolveSettingsConflict: this.resolveSettingsConflict, applyResolvedSettings: this.applyResolvedSettings,
421
452
  startAnotherSession: this.startAnotherSession,
422
453
  newSession: this.newSession, selectSession: this.selectSession, setInput: this.setInput,
423
454
  setSelection: this.setSelection, pickWorkspace: this.pickWorkspace, send: this.send,
@@ -589,11 +620,20 @@ export class CodeController {
589
620
  if (transport === 'connected' && this.active) {
590
621
  void this.readIndex();
591
622
  for (const id of this.details.keys()) void this.sync(id, true);
623
+ for (const [id, draft] of this.book.sessions) {
624
+ if (draft.settings?.state === 'unknown' && !draft.settings.expired) { this.clearSettingsTimer(draft); this.scheduleSettingsLookup(id, draft, true); }
625
+ }
592
626
  }
593
627
  };
594
628
  refresh = async (): Promise<void> => {
595
629
  const id = this.book.selectedId;
596
630
  await Promise.all([this.readCatalog(), this.readIndex(), id ? this.sync(id, true) : Promise.resolve(), this.readGit(), this.reconnectCreation()]);
631
+ if (!this.active) return;
632
+ for (const [sessionId, draft] of this.book.sessions) {
633
+ if (draft.settings?.state === 'unknown' && !draft.settings.expired) this.scheduleSettingsLookup(sessionId, draft, true);
634
+ // A batch that already used its automatic retry waits for an explicit Apply, across reloads too.
635
+ else if (draft.settings?.state === 'pending' && !draft.settings.op && !draft.settings.autoRetried) void this.resumePendingSettings(sessionId, draft);
636
+ }
597
637
  };
598
638
  private async reconnectCreation(): Promise<void> {
599
639
  const draft = this.book.fresh, key = draft.creationKey, life = this.lifetime, navigation = this.book.navigation;
@@ -606,7 +646,8 @@ export class CodeController {
606
646
  const existing = this.book.sessions.get(found.sessionId);
607
647
  draft.creationKey = null; draft.createUnknown = false;
608
648
  if (meaningfulDraft(existing)) {
609
- draft.operation = { kind: 'idle', error: 'The original session was found and already has its own draft. This text stays here as a new draft; sending it creates another session.' };
649
+ draft.selection = overlay(draft.selection, draft.settings); draft.settings = null;
650
+ draft.operation = { kind: 'idle', error: 'The original session was found and already has its own draft. This text and settings stay here as a new draft; sending it creates another session.' };
610
651
  } else {
611
652
  draft.operation = { kind: 'idle', error: null };
612
653
  this.book.sessions.set(found.sessionId, draft);
@@ -614,8 +655,9 @@ export class CodeController {
614
655
  if (this.book.selectedId === null && this.book.navigation === navigation) {
615
656
  this.book.selectedId = found.sessionId; this.book.navigation++;
616
657
  this.state(found.sessionId);
617
- void this.sync(found.sessionId, true);
618
658
  }
659
+ this.notify();
660
+ if (draft.settings) await this.resumePendingSettings(found.sessionId, draft);
619
661
  }
620
662
  this.scheduleIndex(); this.notify();
621
663
  } catch (error) {
@@ -628,7 +670,7 @@ export class CodeController {
628
670
  startAnotherSession = (): void => {
629
671
  const previous = this.book.fresh;
630
672
  if (this.book.selectedId !== null || !previous.createUnknown) return;
631
- const draft = createCodeDraft(previous.selection);
673
+ const draft = createCodeDraft(overlay(previous.selection, previous.settings));
632
674
  draft.input = previous.input; draft.edit = previous.edit; draft.selectionEdit = previous.selectionEdit;
633
675
  draft.operation.error = 'The original session may still exist. Your text is preserved; Send will create another session.';
634
676
  this.book.fresh = draft;
@@ -706,12 +748,20 @@ export class CodeController {
706
748
  setSelection = async (patch: Partial<CodeCreateSessionRequest>): Promise<void> => {
707
749
  const id = this.book.selectedId;
708
750
  const session = this.info(id);
751
+ const draft = this.draft();
752
+ const creating = !id && (draft.operation.kind === 'creating' || draft.createUnknown);
753
+ if (draft.settings && (!creating || draft.settings.state !== 'pending' || draft.settings.op)) return;
709
754
  if (session && patch.provider && patch.provider !== session.provider) {
710
755
  this.newSession();
711
756
  await this.setSelection({ ...patch, cwd: session.cwd });
712
757
  return;
713
758
  }
714
- const draft = this.draft();
759
+ if (creating) {
760
+ if ((patch.provider !== undefined && patch.provider !== draft.selection.provider) || (patch.cwd !== undefined && patch.cwd !== draft.selection.cwd)) {
761
+ draft.operation.error = 'Runtime and workspace cannot change while session creation is unconfirmed.'; this.notify(); return;
762
+ }
763
+ this.editSettings(draft, draft.selection, patch); this.notify(); return;
764
+ }
715
765
  if (draft.operation.kind !== 'idle' || draft.createUnknown) return;
716
766
  if (session && id) {
717
767
  if ((patch.cwd !== undefined && patch.cwd !== session.cwd) || (patch.provider && patch.provider !== session.provider)) {
@@ -722,10 +772,9 @@ export class CodeController {
722
772
  draft.operation.error = 'Wait for this session to be idle and synchronized before changing settings.';
723
773
  this.notify(); return;
724
774
  }
725
- await this.patch(id, { model: patch.model ?? session.model,
726
- effort: patch.effort === undefined ? session.effort : patch.effort,
727
- permissionMode: patch.permissionMode ?? session.permissionMode,
728
- ...(session.provider === 'claude' ? { thinking: patch.thinking ?? session.thinking ?? true } : {}) });
775
+ this.editSettings(draft, session, patch);
776
+ this.notify();
777
+ if (draft.settings) await this.applySettings(id, draft);
729
778
  return;
730
779
  }
731
780
  if (id) return;
@@ -739,6 +788,236 @@ export class CodeController {
739
788
  this.notify();
740
789
  if (patch.cwd !== undefined) await this.readGit();
741
790
  };
791
+ private editSettings(draft: CodeDraft, baseline: CodeCreateSessionRequest | CodeSessionInfo, patch: Partial<CodeCreateSessionRequest>): void {
792
+ const batch = draft.settings ?? { fields: [], state: 'pending', mutationId: null, expectedRevision: null, watermark: null,
793
+ expired: false, autoRetried: false, retryReady: false, error: null, op: null } satisfies CodePendingSettings;
794
+ for (const field of settingFields) {
795
+ if (patch[field] === undefined) continue;
796
+ const value = patch[field] ?? null;
797
+ const existing = batch.fields.find(row => row.field === field);
798
+ const original = existing?.baseline ?? settingValue(baseline, field);
799
+ batch.fields = batch.fields.filter(row => row.field !== field);
800
+ if (value !== original) batch.fields.push({ field, baseline: original, value });
801
+ }
802
+ draft.settings = batch.fields.length ? batch : null;
803
+ }
804
+ private clearSettingsTimer(draft: CodeDraft): void {
805
+ const timer = this.settingsTimers.get(draft); if (timer !== undefined) clearTimeout(timer);
806
+ this.settingsTimers.delete(draft); this.settingsDelays.delete(draft);
807
+ }
808
+ private settingsOwner(id: string, draft: CodeDraft, batch: CodePendingSettings, token: number, mutationId: string | null, life: number): boolean {
809
+ return this.active && this.lifetime === life && this.book.sessions.get(id) === draft && draft.settings === batch
810
+ && batch.mutationId === mutationId && batch.op?.token === token;
811
+ }
812
+ private compareSettings(batch: CodePendingSettings, session: CodeSessionInfo): boolean {
813
+ batch.fields = batch.fields.filter(row => settingValue(session, row.field) !== row.value);
814
+ let conflict = false;
815
+ for (const row of batch.fields) {
816
+ const theirs = settingValue(session, row.field);
817
+ if (theirs !== row.baseline) { row.conflict = { theirs }; conflict = true; }
818
+ else delete row.conflict;
819
+ }
820
+ return conflict;
821
+ }
822
+ /**
823
+ * The server recorded this batch's id as `rejected_conflict`, however the client learned it
824
+ * (a 409, a lookup, a fence). A field another client changed asks for a choice; otherwise the
825
+ * batch rebases on the current values and retries once on its own, then waits for Apply.
826
+ * Returns true when the caller should send now. The rejected id is ledgered, so no fence is needed.
827
+ */
828
+ private reconcileRejected(draft: CodeDraft, batch: CodePendingSettings, session: CodeSessionInfo, mutationId: string): boolean {
829
+ batch.watermark = maxId(batch.watermark, mutationId);
830
+ if (this.compareSettings(batch, session)) { batch.state = 'conflict'; batch.error = 'Session settings changed elsewhere.'; return false; }
831
+ if (!batch.fields.length) { draft.settings = null; return false; }
832
+ for (const row of batch.fields) row.baseline = settingValue(session, row.field);
833
+ batch.state = 'pending'; batch.mutationId = null;
834
+ // The retry counts as used only when it is dispatched (applySettings), so an interruption
835
+ // before then leaves it ready to resume rather than spent.
836
+ if (!batch.autoRetried) { batch.retryReady = true; batch.error = null; return true; }
837
+ batch.error = 'Session settings changed again elsewhere. Apply your settings again or discard them.';
838
+ return false;
839
+ }
840
+ private async syncSettings(id: string, current: () => boolean): Promise<void> {
841
+ const existing = this.syncing.get(id);
842
+ if (existing) { await existing; if (!current()) return; }
843
+ if (current()) await this.sync(id, true);
844
+ }
845
+ private async resumePendingSettings(id: string, draft: CodeDraft): Promise<void> {
846
+ const batch = draft.settings, life = this.lifetime;
847
+ if (!batch || batch.state !== 'pending' || batch.op || !this.active) return;
848
+ const token = ++this.settingsToken, mutationId = batch.mutationId;
849
+ batch.op = { token, kind: 'check' }; this.notify();
850
+ await this.syncSettings(id, () => this.settingsOwner(id, draft, batch, token, mutationId, life));
851
+ if (!this.settingsOwner(id, draft, batch, token, mutationId, life)) return;
852
+ batch.op = null;
853
+ if (!this.details.get(id)?.synced || this.details.get(id)?.error) { batch.error = 'Could not refresh the session to apply settings.'; this.notify(); return; }
854
+ await this.applySettings(id, draft);
855
+ }
856
+ private async applySettings(id: string, draft: CodeDraft): Promise<void> {
857
+ const batch = draft.settings, session = this.info(id);
858
+ if (!this.active || !batch || batch.state !== 'pending' || batch.op || !session) return;
859
+ if (this.compareSettings(batch, session)) { batch.state = 'conflict'; batch.error = 'Session settings changed elsewhere.'; this.notify(); return; }
860
+ if (!batch.fields.length) { draft.settings = null; this.notify(); return; }
861
+ try { batch.mutationId = ulid(Date.now(), batch.watermark); }
862
+ catch (error) { batch.error = error instanceof Error ? error.message : 'Could not create a settings identity.'; this.notify(); return; }
863
+ batch.expectedRevision = session.revision; batch.state = 'sent'; batch.error = null;
864
+ // A ready automatic retry is spent in the same checkpoint that records it as sent.
865
+ const wasReady = batch.retryReady, wasRetried = batch.autoRetried;
866
+ if (wasReady) { batch.autoRetried = true; batch.retryReady = false; }
867
+ const mutationId = batch.mutationId, token = ++this.settingsToken, life = this.lifetime;
868
+ batch.op = { token, kind: 'send' }; this.notify();
869
+ const saved = this.book.storage && loadCodeDraftStorage(this.book.storage, this.book.endpoint).data?.sessions.find(row => row.id === id)?.draft.settings;
870
+ if (!saved || saved.state !== 'sent' || saved.mutationId !== mutationId) {
871
+ batch.state = 'pending'; batch.mutationId = null; batch.op = null; batch.retryReady = wasReady; batch.autoRetried = wasRetried;
872
+ batch.error = 'Draft recovery could not save the settings change, so it was not sent.'; this.notify(); return;
873
+ }
874
+ const patch: CodePatchSessionRequest = { expectedRevision: session.revision, clientMutationId: mutationId,
875
+ model: session.model, effort: session.effort, permissionMode: session.permissionMode,
876
+ ...(session.provider === 'claude' && session.thinking !== null ? { thinking: session.thinking } : {}) };
877
+ for (const row of batch.fields) {
878
+ if (row.field === 'model' && typeof row.value === 'string') patch.model = row.value;
879
+ else if (row.field === 'effort' && (typeof row.value === 'string' || row.value === null)) patch.effort = row.value;
880
+ else if (row.field === 'permissionMode' && typeof row.value === 'string') patch.permissionMode = row.value as CodeCreateSessionRequest['permissionMode'];
881
+ else if (row.field === 'thinking' && typeof row.value === 'boolean') patch.thinking = row.value;
882
+ }
883
+ let retry = false;
884
+ try {
885
+ const result = await this.client.patchSettings(id, patch);
886
+ if (!this.settingsOwner(id, draft, batch, token, mutationId, life)) return;
887
+ this.accept(result.session); draft.settings = null;
888
+ } catch (error) {
889
+ if (!this.settingsOwner(id, draft, batch, token, mutationId, life)) return;
890
+ if (error instanceof CodeClientError && error.code === 'revision_conflict' && error.session?.sessionId === id) {
891
+ this.observe(error.session); this.accept(error.session);
892
+ batch.watermark = maxId(batch.watermark, error.watermark ?? null);
893
+ retry = this.reconcileRejected(draft, batch, error.session, mutationId);
894
+ } else if (error instanceof CodeClientError && error.code === 'mutation_fenced') {
895
+ batch.state = 'rejected'; batch.error = error.message;
896
+ } else if (error instanceof CodeClientError && error.status === 410 && error.code === 'mutation_outcome_expired') {
897
+ batch.state = 'unknown'; batch.expired = true; batch.watermark = error.watermark ?? batch.watermark; batch.error = error.message;
898
+ } else {
899
+ const definite = error instanceof CodeClientError && ((error.status === 400 && (/^(invalid_|unsupported_)/.test(error.code) || ['unknown_field', 'empty_patch'].includes(error.code)))
900
+ || (error.status === 404 && error.code === 'session_not_found') || (error.status === 409 && ['session_busy', 'resume_unavailable', 'session_archived', 'cleanup_pending', 'mutation_id_conflict'].includes(error.code)));
901
+ batch.state = definite ? 'rejected' : 'unknown'; batch.error = message(error);
902
+ }
903
+ }
904
+ if (draft.settings === batch) batch.op = null;
905
+ this.notify(); this.scheduleIndex();
906
+ if (retry && draft.settings === batch) await this.applySettings(id, draft);
907
+ else if (draft.settings === batch && batch.state === 'unknown' && !batch.expired) this.scheduleSettingsLookup(id, draft);
908
+ }
909
+ private scheduleSettingsLookup(id: string, draft: CodeDraft, immediate = false): void {
910
+ if (!this.active || this.settingsTimers.has(draft) || draft.settings?.state !== 'unknown' || draft.settings.expired) return;
911
+ const delay = immediate ? 0 : this.settingsDelays.get(draft) ?? 1000;
912
+ this.settingsDelays.set(draft, Math.min(delay ? delay * 2 : 1000, 30000));
913
+ this.settingsTimers.set(draft, setTimeout(() => {
914
+ this.settingsTimers.delete(draft); void this.lookupSettings(id, draft, 'lookup');
915
+ }, delay));
916
+ }
917
+ private async lookupSettings(id: string, draft: CodeDraft, kind: 'lookup' | 'check'): Promise<void> {
918
+ const batch = draft.settings;
919
+ if (!this.active || !batch || batch.state !== 'unknown' || batch.expired || !batch.mutationId || batch.op) return;
920
+ const mutationId = batch.mutationId, token = ++this.settingsToken, life = this.lifetime;
921
+ batch.op = { token, kind }; this.notify();
922
+ let retry = false;
923
+ try {
924
+ const { mutation, watermark } = await this.client.readMutation(id, mutationId);
925
+ if (!this.settingsOwner(id, draft, batch, token, mutationId, life)) return;
926
+ batch.watermark = maxId(batch.watermark, watermark);
927
+ if (mutation.status === 'applied' || mutation.status === 'rejected_conflict') {
928
+ await this.syncSettings(id, () => this.settingsOwner(id, draft, batch, token, mutationId, life));
929
+ if (!this.settingsOwner(id, draft, batch, token, mutationId, life)) return;
930
+ if (!this.details.get(id)?.synced || this.details.get(id)?.error) throw new Error('Session refresh failed');
931
+ }
932
+ if (mutation.status === 'applied') { draft.settings = null; this.clearSettingsTimer(draft); }
933
+ else if (mutation.status === 'rejected_conflict') {
934
+ const session = this.info(id);
935
+ if (session) retry = this.reconcileRejected(draft, batch, session, mutationId);
936
+ else { batch.state = 'unknown'; batch.error = 'Could not refresh the session to review settings.'; }
937
+ } else { batch.state = 'rejected'; batch.error = 'This settings change was fenced before it applied.'; }
938
+ } catch (error) {
939
+ if (!this.settingsOwner(id, draft, batch, token, mutationId, life)) return;
940
+ if (error instanceof CodeClientError && error.status === 410) { batch.expired = true; batch.watermark = error.watermark ?? batch.watermark; }
941
+ if (!(error instanceof CodeClientError && error.code === 'mutation_not_found')) batch.error = message(error);
942
+ }
943
+ if (draft.settings === batch) batch.op = null;
944
+ this.notify();
945
+ if (retry && draft.settings === batch) await this.applySettings(id, draft);
946
+ else if (draft.settings === batch && batch.state === 'unknown' && !batch.expired) this.scheduleSettingsLookup(id, draft);
947
+ }
948
+ checkSettings = async (): Promise<void> => {
949
+ const id = this.book.selectedId; if (!id) return;
950
+ const draft = this.draft(id); this.clearSettingsTimer(draft); await this.lookupSettings(id, draft, 'check');
951
+ };
952
+ private async settleSettings(action: 'discard' | 'reapply'): Promise<void> {
953
+ const id = this.book.selectedId, draft = this.draft(id), batch = draft.settings;
954
+ if (!batch || batch.op) return;
955
+ // Nothing of a pending batch reached the server (or it was rejected and recorded), so no fence.
956
+ if (batch.state === 'pending') {
957
+ if (action === 'discard') { draft.settings = null; this.notify(); }
958
+ else if (id) { batch.error = null; await this.resumePendingSettings(id, draft); }
959
+ return;
960
+ }
961
+ if (!id || batch.state === 'conflict') {
962
+ if (action === 'discard') { draft.settings = null; this.notify(); }
963
+ return;
964
+ }
965
+ if (!['unknown', 'rejected'].includes(batch.state) || !batch.mutationId) return;
966
+ this.clearSettingsTimer(draft);
967
+ const mutationId = batch.mutationId, token = ++this.settingsToken, life = this.lifetime;
968
+ batch.op = { token, kind: 'fence' }; this.notify();
969
+ let outcome: 'fenced' | 'applied' | 'rejected_conflict' = 'fenced';
970
+ try {
971
+ if (!batch.expired) {
972
+ const fenced = await this.client.fenceMutation(id, mutationId);
973
+ outcome = fenced.mutation.status;
974
+ if (this.settingsOwner(id, draft, batch, token, mutationId, life)) batch.watermark = maxId(batch.watermark, fenced.watermark);
975
+ }
976
+ if (!this.settingsOwner(id, draft, batch, token, mutationId, life)) return;
977
+ } catch (error) {
978
+ if (!this.settingsOwner(id, draft, batch, token, mutationId, life)) return;
979
+ if (error instanceof CodeClientError && error.status === 410) { batch.watermark = error.watermark ?? batch.watermark; batch.expired = true; }
980
+ else { batch.op = null; batch.error = message(error); this.notify(); if (batch.state === 'unknown') this.scheduleSettingsLookup(id, draft); return; }
981
+ }
982
+ if (outcome === 'applied' || outcome === 'rejected_conflict') {
983
+ await this.syncSettings(id, () => this.settingsOwner(id, draft, batch, token, mutationId, life));
984
+ if (!this.settingsOwner(id, draft, batch, token, mutationId, life)) return;
985
+ if (!this.details.get(id)?.synced || this.details.get(id)?.error) { batch.op = null; batch.error = 'Could not refresh the session to review settings.'; this.notify(); return; }
986
+ }
987
+ let retry = false;
988
+ if (outcome === 'applied' || (outcome === 'rejected_conflict' && action === 'discard')) draft.settings = null;
989
+ else if (outcome === 'rejected_conflict') {
990
+ const session = this.info(id);
991
+ if (!session) { batch.op = null; batch.error = 'Could not refresh the session to review settings.'; this.notify(); return; }
992
+ // An explicit Re-apply earns its own automatic rebase.
993
+ batch.autoRetried = false;
994
+ batch.retryReady = false;
995
+ retry = this.reconcileRejected(draft, batch, session, mutationId);
996
+ } else if (action === 'discard') draft.settings = null;
997
+ else { batch.state = 'pending'; batch.watermark = maxId(batch.watermark, mutationId);
998
+ batch.expired = false; batch.autoRetried = false; batch.retryReady = false; batch.error = null; batch.mutationId = null; retry = true; }
999
+ if (draft.settings === batch) batch.op = null;
1000
+ this.notify();
1001
+ if (retry && action === 'reapply' && draft.settings === batch && batch.state === 'pending') await this.applySettings(id, draft);
1002
+ }
1003
+ reapplySettings = async (): Promise<void> => { await this.settleSettings('reapply'); };
1004
+ discardSettings = async (): Promise<void> => { await this.settleSettings('discard'); };
1005
+ resolveSettingsConflict = (field: CodeSettingsField, choice: 'mine' | 'theirs'): void => {
1006
+ const batch = this.draft().settings;
1007
+ const row = batch?.fields.find(item => item.field === field);
1008
+ if (!batch || batch.state !== 'conflict' || batch.op || !row?.conflict) return;
1009
+ row.conflict.resolution = choice; this.notify();
1010
+ };
1011
+ applyResolvedSettings = async (): Promise<void> => {
1012
+ const id = this.book.selectedId, draft = this.draft(id), batch = draft.settings, session = this.info(id);
1013
+ if (!id || !batch || batch.state !== 'conflict' || batch.op || !session || batch.fields.some(row => row.conflict && !row.conflict.resolution)) return;
1014
+ batch.fields = batch.fields.filter(row => row.conflict?.resolution !== 'theirs');
1015
+ for (const row of batch.fields) { if (row.conflict) row.baseline = row.conflict.theirs; delete row.conflict; }
1016
+ if (!batch.fields.length) { draft.settings = null; this.notify(); return; }
1017
+ if (batch.mutationId && (!batch.watermark || batch.mutationId > batch.watermark)) batch.watermark = batch.mutationId;
1018
+ batch.state = 'pending'; batch.mutationId = null; batch.autoRetried = false; batch.retryReady = false; batch.error = null; this.notify();
1019
+ await this.applySettings(id, draft);
1020
+ };
742
1021
  private async patch(id: string, input: Omit<CodePatchSessionRequest, 'expectedRevision'>, rejectFailure = false): Promise<void> {
743
1022
  const draft = this.draft(id);
744
1023
  const session = this.info(id);
@@ -849,6 +1128,7 @@ export class CodeController {
849
1128
  let id = this.book.selectedId;
850
1129
  let draft = this.draft(id);
851
1130
  if (draft.operation.kind !== 'idle' || draft.createUnknown || !draft.input.trim() || draft.steer?.state === 'sending') return;
1131
+ if (draft.settings) { draft.operation.error = 'Apply or discard pending settings before sending.'; this.notify(); return; }
852
1132
  let session = this.info(id);
853
1133
  const captured = { text: draft.input, edit: draft.edit, key: crypto.randomUUID() };
854
1134
  let attachToken: number | null = null;
@@ -905,7 +1185,8 @@ export class CodeController {
905
1185
  // started there stays, and ownership of the captured text is no longer clear.
906
1186
  if (meaningfulDraft(this.book.sessions.get(id)) && this.book.sessions.get(id) !== draft) {
907
1187
  this.accept(created);
908
- draft.operation = { kind: 'idle', error: 'The new session already has its own draft, so this text stayed here and was not sent. Sending it creates another session.' };
1188
+ draft.selection = overlay(draft.selection, draft.settings); draft.settings = null;
1189
+ draft.operation = { kind: 'idle', error: 'The new session already has its own draft, so this text and settings stayed here and were not sent. Sending it creates another session.' };
909
1190
  this.notify(); this.scheduleIndex(); return;
910
1191
  }
911
1192
  this.book.sessions.set(id, draft);
@@ -916,10 +1197,23 @@ export class CodeController {
916
1197
  }
917
1198
  this.accept(created);
918
1199
  if (this.active) this.state(id);
1200
+ draft.operation = { kind: 'idle', error: null };
1201
+ this.notify();
1202
+ if (draft.settings) {
1203
+ await this.resumePendingSettings(id, draft);
1204
+ if (draft.settings || !this.active) {
1205
+ draft.operation = { kind: 'idle', error: 'Your message was not sent because the pending settings are not applied yet.' };
1206
+ this.notify(); return;
1207
+ }
1208
+ }
919
1209
  this.scheduleIndex();
920
1210
  } catch (error) {
921
1211
  draft.createUnknown = !rejected(error);
922
- if (!draft.createUnknown) draft.creationKey = null;
1212
+ if (!draft.createUnknown) {
1213
+ draft.creationKey = null;
1214
+ // Nothing was created, so the queued edits are simply this draft's choices again.
1215
+ draft.selection = overlay(draft.selection, draft.settings); draft.settings = null;
1216
+ }
923
1217
  draft.operation = { kind: draft.createUnknown ? 'creating' : 'idle', error: draft.createUnknown
924
1218
  ? 'Session creation could not be confirmed. The original session may exist. Refresh the list, or choose Start another session to keep this text in a new draft.' : message(error) };
925
1219
  this.notify(); this.scheduleIndex(); return;
@@ -927,6 +1221,7 @@ export class CodeController {
927
1221
  }
928
1222
  draft = this.draft(id);
929
1223
  if (attachToken !== null && draft.attachToken !== attachToken) return;
1224
+ if (draft.settings) { draft.operation = { kind: 'idle', error: 'Your message was not sent because the pending settings are not applied yet.' }; this.notify(); return; }
930
1225
  draft.retry = captured;
931
1226
  if (restore && draft.restore === restore) draft.restore = null;
932
1227
  await this.submit(id, draft);
@@ -9,6 +9,36 @@ export type CodeSessionFilter = { scope: 'all' | 'cwd'; archived: boolean };
9
9
  export type CodeOperationKind = 'idle' | 'creating' | 'sending' | 'stopping' | 'resuming' | 'patching' | 'rolling-back' | 'unknown-send';
10
10
  export interface CodeControllerOptions { port: number; workingDir: string }
11
11
 
12
+ export type CodeSettingsField = 'model' | 'effort' | 'permissionMode' | 'thinking';
13
+ export type CodeSettingsValue = string | boolean | null;
14
+ /**
15
+ * A batch of settings edits and where its one PATCH stands. `sent` has left (or may have
16
+ * left) this page; `unknown` means its outcome could not be read; `rejected` was refused
17
+ * before the server recorded it; `conflict` waits for a per-field choice.
18
+ */
19
+ export type CodeSettingsState = 'pending' | 'sent' | 'unknown' | 'conflict' | 'rejected';
20
+ export interface CodeSettingsView {
21
+ state: CodeSettingsState;
22
+ fields: Array<{
23
+ field: CodeSettingsField;
24
+ /** The value this edit was made against. */
25
+ baseline: CodeSettingsValue;
26
+ /** The value the user chose. */
27
+ value: CodeSettingsValue;
28
+ /** Conflict only: the value another client saved since the baseline. */
29
+ theirs?: CodeSettingsValue;
30
+ /** Conflict only: the user's choice so far. */
31
+ resolution?: 'mine' | 'theirs';
32
+ }>;
33
+ /** The server no longer holds this edit's outcome; only an explicit Re-apply or Discard ends it. */
34
+ expired: boolean;
35
+ /** A check, fence or send owns the batch; recovery actions wait. */
36
+ busy: boolean;
37
+ /** The batch belongs to a new session whose creation is not confirmed yet. */
38
+ waitingForSession: boolean;
39
+ error: string | null;
40
+ }
41
+
12
42
  export interface CodeControllerModel {
13
43
  catalog: CodeModelCatalog | null;
14
44
  sessions: CodeSessionInfo[];
@@ -50,6 +80,10 @@ export interface CodeControllerModel {
50
80
  hasOlderHistory: boolean;
51
81
  filter: CodeSessionFilter;
52
82
  creationUnknown: boolean;
83
+ /** The new-session draft has a create in flight or unconfirmed; settings edits queue as pending. */
84
+ creationPending: boolean;
85
+ /** Pending settings of the shown draft; null when none. Sends wait while this is non-null. */
86
+ settings: CodeSettingsView | null;
53
87
  /** A restore (attach, or attach-then-send) is in flight for the selected session; Stop can end it. */
54
88
  restoring?: boolean;
55
89
  startAnotherSession(): void;
@@ -76,4 +110,13 @@ export interface CodeControllerModel {
76
110
  loadOlderHistory(): Promise<void>;
77
111
  setFilter(filter: CodeSessionFilter): void;
78
112
  clearError(): void;
113
+ /** Read the recorded outcome of an unknown settings edit again. Never resends. */
114
+ checkSettings(): Promise<void>;
115
+ /** Fence the unknown/rejected edit, then send it again under a new id. */
116
+ reapplySettings(): Promise<void>;
117
+ /** Fence the unknown/rejected edit, then drop it. A pending or conflict batch is dropped directly. */
118
+ discardSettings(): Promise<void>;
119
+ resolveSettingsConflict(field: CodeSettingsField, choice: 'mine' | 'theirs'): void;
120
+ /** Send a conflict batch once every conflicting field has a choice. */
121
+ applyResolvedSettings(): Promise<void>;
79
122
  }
@@ -1,7 +1,7 @@
1
1
  import type {
2
2
  CodeCancelRequest, CodeCreateSessionRequest, CodeEventsPage, CodeHistoryPage, CodeModelCatalog,
3
3
  CodePatchSessionRequest, CodePermissionAnswer, CodePromptReceipt, CodePromptRequest,
4
- CodeRollbackRequest, CodeSessionInfo, CodeSessionPage, CodeSnapshot, CodeSteerRequest,
4
+ CodeRollbackRequest, CodeSessionInfo, CodeSessionPage, CodeSnapshot, CodeSteerRequest, CodeSessionMutation, CodePatchSessionResult,
5
5
  } from '../../../../src/code-mode/wire';
6
6
 
7
7
  export interface CodeGitInfo {
@@ -28,6 +28,12 @@ export interface CodeGitInfo {
28
28
  };
29
29
  }
30
30
 
31
+ export interface CodeMutationOutcome { mutation: CodeSessionMutation; watermark: string | null }
32
+ /** Older servers omit the watermark on success; absence reads as none known. */
33
+ function outcome(data: { mutation: CodeSessionMutation; watermark?: string | null }): CodeMutationOutcome {
34
+ return { mutation: data.mutation, watermark: typeof data.watermark === 'string' ? data.watermark : null };
35
+ }
36
+
31
37
  export interface CodeListOptions {
32
38
  scope?: 'all' | 'cwd'; cwd?: string; archived?: boolean; pinned?: boolean; cursor?: string; limit?: number;
33
39
  }
@@ -39,6 +45,10 @@ export interface CodeSessionClient {
39
45
  history(id: string, beforeSequence: number, signal?: AbortSignal): Promise<CodeHistoryPage>;
40
46
  createSession(input: CodeCreateSessionRequest): Promise<CodeSessionInfo>;
41
47
  patchSession(id: string, input: CodePatchSessionRequest): Promise<CodeSessionInfo>;
48
+ patchSettings(id: string, input: CodePatchSessionRequest): Promise<CodePatchSessionResult>;
49
+ /** The recorded outcome plus the session watermark (null when nothing was evicted yet). */
50
+ readMutation(id: string, mutationId: string): Promise<CodeMutationOutcome>;
51
+ fenceMutation(id: string, mutationId: string): Promise<CodeMutationOutcome>;
42
52
  sendPrompt(id: string, input: CodePromptRequest): Promise<CodePromptReceipt>;
43
53
  /** A Claude follow-up for the captured running turn; never retried. */
44
54
  steerSession(id: string, input: CodeSteerRequest): Promise<CodePromptReceipt>;
@@ -60,6 +70,11 @@ const ERROR_COPY: Record<string, string> = {
60
70
  request_not_current: 'This approval is no longer current. Refreshing its status.',
61
71
  invalid_option: 'This approval option is no longer available. Refreshing its status.',
62
72
  revision_conflict: 'Session settings changed elsewhere. Review the updated values and try again.',
73
+ mutation_fenced: 'This settings change was fenced before it applied.',
74
+ mutation_outcome_expired: 'The settings outcome has expired. Choose Re-apply or Discard.',
75
+ mutation_not_found: 'The settings outcome is not recorded yet.',
76
+ mutation_id_conflict: 'This settings mutation identity belongs to another request.',
77
+ invalid_mutation_id: 'The settings mutation identity is invalid.',
63
78
  invalid_sequence: 'Conversation history needs to be refreshed.',
64
79
  snapshot_limit: 'This conversation exceeds the snapshot limit. Stop and recovery controls remain available.',
65
80
  transcript_limit: 'The conversation has reached its storage limit.',
@@ -85,7 +100,8 @@ const ERROR_COPY: Record<string, string> = {
85
100
  };
86
101
 
87
102
  export class CodeClientError extends Error {
88
- constructor(readonly code: string, readonly status: number, readonly session?: CodeSessionInfo) {
103
+ constructor(readonly code: string, readonly status: number, readonly session?: CodeSessionInfo,
104
+ readonly mutation?: CodeSessionMutation, readonly watermark?: string | null) {
89
105
  super(ERROR_COPY[code] ?? 'The request could not be completed. Refresh the session and try again.');
90
106
  this.name = 'CodeClientError';
91
107
  }
@@ -105,7 +121,7 @@ export function createCodeSessionClient(port: number): CodeSessionClient {
105
121
  });
106
122
  const data = await response.json();
107
123
  if (!response.ok || data.ok !== true) {
108
- throw new CodeClientError(typeof data.error === 'string' ? data.error : 'code_request_failed', response.status, data.session);
124
+ throw new CodeClientError(typeof data.error === 'string' ? data.error : 'code_request_failed', response.status, data.session, data.mutation, data.watermark);
109
125
  }
110
126
  return data as T;
111
127
  }
@@ -124,6 +140,9 @@ export function createCodeSessionClient(port: number): CodeSessionClient {
124
140
  history: (id, beforeSequence, signal) => request('GET', `${sessionPath(id)}/items?beforeSequence=${beforeSequence}&limit=200`, undefined, signal),
125
141
  createSession: input => sessionRequest('POST', '/sessions', input),
126
142
  patchSession: (id, input) => sessionRequest('PATCH', sessionPath(id), input),
143
+ patchSettings: (id, input) => request('PATCH', sessionPath(id), input),
144
+ readMutation: async (id, mutationId) => outcome(await request('GET', `${sessionPath(id)}/mutations/${encodeURIComponent(mutationId)}`)),
145
+ fenceMutation: async (id, mutationId) => outcome(await request('POST', `${sessionPath(id)}/mutations/${encodeURIComponent(mutationId)}/fence`, {})),
127
146
  sendPrompt: (id, input) => request('POST', `${sessionPath(id)}/prompt`, input),
128
147
  steerSession: (id, input) => request('POST', `${sessionPath(id)}/steer`, input),
129
148
  cancelPrompt: (id, input) => sessionRequest('POST', `${sessionPath(id)}/cancel`, input),
@@ -86,6 +86,7 @@ function apply(state: CodeSessionState, event: CodeWireEvent): CodeSessionState
86
86
  ...(update.appendToolOutput === undefined ? {} : { tool: { ...previous.tool!, output: (previous.tool!.output ?? '') + update.appendToolOutput } }),
87
87
  ...(update.status === undefined ? {} : { status: update.status }),
88
88
  ...(update.phase === undefined ? {} : { phase: update.phase }),
89
+ ...(update.truncation === undefined ? {} : { truncation: update.truncation }),
89
90
  };
90
91
  } else return { ...state, needsSnapshot: true, synced: false };
91
92
  items = order([...items.filter(row => row.itemId !== item.itemId), item]);
@@ -0,0 +1,19 @@
1
+ const alphabet = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
2
+ const pattern = /^[0-7][0-9A-HJKMNP-TV-Z]{25}$/;
3
+
4
+ export const compareMutationId = (a: string, b: string): number => a < b ? -1 : a > b ? 1 : 0;
5
+
6
+ export function ulid(now = Date.now(), floor: string | null = null): string {
7
+ if (!Number.isSafeInteger(now) || now < 0 || (floor !== null && !pattern.test(floor))) throw new Error('Invalid mutation clock or watermark');
8
+ let time = now;
9
+ if (floor) {
10
+ let floorTime = 0;
11
+ for (const char of floor.slice(0, 10)) floorTime = floorTime * 32 + alphabet.indexOf(char);
12
+ if (floorTime >= time) time = floorTime + 1;
13
+ }
14
+ if (time > 0xffffffffffff) throw new Error('Mutation clock exhausted');
15
+ let prefix = '';
16
+ for (let i = 0; i < 10; i++) { prefix = alphabet[time % 32] + prefix; time = Math.floor(time / 32); }
17
+ const bytes = crypto.getRandomValues(new Uint8Array(16));
18
+ return prefix + Array.from(bytes, byte => alphabet[byte & 31]).join('');
19
+ }