@thegitai/cli 1.0.0-preview.6 → 1.0.0-preview.60

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 (90) hide show
  1. package/README.md +229 -7
  2. package/dist/bin/ai.js +140 -111
  3. package/dist/bin/browser-host.js +265 -0
  4. package/dist/src/agent-mode.js +32 -7
  5. package/dist/src/api/auth.js +8 -2
  6. package/dist/src/api/browser-login.js +147 -35
  7. package/dist/src/api/chat.js +691 -166
  8. package/dist/src/api/contracts.js +55 -1
  9. package/dist/src/api/default-host.js +1 -0
  10. package/dist/src/api/http.js +139 -8
  11. package/dist/src/api/models.js +34 -9
  12. package/dist/src/api/startup-handshake.js +36 -0
  13. package/dist/src/api/turn-recovery.js +189 -0
  14. package/dist/src/background-jobs.js +8 -2
  15. package/dist/src/browser/bridge.js +262 -0
  16. package/dist/src/browser/framing.js +42 -0
  17. package/dist/src/browser/native-host.js +219 -0
  18. package/dist/src/browser/protocol.js +46 -0
  19. package/dist/src/browser/session-bridge.js +130 -0
  20. package/dist/src/cli-args.js +19 -5
  21. package/dist/src/client-environment.js +2 -0
  22. package/dist/src/core/clipboard.js +7 -13
  23. package/dist/src/core/image-limits.js +56 -0
  24. package/dist/src/core/image-path-extractor.js +70 -3
  25. package/dist/src/core/session-image-store.js +246 -0
  26. package/dist/src/edit-journal.js +33 -2
  27. package/dist/src/executor.js +25 -3
  28. package/dist/src/help-text.js +128 -22
  29. package/dist/src/job-follow-up.js +40 -0
  30. package/dist/src/mcp-client.js +335 -0
  31. package/dist/src/mcp-command.js +176 -0
  32. package/dist/src/mcp-config.js +123 -0
  33. package/dist/src/mcp-sdk.js +3 -0
  34. package/dist/src/mcp-types.js +26 -0
  35. package/dist/src/patcher.js +43 -4
  36. package/dist/src/permissions.js +301 -0
  37. package/dist/src/preferences.js +39 -0
  38. package/dist/src/project-key.js +11 -0
  39. package/dist/src/project-model-preferences.js +74 -0
  40. package/dist/src/quota-notice.js +35 -0
  41. package/dist/src/reasoning-effort.js +27 -0
  42. package/dist/src/session-safety.js +0 -12
  43. package/dist/src/session-store.js +123 -30
  44. package/dist/src/session.js +20 -4
  45. package/dist/src/signin.js +58 -0
  46. package/dist/src/tool-executor.js +23 -49
  47. package/dist/src/tools/browser.js +641 -0
  48. package/dist/src/tools/delete-file.js +20 -4
  49. package/dist/src/tools/index.js +32 -10
  50. package/dist/src/tools/patch-file.js +12 -26
  51. package/dist/src/tools/read-file.js +5 -0
  52. package/dist/src/tools/read-image-file.js +85 -0
  53. package/dist/src/tools/replace-document-text.js +28 -18
  54. package/dist/src/tools/restore-checkpoint.js +0 -1
  55. package/dist/src/tools/run-command.js +14 -71
  56. package/dist/src/tools/run-node-script.js +12 -81
  57. package/dist/src/tools/save-generated-image.js +120 -0
  58. package/dist/src/tools/str-replace.js +12 -26
  59. package/dist/src/tools/undo-edit.js +1 -6
  60. package/dist/src/tools/write-file.js +67 -11
  61. package/dist/src/ui/prompt-history-store.js +1 -1
  62. package/dist/src/ui/repl.js +1017 -299
  63. package/dist/src/ui/slash-commands.js +122 -0
  64. package/dist/src/ui/tui/attention.js +25 -0
  65. package/dist/src/ui/tui/bridge.js +38 -5
  66. package/dist/src/ui/tui/build-frame.js +807 -270
  67. package/dist/src/ui/tui/composer-layout.js +76 -0
  68. package/dist/src/ui/tui/desktop-notification.js +118 -0
  69. package/dist/src/ui/tui/markdown-render.js +21 -11
  70. package/dist/src/ui/tui/model-label.js +13 -0
  71. package/dist/src/ui/tui/shell-input.js +275 -73
  72. package/dist/src/ui/tui/shortcuts.js +61 -0
  73. package/dist/src/ui/tui/terminal-theme.js +28 -0
  74. package/dist/src/ui/tui/text.js +31 -6
  75. package/dist/src/ui/tui/user-input.js +593 -0
  76. package/dist/src/update-check.js +205 -0
  77. package/dist/src/usage-notice.js +52 -0
  78. package/dist/src/usage.js +5 -2
  79. package/dist/src/utils.js +13 -0
  80. package/dist/src/version.js +52 -2
  81. package/dist/vendor/mcp/LICENSES.txt +414 -0
  82. package/dist/vendor/mcp/client.cjs +82 -0
  83. package/package.json +22 -9
  84. package/dist/src/project-index.js +0 -233
  85. package/dist/src/tools/code-intel.js +0 -472
  86. package/dist/src/tools/find-symbol.js +0 -70
  87. package/dist/src/tools/hover-symbol.js +0 -95
  88. package/dist/src/tools/list-symbols.js +0 -55
  89. package/dist/src/tools/search-code.js +0 -37
  90. package/dist/src/tools/signature-help.js +0 -118
@@ -1,22 +1,38 @@
1
+ import { sessionMcp } from '../mcp-client.js';
2
+ import { projectModelEffort, readProjectModelEfforts, saveProjectModelEffort } from '../project-model-preferences.js';
3
+ import { REASONING_EFFORT_LABELS } from '../reasoning-effort.js';
4
+ import { basename } from 'node:path';
1
5
  import { createRatatuiBridge } from './tui/bridge.js';
2
- import { buildTuiFrame, formatJobElapsed, formatTodoProgress, renderTranscriptEntryLines, } from './tui/build-frame.js';
6
+ import { bucketActionLabel, } from '../permissions.js';
7
+ import { AGENT_MODE_LOCKED_STATUS, approvalScrollLimit, buildTuiFrame, formatJobElapsed, formatTodoProgress, pickThinkingFallbackPhrase, renderTranscriptEntryLines, THINKING_FALLBACK_PHRASES, userInputViewportForFrame, } from './tui/build-frame.js';
8
+ import { createAttentionController, INITIAL_TERMINAL_FOCUS, } from './tui/attention.js';
9
+ import { backendFor, createNotificationQueue, } from './tui/desktop-notification.js';
10
+ import { readPreferences, writePreferences } from '../preferences.js';
3
11
  import { createTerminalTitleController } from './tui/terminal-title.js';
4
12
  import { captureTerminalWrites, releaseTerminalWrites, } from './tui/terminal-writes.js';
5
- export { getSlashCommandSuggestions } from './tui/build-frame.js';
13
+ import { getInputCommandToken, getSlashCommandSuggestions, SLASH_COMMANDS, slashCommandMatchesToken, } from './slash-commands.js';
14
+ export { getInputCommandToken, getSlashCommandSuggestions, SLASH_COMMANDS, slashCommandMatchesToken, };
15
+ import { composerInputWidth, frameContentWidth } from './tui/composer-layout.js';
6
16
  import { agentModeLabel, nextAgentMode, } from '../agent-mode.js';
7
17
  import { chat, models } from '../api/index.js';
8
- import { isTurnCancelledError } from '../api/chat.js';
18
+ import { isTurnCancelledError, isTurnOutcomeKnown } from '../api/chat.js';
19
+ import { formatTurnRecoveryStatus } from '../api/turn-recovery.js';
20
+ import { createJobWaitTracker } from '../job-follow-up.js';
9
21
  import { getJobBufferedOutput, getJobOutputPreview, hasRunningBackgroundJobs, killAllBackgroundJobs, killBackgroundJob, listBackgroundJobs, setBackgroundJobSession, setBackgroundJobUpdateHook, } from '../background-jobs.js';
10
22
  import { clearTodos, listTodos, setTodoSession } from '../todo-list.js';
11
23
  import { setScratchSession } from '../scratch-dir.js';
24
+ import { setImageStoreSession } from '../core/session-image-store.js';
12
25
  import { cancelActiveCommand } from '../executor.js';
13
26
  import { isTurnFailureMarker } from '../turn-failure-marker.js';
14
- import { clearCliAuthConfig } from '../api/auth.js';
27
+ import { clearCliAuthConfig, logoutFromServer, } from '../api/auth.js';
15
28
  import { authenticationErrorMessage, isAuthenticationError, } from '../api/http.js';
29
+ import { buildQuotaNotice } from '../quota-notice.js';
30
+ import { createUsageNoticeTracker } from '../usage-notice.js';
31
+ import { createUserInputPromptState, formatUserInputTranscript, } from './tui/user-input.js';
16
32
  import { setCommandOutputHook, withTuiMode } from '../runtime-mode.js';
17
33
  import { collectBackgroundJobUiKillMutations, collectBackgroundJobUiOutputMutations, } from '../tool-executor.js';
18
- import { clearConversation, } from '../session.js';
19
- import { applySessionSnapshot, listSessionMetadata, loadSessionSnapshot, saveSessionState, } from '../session-store.js';
34
+ import { startNewConversation, } from '../session.js';
35
+ import { applySessionSnapshot, listSessionMetadata, loadSessionSnapshot, saveSessionState, sessionHasUserMessage, } from '../session-store.js';
20
36
  import { truncate } from '../utils.js';
21
37
  import { writeClipboardText } from '../core/clipboard.js';
22
38
  import { openUrl } from '../core/open-url.js';
@@ -72,58 +88,46 @@ const TRANSCRIPT_DIFF_PREVIEW_LINES = 24;
72
88
  const WORKING_TOOL_PREVIEW_ITEMS = 4;
73
89
  const THINKING_NOTE_PREVIEW_ROWS = 3;
74
90
  const WORKING_TOOL_PREVIEW_ROWS = 3;
75
- const AGENT_MODE_LABEL_WIDTH = 16;
76
- const APPROVAL_OPTIONS = [
77
- {
78
- value: 'y',
79
- label: 'Approve once',
80
- description: 'Run this action only this time',
81
- },
82
- {
83
- value: 'a',
84
- label: 'Approve all remaining actions',
85
- description: 'Turn on auto-approve for the rest of the session',
86
- },
87
- {
88
- value: 'n',
89
- label: 'Deny',
90
- description: 'Reject this action',
91
- },
92
- ];
93
- export const SLASH_COMMANDS = [
94
- {
95
- command: '/help',
96
- description: 'Show available chat commands',
97
- },
98
- {
99
- command: '/about',
100
- description: 'Show version and platform info',
101
- },
102
- {
103
- command: '/usage',
104
- description: 'Show account usage percentage and reset times',
105
- },
106
- {
107
- command: '/model',
108
- description: 'Switch the active model',
109
- },
110
- {
111
- command: '/resume',
112
- description: 'Open the session picker',
113
- },
114
- {
115
- command: '/jobs',
116
- description: 'Background jobs: pick to view output or kill',
117
- },
118
- {
119
- command: '/clear',
120
- description: 'Clear conversation history',
121
- },
122
- {
123
- command: '/exit',
124
- description: 'Quit the current session',
125
- },
126
- ];
91
+ export const REPORT_ISSUE_URL = 'https://thegit.ai/report';
92
+ export function buildReportTranscriptEntries(openedUrl) {
93
+ return openedUrl
94
+ ? [
95
+ {
96
+ body: `Opening the private bug report form in your browser. If nothing opened, visit:\n\n${REPORT_ISSUE_URL}\n`,
97
+ kind: 'system',
98
+ title: 'Report',
99
+ },
100
+ ]
101
+ : [
102
+ {
103
+ body: `Could not open a browser. Report the bug manually at:\n\n${REPORT_ISSUE_URL}\n`,
104
+ kind: 'error',
105
+ title: 'Report',
106
+ },
107
+ ];
108
+ }
109
+ export function buildTurnFailureHintEntries(cancelled) {
110
+ if (cancelled)
111
+ return [];
112
+ return [
113
+ {
114
+ body: 'Something went wrong? Use /report to submit the issue.',
115
+ kind: 'error',
116
+ title: 'Report',
117
+ },
118
+ ];
119
+ }
120
+ export function composerAttachmentsAfterCancel(queuedAttachments, inFlightAttachments) {
121
+ const seen = new Set();
122
+ const kept = [];
123
+ for (const attachment of [...queuedAttachments, ...inFlightAttachments]) {
124
+ if (seen.has(attachment.index))
125
+ continue;
126
+ seen.add(attachment.index);
127
+ kept.push(attachment);
128
+ }
129
+ return kept;
130
+ }
127
131
  function getShellWidth(columns) {
128
132
  const safeColumns = Math.max(columns, 20);
129
133
  const targetWidth = Math.floor(safeColumns * TUI_WIDTH_RATIO);
@@ -492,11 +496,43 @@ function buildWriteFileDiff(content) {
492
496
  return '';
493
497
  return `@@ -0,0 +1,${lines.length} @@\n${lines.map((line) => `+${line}`).join('\n')}`;
494
498
  }
499
+ const MAX_DELETE_PREVIEW_LINES = 400;
495
500
  function buildDeleteFileDiff(content) {
496
501
  const lines = splitDiffLines(String(content ?? ''));
497
- if (lines.length === 0)
502
+ if (lines.length === 0) {
503
+ return { removed: 0, text: '' };
504
+ }
505
+ const shown = lines.slice(0, MAX_DELETE_PREVIEW_LINES);
506
+ const rows = [
507
+ `@@ -1,${lines.length} +0,0 @@`,
508
+ ...shown.map((line) => `-${line}`),
509
+ ];
510
+ const omitted = lines.length - shown.length;
511
+ if (omitted > 0) {
512
+ rows.push(`@@ ${omitted} more removed line(s) not shown @@`);
513
+ }
514
+ return { removed: lines.length, text: rows.join('\n') };
515
+ }
516
+ function deletedFileSummary(result) {
517
+ const bytes = typeof result?.bytes === 'number' ? result.bytes : null;
518
+ if (bytes === null) {
498
519
  return '';
499
- return `@@ -1,${lines.length} +0,0 @@\n${lines.map((line) => `-${line}`).join('\n')}`;
520
+ }
521
+ const reason = result?.contentOmitted === 'binary' ? ', binary' : '';
522
+ return ` (${formatFileSize(bytes)}${reason})`;
523
+ }
524
+ function formatFileSize(bytes) {
525
+ if (bytes < 1024) {
526
+ return `${bytes} B`;
527
+ }
528
+ const units = ['KiB', 'MiB', 'GiB', 'TiB'];
529
+ let value = bytes / 1024;
530
+ let unit = 0;
531
+ while (value >= 1024 && unit < units.length - 1) {
532
+ value /= 1024;
533
+ unit += 1;
534
+ }
535
+ return `${value >= 10 ? Math.round(value) : value.toFixed(1)} ${units[unit]}`;
500
536
  }
501
537
  function isFileChangeTool(name) {
502
538
  return (name === 'patch_file' ||
@@ -512,13 +548,7 @@ function getToolFilePath(call, result) {
512
548
  '').trim();
513
549
  }
514
550
  function formatToolResultState(result) {
515
- if (result?.skipped)
516
- return 'Skipped';
517
- if (result?.blocked)
518
- return 'Blocked';
519
- if (result?.ok === true)
520
- return 'OK';
521
- return 'Failed';
551
+ return result?.skipped ? 'Skipped' : 'OK';
522
552
  }
523
553
  function formatRunCommandResultState(result) {
524
554
  if (result?.timedOut)
@@ -556,12 +586,15 @@ function buildFileChangeEntry(event) {
556
586
  : call.name === 'undo_edit'
557
587
  ? 'Undo'
558
588
  : 'Edit';
559
- return {
560
- body: error || `${call.name} ${filePath}`,
561
- filePath,
562
- kind: skipped ? 'system' : 'error',
563
- title: skipped ? `${verb} skipped: ${filePath}` : `${verb} failed: ${filePath}`,
564
- };
589
+ if (skipped) {
590
+ return {
591
+ body: error || `${call.name} ${filePath}`,
592
+ filePath,
593
+ kind: 'system',
594
+ title: `${verb} skipped: ${filePath}`,
595
+ };
596
+ }
597
+ return { body: '', filePath, kind: 'system', title: `${verb}: ${filePath}` };
565
598
  }
566
599
  if (result?.scratch === true) {
567
600
  const scratchName = truncate(filePath.split(/[\\/]/).filter(Boolean).at(-1) ?? filePath, 72);
@@ -622,9 +655,11 @@ function buildFileChangeEntry(event) {
622
655
  };
623
656
  }
624
657
  const content = typeof result?.content === 'string' ? result.content : '';
625
- const diffText = buildDeleteFileDiff(content);
626
- const preview = diffText ? parseDiffPreview(diffText) : undefined;
627
- const summary = preview ? ` (+0 -${preview.removed})` : '';
658
+ const diff = buildDeleteFileDiff(content);
659
+ const preview = diff.text ? parseDiffPreview(diff.text) : undefined;
660
+ const summary = preview
661
+ ? ` (+0 -${diff.removed})`
662
+ : deletedFileSummary(result);
628
663
  return {
629
664
  body: '',
630
665
  diffPreview: preview,
@@ -674,24 +709,27 @@ function buildFileChangeEntry(event) {
674
709
  title: `Edited ${filePath}${summary}`,
675
710
  };
676
711
  }
677
- function buildWorkingToolEntry(event) {
712
+ export function buildWorkingToolEntry(event, label = event.call.name) {
678
713
  const { call, result } = event;
679
- const error = typeof result?.error === 'string' && result.error.trim()
714
+ const failed = result?.ok !== true && result?.skipped !== true;
715
+ const kind = result?.ok === true ? 'tool' : 'system';
716
+ const state = (text) => (failed ? '' : text);
717
+ const error = !failed && typeof result?.error === 'string' && result.error.trim()
680
718
  ? `\n${truncate(result.error.trim(), 180)}`
681
719
  : '';
682
720
  if (call.name === 'run_command') {
683
721
  const command = String(call.args?.command ?? result?.command ?? '').trim();
684
722
  if (result?.backgrounded === true && result?.jobId) {
685
723
  return {
686
- body: `$ ${truncate(command, 180)}\nBackground job ${String(result.jobId)} started.${error}`,
687
- kind: result?.ok === true ? 'tool' : 'error',
724
+ body: `$ ${truncate(command, 180)}${state(`\nBackground job ${String(result.jobId)} started.`)}${error}`,
725
+ kind,
688
726
  preformatted: true,
689
727
  title: 'Shell',
690
728
  };
691
729
  }
692
730
  return {
693
- body: `$ ${truncate(command, 180)}\n${formatRunCommandResultState(result)}${error}`,
694
- kind: result?.ok === true ? 'tool' : 'error',
731
+ body: `$ ${truncate(command, 180)}${state(`\n${formatRunCommandResultState(result)}`)}${error}`,
732
+ kind,
695
733
  title: 'Shell',
696
734
  };
697
735
  }
@@ -703,15 +741,15 @@ function buildWorkingToolEntry(event) {
703
741
  ? `${status}${exitCode != null ? ` (code ${exitCode})` : ''}`
704
742
  : formatToolResultState(result);
705
743
  return {
706
- body: `${jobId || '(unknown job)'} · ${stateText}${error}`,
707
- kind: result?.ok === true ? 'tool' : 'error',
744
+ body: `${jobId || '(unknown job)'}${state(` · ${stateText}`)}${error}`,
745
+ kind,
708
746
  title: call.name === 'shell_job_kill' ? 'Kill job' : 'Job output',
709
747
  };
710
748
  }
711
749
  if (call.name === 'run_node_script') {
712
750
  return {
713
- body: `node --input-type=module <script via stdin>\n${formatRunCommandResultState(result)}${error}`,
714
- kind: result?.ok === true ? 'tool' : 'error',
751
+ body: `node --input-type=module <script via stdin>${state(`\n${formatRunCommandResultState(result)}`)}${error}`,
752
+ kind,
715
753
  title: 'Node',
716
754
  };
717
755
  }
@@ -720,8 +758,8 @@ function buildWorkingToolEntry(event) {
720
758
  }
721
759
  const args = formatToolArgs(call, result);
722
760
  return {
723
- body: `${call.name}${args ? ` ${args}` : ''} -> ${formatToolResultState(result)}${error}`,
724
- kind: result?.ok === true ? 'tool' : 'error',
761
+ body: `${label}${args ? ` ${args}` : ''}${state(` -> ${formatToolResultState(result)}`)}${error}`,
762
+ kind,
725
763
  title: 'Tool',
726
764
  };
727
765
  }
@@ -787,10 +825,18 @@ function displayUserTextFromHistoryEntry(entry) {
787
825
  export function buildTranscriptFromSessionHistory(history) {
788
826
  const entries = [];
789
827
  const pendingCalls = new Map();
828
+ const pendingUserInputRequests = new Map();
790
829
  for (const entry of history) {
791
830
  if (!entry?.parts?.length)
792
831
  continue;
793
832
  for (const part of entry.parts) {
833
+ const userInputRequest = part?.userInputRequest;
834
+ if (userInputRequest && typeof userInputRequest === 'object') {
835
+ const requestId = String(userInputRequest.requestId ?? '').trim();
836
+ if (requestId && Array.isArray(userInputRequest.questions)) {
837
+ pendingUserInputRequests.set(requestId, userInputRequest.questions);
838
+ }
839
+ }
794
840
  const call = part?.functionCall;
795
841
  if (!call || typeof call !== 'object')
796
842
  continue;
@@ -800,6 +846,21 @@ export function buildTranscriptFromSessionHistory(history) {
800
846
  pendingCalls.set(callId, call);
801
847
  }
802
848
  for (const part of entry.parts) {
849
+ const userInputResult = part?.userInputResult;
850
+ if (userInputResult && typeof userInputResult === 'object') {
851
+ const requestId = String(userInputResult.requestId ?? '').trim();
852
+ const questions = pendingUserInputRequests.get(requestId);
853
+ const result = userInputResult.result;
854
+ if (questions &&
855
+ (result?.status === 'submitted' || result?.status === 'cancelled')) {
856
+ pendingUserInputRequests.delete(requestId);
857
+ entries.push({
858
+ body: formatUserInputTranscript(questions, result),
859
+ kind: result.status === 'submitted' ? 'user' : 'system',
860
+ title: result.status === 'submitted' ? 'Your answers' : 'Question',
861
+ });
862
+ }
863
+ }
803
864
  const functionResponse = part?.functionResponse;
804
865
  if (!functionResponse || typeof functionResponse !== 'object')
805
866
  continue;
@@ -816,10 +877,10 @@ export function buildTranscriptFromSessionHistory(history) {
816
877
  }
817
878
  if (!call || !isFileChangeTool(call.name))
818
879
  continue;
819
- entries.push(buildFileChangeEntry({
820
- call,
821
- result: functionResponse.response ?? {},
822
- }));
880
+ const result = (functionResponse.response ?? {});
881
+ if (result.ok !== true && result.skipped !== true)
882
+ continue;
883
+ entries.push(buildFileChangeEntry({ call, result }));
823
884
  }
824
885
  if (entry.role === 'user' && entry.kind === 'turnStart') {
825
886
  const text = displayUserTextFromHistoryEntry(entry);
@@ -828,6 +889,13 @@ export function buildTranscriptFromSessionHistory(history) {
828
889
  }
829
890
  continue;
830
891
  }
892
+ if (entry.role === 'user' && entry.kind === 'userInterjection') {
893
+ const text = String(entry.userInput ?? '').trim();
894
+ if (text) {
895
+ entries.push({ body: text, kind: 'user', title: 'You · sent mid-turn' });
896
+ }
897
+ continue;
898
+ }
831
899
  const text = textFromHistoryEntry(entry);
832
900
  if ((entry.role === 'model' || entry.role === 'assistant') && text) {
833
901
  if (isTurnFailureMarker(text)) {
@@ -856,7 +924,24 @@ function createSessionTranscript(session) {
856
924
  const transcript = buildTranscriptFromSessionHistory(session.history);
857
925
  return transcript.length ? transcript : createInitialTranscript();
858
926
  }
859
- function createShellStore(initialState) {
927
+ export function isJobsPickerCommand(input) {
928
+ return String(input ?? '').trim() === '/jobs';
929
+ }
930
+ export function statusBehindJobsPicker(state) {
931
+ return state.jobsPickerOpen
932
+ ? (state.jobsPickerReturnStatus ?? 'Ready')
933
+ : state.status;
934
+ }
935
+ export function closedJobsPickerFields(state) {
936
+ if (!state.jobsPickerOpen)
937
+ return {};
938
+ return {
939
+ jobsPickerExpandedId: null,
940
+ jobsPickerOpen: false,
941
+ jobsPickerReturnStatus: null,
942
+ };
943
+ }
944
+ export function createShellStore(initialState) {
860
945
  let state = initialState;
861
946
  let nextEntryId = 1;
862
947
  const listeners = new Set();
@@ -864,6 +949,10 @@ function createShellStore(initialState) {
864
949
  for (const listener of listeners)
865
950
  listener();
866
951
  };
952
+ const setState = (nextState) => {
953
+ state = nextState.busy ? nextState : { ...nextState, usageNotice: null };
954
+ notify();
955
+ };
867
956
  return {
868
957
  getState: () => state,
869
958
  subscribe: (listener) => {
@@ -872,14 +961,8 @@ function createShellStore(initialState) {
872
961
  listeners.delete(listener);
873
962
  };
874
963
  },
875
- setState: (nextState) => {
876
- state = nextState;
877
- notify();
878
- },
879
- update: (updater) => {
880
- state = updater(state);
881
- notify();
882
- },
964
+ setState,
965
+ update: (updater) => setState(updater(state)),
883
966
  appendEntry: (entry) => {
884
967
  const id = nextEntryId++;
885
968
  state = {
@@ -958,31 +1041,40 @@ function shallowArrayEqual(a, b) {
958
1041
  }
959
1042
  return true;
960
1043
  }
961
- function createInitialShellState(session, serverModels, debugUi) {
1044
+ function createInitialShellState(session, serverModels, debugUi, serverUrl) {
962
1045
  return {
963
1046
  activeTurnInput: '',
964
1047
  activeTurnInputPreformatted: false,
965
1048
  agentMode: session.agentMode,
966
- approvalCursor: getDefaultApprovalCursor(),
1049
+ analyzingImages: 0,
1050
+ generatingImage: false,
1051
+ approvalCursor: 0,
967
1052
  approvalPrompt: null,
1053
+ approvalScrollOffset: 0,
968
1054
  autoYes: session.autoYes,
969
1055
  backgroundJobs: [],
970
1056
  busy: false,
1057
+ busyPausedAt: null,
971
1058
  busySince: null,
972
1059
  clockNow: Date.now(),
973
1060
  commandCursor: 0,
974
1061
  commandLog: [],
975
1062
  contextStatus: 'Idle',
976
1063
  currentModelId: session.modelId,
1064
+ reasoningEffort: projectModelEffort(readProjectModelEfforts(session.rootDir, serverUrl, session.env), session.modelId),
977
1065
  cursor: 0,
978
1066
  exiting: false,
979
1067
  input: '',
980
1068
  maxToolSteps: session.maxToolSteps,
1069
+ notificationsEnabled: readPreferences(session.env).notifications,
1070
+ terminalFocused: INITIAL_TERMINAL_FOCUS,
981
1071
  jobsPickerExpandedId: null,
982
1072
  jobsPickerIndex: 0,
983
1073
  jobsPickerOpen: false,
984
1074
  modelPickerIndex: getDefaultModelPickerIndex(session.modelId, serverModels.models),
985
1075
  modelPickerOpen: false,
1076
+ shortcutsOpen: false,
1077
+ transientStatus: null,
986
1078
  projectRoot: session.rootDir,
987
1079
  sessionId: session.sessionId,
988
1080
  showSessionId: debugUi.showSessionId,
@@ -995,6 +1087,7 @@ function createInitialShellState(session, serverModels, debugUi) {
995
1087
  resumePickerSessions: [],
996
1088
  transcriptScrollOffset: 0,
997
1089
  queuedMessage: null,
1090
+ turnMessages: [],
998
1091
  serverModels: serverModels.models,
999
1092
  sudoPrompt: null,
1000
1093
  status: 'Ready',
@@ -1005,6 +1098,7 @@ function createInitialShellState(session, serverModels, debugUi) {
1005
1098
  tokenUsage: formatClientTokenUsage(null),
1006
1099
  transcript: [],
1007
1100
  turnCounter: Math.max(0, session.history.filter((entry) => entry.role === 'user').length),
1101
+ userInputPrompt: null,
1008
1102
  pastedChunks: [],
1009
1103
  imageAttachments: [],
1010
1104
  workingTools: [],
@@ -1021,7 +1115,6 @@ export function formatClientTokenUsage(_responseTimeMs, usageSummary = null) {
1021
1115
  const reasoningTokens = usageSummary?.reasoningTokens ?? 0;
1022
1116
  const cacheTokens = usageSummary?.cacheTokens ?? 0;
1023
1117
  const cacheWriteTokens = usageSummary?.cacheWriteTokens ?? 0;
1024
- const indexTokens = usageSummary?.indexTokens ?? 0;
1025
1118
  return [
1026
1119
  'Session tokens',
1027
1120
  `in ${formatTokenCount(inputTokens)}`,
@@ -1029,7 +1122,6 @@ export function formatClientTokenUsage(_responseTimeMs, usageSummary = null) {
1029
1122
  ...(reasoningTokens > 0 ? [`think ${formatTokenCount(reasoningTokens)}`] : []),
1030
1123
  `cache ${formatTokenCount(cacheTokens)}`,
1031
1124
  `write ${formatTokenCount(cacheWriteTokens)}`,
1032
- `index ${formatTokenCount(indexTokens)}`,
1033
1125
  ].join(' • ');
1034
1126
  }
1035
1127
  export function formatPromptDirectoryLabel(projectRoot, homeDir = process.env.HOME ?? '') {
@@ -1072,6 +1164,24 @@ function splitThinkingLines(text) {
1072
1164
  .map((part) => part.trim())
1073
1165
  .filter(Boolean));
1074
1166
  }
1167
+ const LIVE_STATUS_PANEL_MAX_CHARS = 72;
1168
+ const TOOL_PROGRESS_STATUS_PATTERN = /^(?:Tool:\s|Running\s\S+(?:\slocally)?\.\.\.$)/i;
1169
+ export function isToolProgressStatus(status) {
1170
+ return TOOL_PROGRESS_STATUS_PATTERN.test(String(status ?? '').trim());
1171
+ }
1172
+ function holdOrPickFallback(currentTitle) {
1173
+ return THINKING_FALLBACK_PHRASES.includes(currentTitle.trim())
1174
+ ? currentTitle
1175
+ : pickThinkingFallbackPhrase();
1176
+ }
1177
+ function liveStatusPanelTitle(status) {
1178
+ const text = String(status ?? '').trim();
1179
+ if (!text || text.includes('\n'))
1180
+ return '';
1181
+ if (isToolProgressStatus(text))
1182
+ return '';
1183
+ return text.length <= LIVE_STATUS_PANEL_MAX_CHARS ? text : '';
1184
+ }
1075
1185
  function thinkingPanelFromStatus(status) {
1076
1186
  const rawText = thinkingNoteFromStatus(status);
1077
1187
  if (!rawText)
@@ -1095,7 +1205,7 @@ function thinkingPanelFromStatus(status) {
1095
1205
  const bodyLines = rawLines.length > 1 && rawLines[0].length <= 72 ? rawLines.slice(1) : rawLines;
1096
1206
  return {
1097
1207
  title,
1098
- notes: splitThinkingLines(bodyLines.join('\n')).slice(-3),
1208
+ notes: splitThinkingLines(bodyLines.join('\n')).slice(0, 3),
1099
1209
  };
1100
1210
  }
1101
1211
  export const EXIT_CTRL_C_CONFIRM_MESSAGE = 'Press Ctrl+C again to quit.';
@@ -1103,16 +1213,6 @@ export const EXIT_CTRL_C_CONFIRM_MS = 3000;
1103
1213
  export function isExitConfirmActive(exitConfirmUntil, now = Date.now()) {
1104
1214
  return exitConfirmUntil != null && now < exitConfirmUntil;
1105
1215
  }
1106
- export function getInputCommandToken(input) {
1107
- const trimmed = String(input ?? '').trim();
1108
- if (!trimmed.startsWith('/'))
1109
- return '';
1110
- const firstSpaceIndex = trimmed.indexOf(' ');
1111
- const token = firstSpaceIndex === -1 ? trimmed : trimmed.slice(0, firstSpaceIndex);
1112
- if (token.indexOf('/', 1) !== -1)
1113
- return '';
1114
- return token;
1115
- }
1116
1216
  function shouldShowCommandPalette(state) {
1117
1217
  const trimmed = String(state.input ?? '').trim();
1118
1218
  return (!state.busy &&
@@ -1120,8 +1220,9 @@ function shouldShowCommandPalette(state) {
1120
1220
  !state.modelPickerOpen &&
1121
1221
  !state.resumePickerOpen &&
1122
1222
  trimmed.startsWith('/') &&
1123
- !trimmed.includes(' ') &&
1124
- getInputCommandToken(trimmed) !== '');
1223
+ !String(state.input ?? '').includes(' ') &&
1224
+ getInputCommandToken(trimmed) !== '' &&
1225
+ getSlashCommandSuggestions(trimmed).length > 0);
1125
1226
  }
1126
1227
  export function shouldRemountLiveFrameForComposerInputChange(current, nextInput) {
1127
1228
  const currentShowsCommands = shouldShowCommandPalette(current);
@@ -1144,9 +1245,6 @@ export function applySlashCommandSuggestion(currentInput, suggestion) {
1144
1245
  input: `${before}${suggestion.command}${after}`,
1145
1246
  };
1146
1247
  }
1147
- export function isExactSlashCommandToken(token) {
1148
- return SLASH_COMMANDS.some((command) => command.command === token);
1149
- }
1150
1248
  export function insertAtCursor(state, text) {
1151
1249
  const before = state.input.slice(0, state.cursor);
1152
1250
  const after = state.input.slice(state.cursor);
@@ -1225,38 +1323,56 @@ export function navigatePromptHistory(state, direction) {
1225
1323
  promptHistoryCursor: nextCursor,
1226
1324
  };
1227
1325
  }
1228
- function getDefaultApprovalCursor() {
1229
- const denyIndex = APPROVAL_OPTIONS.findIndex((option) => option.value === 'n');
1230
- return denyIndex === -1 ? 0 : denyIndex;
1231
- }
1232
- export function getNextApprovalCursor(currentIndex, direction) {
1233
- return (currentIndex + direction + APPROVAL_OPTIONS.length) % APPROVAL_OPTIONS.length;
1234
- }
1235
- export function getApprovalChoiceForCursor(cursor) {
1236
- return (APPROVAL_OPTIONS[Math.min(Math.max(cursor, 0), APPROVAL_OPTIONS.length - 1)]
1237
- ?.value ?? 'n');
1238
- }
1239
- export function resolveApprovalChoiceFromInput(input) {
1240
- const normalizedInput = String(input ?? '').trim().toLowerCase();
1241
- if (normalizedInput === 'y')
1242
- return 'y';
1243
- if (normalizedInput === 'a')
1244
- return 'a';
1245
- if (normalizedInput === 'n')
1246
- return 'n';
1247
- return null;
1326
+ export function getDefaultApprovalCursor(optionCount) {
1327
+ return Math.max(0, optionCount - 1);
1328
+ }
1329
+ export function getNextApprovalCursor(currentIndex, direction, optionCount) {
1330
+ if (optionCount <= 0)
1331
+ return 0;
1332
+ return (currentIndex + direction + optionCount) % optionCount;
1333
+ }
1334
+ export function pauseBusyClock(state, nowMs) {
1335
+ if (state.busySince === null || state.busyPausedAt !== null)
1336
+ return state;
1337
+ return { ...state, busyPausedAt: nowMs };
1338
+ }
1339
+ export function resumeBusyClock(state, nowMs) {
1340
+ if (state.busyPausedAt === null)
1341
+ return state;
1342
+ return {
1343
+ ...state,
1344
+ busyPausedAt: null,
1345
+ busySince: state.busySince === null
1346
+ ? null
1347
+ : state.busySince + Math.max(0, nowMs - state.busyPausedAt),
1348
+ };
1349
+ }
1350
+ export function busyElapsedMs(state, nowMs) {
1351
+ if (state.busySince === null)
1352
+ return null;
1353
+ return Math.max(0, (state.busyPausedAt ?? nowMs) - state.busySince);
1354
+ }
1355
+ export function busyElapsedSeconds(state, nowMs) {
1356
+ return Math.floor((busyElapsedMs(state, nowMs) ?? 0) / 1000);
1248
1357
  }
1249
1358
  export function buildModelPickerOptions(currentModelId, serverModels) {
1250
- return serverModels.map((model) => ({
1359
+ return [
1360
+ ...serverModels.filter((model) => model.auto),
1361
+ ...serverModels.filter((model) => !model.auto),
1362
+ ].map((model) => ({
1251
1363
  id: model.id,
1252
- label: model.label,
1364
+ label: model.auto ? autoOptionLabel(model.label) : model.label,
1253
1365
  publicId: model.id,
1254
1366
  costRating: model.costRating,
1255
1367
  current: model.id === currentModelId,
1256
1368
  disabled: false,
1369
+ group: model.auto ? 'auto' : 'models',
1257
1370
  note: model.description,
1258
1371
  }));
1259
1372
  }
1373
+ function autoOptionLabel(label) {
1374
+ return /^Auto \((.+)\)$/.exec(label)?.[1] ?? label;
1375
+ }
1260
1376
  function getDefaultModelPickerIndex(currentModelId, serverModels) {
1261
1377
  const options = buildModelPickerOptions(currentModelId, serverModels);
1262
1378
  const currentIndex = options.findIndex((option) => option.id === currentModelId);
@@ -1282,10 +1398,12 @@ function appendCommandLog(state, text) {
1282
1398
  };
1283
1399
  }
1284
1400
  async function saveSessionBoth({ serverSessionClient, session, }) {
1401
+ if (!sessionHasUserMessage(session))
1402
+ return;
1285
1403
  saveSessionState(session);
1286
1404
  await serverSessionClient.save(session);
1287
1405
  }
1288
- export async function runClientInteractive({ appendPromptHistory, authConfig, debugUi, projectIndex, serverModels, serverSessionClient, session, usageText, initialPrompt, }) {
1406
+ export async function runClientInteractive({ appendPromptHistory, authConfig, debugUi, serverModels, serverSessionClient, session, usageText, initialPrompt, }) {
1289
1407
  if (process.stdin.isTTY !== true) {
1290
1408
  throw new Error('stdin is not a terminal');
1291
1409
  }
@@ -1293,17 +1411,20 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1293
1411
  throw new Error('stdout is not a terminal');
1294
1412
  }
1295
1413
  let fatalError = null;
1414
+ let signedOut = false;
1296
1415
  await withTuiMode(async () => {
1297
1416
  setBackgroundJobSession(session.sessionId);
1298
1417
  setScratchSession(session.sessionId);
1418
+ setImageStoreSession(session.sessionId);
1299
1419
  setTodoSession(session.sessionId);
1300
- const store = createShellStore(createInitialShellState(session, serverModels, debugUi));
1420
+ const store = createShellStore(createInitialShellState(session, serverModels, debugUi, authConfig.serverUrl));
1301
1421
  store.replaceTranscript(createSessionTranscript(session));
1302
1422
  let currentServerModels = serverModels;
1303
1423
  let sessionAutoYes = session.autoYes;
1304
1424
  let resolveDone = null;
1305
- let resolveApprovalChoice = null;
1425
+ let resolvePermissionDecision = null;
1306
1426
  let resolveSudoPassword = null;
1427
+ let pendingUserInput = null;
1307
1428
  let cleanupSudoPasswordPrompt = null;
1308
1429
  let sudoPasswordBuffer = '';
1309
1430
  const bridge = createRatatuiBridge();
@@ -1318,8 +1439,14 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1318
1439
  let tuiReady = false;
1319
1440
  let lastTurnStartedAt = null;
1320
1441
  let latestUsageSummary = null;
1442
+ const usageNotice = createUsageNoticeTracker();
1321
1443
  let pendingTurnEntries = [];
1322
1444
  let activeTurnAbort = null;
1445
+ let activeTurnImageAttachments = [];
1446
+ let activeServerTurnId = null;
1447
+ let unacknowledged = new Map();
1448
+ const blockedRows = new WeakMap();
1449
+ let newConversationInFlight = false;
1323
1450
  let todosTouchedThisTurn = false;
1324
1451
  const syncTodosState = () => {
1325
1452
  store.update((current) => ({ ...current, todos: listTodos() }));
@@ -1328,6 +1455,36 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1328
1455
  let exitCtrlCArmed = false;
1329
1456
  let exitCtrlCTimer = null;
1330
1457
  let transientStatusTimer = null;
1458
+ const THINKING_MIN_DWELL_MS = 3_000;
1459
+ let thinkingAppliedAt = 0;
1460
+ let pendingThinking = null;
1461
+ const applyThinking = (next) => {
1462
+ thinkingAppliedAt = Date.now();
1463
+ pendingThinking = null;
1464
+ store.update((current) => ({
1465
+ ...current,
1466
+ thinkingTitle: next.title || holdOrPickFallback(current.thinkingTitle),
1467
+ thinkingNotes: next.notes,
1468
+ }));
1469
+ };
1470
+ const queueThinkingUpdate = (next) => {
1471
+ if (Date.now() - thinkingAppliedAt >= THINKING_MIN_DWELL_MS) {
1472
+ applyThinking(next);
1473
+ return;
1474
+ }
1475
+ pendingThinking = next;
1476
+ };
1477
+ const flushPendingThinking = () => {
1478
+ if (!pendingThinking)
1479
+ return;
1480
+ if (Date.now() - thinkingAppliedAt < THINKING_MIN_DWELL_MS)
1481
+ return;
1482
+ applyThinking(pendingThinking);
1483
+ };
1484
+ const resetThinkingPacer = () => {
1485
+ thinkingAppliedAt = 0;
1486
+ pendingThinking = null;
1487
+ };
1331
1488
  const done = new Promise((resolve) => {
1332
1489
  resolveDone = resolve;
1333
1490
  });
@@ -1341,15 +1498,17 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1341
1498
  void remountTui();
1342
1499
  }, 0);
1343
1500
  };
1344
- const showTransientStatus = (status) => {
1501
+ const showTransientStatus = (transientStatus) => {
1345
1502
  if (transientStatusTimer) {
1346
1503
  clearTimeout(transientStatusTimer);
1347
1504
  transientStatusTimer = null;
1348
1505
  }
1349
- store.update((current) => ({ ...current, status }));
1506
+ store.update((current) => ({ ...current, transientStatus }));
1350
1507
  transientStatusTimer = setTimeout(() => {
1351
1508
  transientStatusTimer = null;
1352
- store.update((current) => current.status === status ? { ...current, status: 'Ready' } : current);
1509
+ store.update((current) => current.transientStatus === transientStatus
1510
+ ? { ...current, transientStatus: null }
1511
+ : current);
1353
1512
  }, 2500);
1354
1513
  };
1355
1514
  const terminalTitle = createTerminalTitleController({
@@ -1362,14 +1521,43 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1362
1521
  busy: state.busy,
1363
1522
  });
1364
1523
  };
1524
+ const notifier = backendFor();
1525
+ let notificationHandle = null;
1526
+ const projectLabel = basename(session.rootDir) || 'TheGitAI';
1527
+ const notifications = createNotificationQueue();
1528
+ const attention = createAttentionController({
1529
+ notify: (kind) => {
1530
+ notifications.run(async () => {
1531
+ notificationHandle = await notifier.post({
1532
+ title: projectLabel,
1533
+ body: kind === 'blocked'
1534
+ ? 'Waiting for your answer'
1535
+ : 'Finished \u2014 your turn',
1536
+ }, notificationHandle);
1537
+ });
1538
+ },
1539
+ withdraw: () => {
1540
+ notifications.run(async () => {
1541
+ notifier.withdraw(notificationHandle);
1542
+ notificationHandle = null;
1543
+ });
1544
+ },
1545
+ });
1546
+ const syncAttention = () => {
1547
+ const state = store.getState();
1548
+ attention.sync({
1549
+ awaitingAnswer: Boolean(state.approvalPrompt || state.sudoPrompt || state.userInputPrompt),
1550
+ busy: state.busy,
1551
+ focused: state.terminalFocused,
1552
+ }, state.notificationsEnabled);
1553
+ };
1365
1554
  const renderCurrentFrame = () => {
1366
1555
  if (!tuiReady)
1367
1556
  return;
1368
1557
  const state = store.getState();
1369
1558
  syncTerminalTitle();
1370
- const elapsedSeconds = state.busySince
1371
- ? Math.max(0, Math.floor((Date.now() - state.busySince) / 1000))
1372
- : 0;
1559
+ syncAttention();
1560
+ const elapsedSeconds = busyElapsedSeconds(state, Date.now());
1373
1561
  bridge.render(buildTuiFrame(state, terminalCols, terminalRows, spinnerFrame, elapsedSeconds, Date.now()));
1374
1562
  };
1375
1563
  const remountTui = async () => {
@@ -1495,15 +1683,16 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1495
1683
  }
1496
1684
  };
1497
1685
  const dismissPendingApproval = () => {
1498
- if (!resolveApprovalChoice)
1686
+ if (!resolvePermissionDecision)
1499
1687
  return;
1500
- const pendingResolve = resolveApprovalChoice;
1501
- resolveApprovalChoice = null;
1502
- pendingResolve('n');
1688
+ const pendingResolve = resolvePermissionDecision;
1689
+ resolvePermissionDecision = null;
1690
+ pendingResolve({ kind: 'deny' });
1503
1691
  store.update((current) => ({
1504
- ...current,
1505
- approvalCursor: getDefaultApprovalCursor(),
1692
+ ...resumeBusyClock(current, Date.now()),
1693
+ approvalCursor: 0,
1506
1694
  approvalPrompt: null,
1695
+ approvalScrollOffset: 0,
1507
1696
  }));
1508
1697
  };
1509
1698
  const dismissPendingSudoPassword = () => {
@@ -1516,21 +1705,40 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1516
1705
  sudoPasswordBuffer = '';
1517
1706
  pendingResolve(null);
1518
1707
  store.update((current) => ({
1519
- ...current,
1708
+ ...resumeBusyClock(current, Date.now()),
1520
1709
  sudoPrompt: null,
1521
1710
  }));
1522
1711
  };
1712
+ const dismissPendingUserInput = () => {
1713
+ const pending = pendingUserInput;
1714
+ if (!pending)
1715
+ return;
1716
+ pendingUserInput = null;
1717
+ pending.signal?.removeEventListener('abort', pending.onAbort);
1718
+ const error = new Error('Turn cancelled.');
1719
+ error.name = 'AbortError';
1720
+ pending.reject(error);
1721
+ store.update((current) => ({
1722
+ ...resumeBusyClock(current, Date.now()),
1723
+ status: current.userInputPrompt?.returnStatus ?? current.status,
1724
+ userInputPrompt: null,
1725
+ }));
1726
+ };
1523
1727
  const cancelActiveTurn = () => {
1524
- if (!store.getState().busy)
1728
+ if (!store.getState().busy || newConversationInFlight)
1525
1729
  return;
1526
1730
  disarmExitConfirm();
1527
1731
  dismissPendingApproval();
1528
1732
  dismissPendingSudoPassword();
1733
+ dismissPendingUserInput();
1529
1734
  activeTurnGeneration += 1;
1735
+ resetThinkingPacer();
1530
1736
  activeTurnAbort?.abort();
1531
1737
  activeTurnAbort = null;
1532
1738
  cancelActiveCommand();
1533
1739
  const queued = store.getState().queuedMessage;
1740
+ const restoredAttachments = composerAttachmentsAfterCancel(queued ? queued.imageAttachments : [], activeTurnImageAttachments);
1741
+ activeTurnImageAttachments = [];
1534
1742
  const cancelledEntries = [
1535
1743
  ...takePendingTurnEntries(),
1536
1744
  {
@@ -1544,20 +1752,23 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1544
1752
  activeTurnInput: '',
1545
1753
  activeTurnInputPreformatted: false,
1546
1754
  busy: false,
1755
+ busyPausedAt: null,
1547
1756
  busySince: null,
1548
1757
  commandLog: [],
1549
1758
  cursor: queued ? queued.body.length : current.cursor,
1550
- imageAttachments: queued ? queued.imageAttachments : [],
1759
+ imageAttachments: restoredAttachments,
1551
1760
  input: queued ? queued.body : current.input,
1552
1761
  pastedChunks: queued ? queued.pastedChunks : current.pastedChunks,
1553
1762
  promptHistoryCursor: queued ? null : current.promptHistoryCursor,
1554
1763
  promptHistoryDraft: queued ? '' : current.promptHistoryDraft,
1555
1764
  queuedMessage: null,
1765
+ recoveryStatus: '',
1556
1766
  status: 'Ready',
1557
1767
  thinkingTitle: '',
1558
1768
  thinkingNotes: [],
1769
+ turnMessages: [],
1559
1770
  workingTools: [],
1560
- tokenUsage: formatClientTokenUsage(current.busySince == null ? null : Date.now() - current.busySince, latestUsageSummary),
1771
+ tokenUsage: formatClientTokenUsage(busyElapsedMs(current, Date.now()), latestUsageSummary),
1561
1772
  }));
1562
1773
  appendStaticEntries(cancelledEntries);
1563
1774
  lastTurnStartedAt = null;
@@ -1572,6 +1783,7 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1572
1783
  autoYes: sessionAutoYes,
1573
1784
  commandCursor: 0,
1574
1785
  currentModelId: session.modelId,
1786
+ reasoningEffort: projectModelEffort(readProjectModelEfforts(session.rootDir, authConfig.serverUrl, session.env), session.modelId),
1575
1787
  sessionId: session.sessionId,
1576
1788
  modelPickerIndex: current.modelPickerOpen
1577
1789
  ? getDefaultModelPickerIndex(session.modelId, current.serverModels)
@@ -1595,6 +1807,9 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1595
1807
  setAgentMode(nextAgentMode(session.agentMode));
1596
1808
  scheduleLiveFrameRemount();
1597
1809
  };
1810
+ const reportAgentModeLocked = () => {
1811
+ showTransientStatus(AGENT_MODE_LOCKED_STATUS);
1812
+ };
1598
1813
  const clearLiveFrameRemountTimer = () => {
1599
1814
  if (!liveFrameRemountTimer)
1600
1815
  return;
@@ -1643,6 +1858,7 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1643
1858
  }
1644
1859
  dismissPendingApproval();
1645
1860
  dismissPendingSudoPassword();
1861
+ dismissPendingUserInput();
1646
1862
  exiting = true;
1647
1863
  killAllBackgroundJobs();
1648
1864
  store.update((current) => ({
@@ -1660,7 +1876,9 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1660
1876
  if (!isAuthenticationError(error))
1661
1877
  return false;
1662
1878
  clearCliAuthConfig(session.env);
1663
- saveSessionState(session);
1879
+ if (sessionHasUserMessage(session)) {
1880
+ saveSessionState(session);
1881
+ }
1664
1882
  fatalError = new Error(authenticationErrorMessage(error));
1665
1883
  requestExit();
1666
1884
  return true;
@@ -1677,6 +1895,18 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1677
1895
  return true;
1678
1896
  }
1679
1897
  };
1898
+ const saveActiveSessionOrAbort = async () => {
1899
+ try {
1900
+ await saveSessionBoth({ serverSessionClient, session });
1901
+ return true;
1902
+ }
1903
+ catch (error) {
1904
+ if (exitForAuthenticationError(error))
1905
+ return false;
1906
+ appendError(`Session save failed: ${error.message}`);
1907
+ return false;
1908
+ }
1909
+ };
1680
1910
  const openSudoPasswordPrompt = (command, prompt, signal) => new Promise((resolve) => {
1681
1911
  if (exiting || signal?.aborted) {
1682
1912
  resolve(null);
@@ -1694,7 +1924,7 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1694
1924
  cleanupSudoPasswordPrompt = null;
1695
1925
  }
1696
1926
  store.update((current) => ({
1697
- ...current,
1927
+ ...pauseBusyClock(current, Date.now()),
1698
1928
  sudoPrompt: {
1699
1929
  command,
1700
1930
  passwordLength: 0,
@@ -1714,7 +1944,7 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1714
1944
  cleanupSudoPasswordPrompt = null;
1715
1945
  sudoPasswordBuffer = '';
1716
1946
  store.update((current) => ({
1717
- ...current,
1947
+ ...resumeBusyClock(current, Date.now()),
1718
1948
  sudoPrompt: null,
1719
1949
  status: current.sudoPrompt?.returnStatus ?? current.status,
1720
1950
  }));
@@ -1728,7 +1958,7 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1728
1958
  cleanupSudoPasswordPrompt = null;
1729
1959
  sudoPasswordBuffer = '';
1730
1960
  store.update((current) => ({
1731
- ...current,
1961
+ ...resumeBusyClock(current, Date.now()),
1732
1962
  sudoPrompt: null,
1733
1963
  status: current.sudoPrompt?.returnStatus ?? current.status,
1734
1964
  }));
@@ -1748,38 +1978,95 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1748
1978
  : null,
1749
1979
  }));
1750
1980
  };
1751
- const openApprovalPrompt = (title, body, options = {}) => new Promise((resolve) => {
1752
- if (exiting) {
1753
- resolve('n');
1981
+ const openUserInputPrompt = (questions, signal) => new Promise((resolve, reject) => {
1982
+ if (exiting || signal?.aborted) {
1983
+ const error = new Error('Turn cancelled.');
1984
+ error.name = 'AbortError';
1985
+ reject(error);
1754
1986
  return;
1755
1987
  }
1756
- resolveApprovalChoice = resolve;
1988
+ const onAbort = () => dismissPendingUserInput();
1989
+ pendingUserInput = {
1990
+ questions,
1991
+ resolve,
1992
+ reject,
1993
+ signal,
1994
+ onAbort,
1995
+ };
1996
+ signal?.addEventListener('abort', onAbort, { once: true });
1757
1997
  store.update((current) => ({
1758
- ...current,
1759
- approvalCursor: getDefaultApprovalCursor(),
1998
+ ...pauseBusyClock(current, Date.now()),
1999
+ ...closedJobsPickerFields(current),
2000
+ status: 'Waiting for your input',
2001
+ userInputPrompt: createUserInputPromptState(questions, statusBehindJobsPicker(current)),
2002
+ }));
2003
+ scheduleLiveFrameRemount();
2004
+ });
2005
+ const handleInlineUserInput = async (result) => {
2006
+ const pending = pendingUserInput;
2007
+ const prompt = store.getState().userInputPrompt;
2008
+ if (!pending || !prompt)
2009
+ return;
2010
+ pendingUserInput = null;
2011
+ pending.signal?.removeEventListener('abort', pending.onAbort);
2012
+ store.update((current) => ({
2013
+ ...resumeBusyClock(current, Date.now()),
2014
+ status: prompt.returnStatus,
2015
+ userInputPrompt: null,
2016
+ }));
2017
+ appendTurnAwareEntry({
2018
+ body: formatUserInputTranscript(pending.questions, result),
2019
+ kind: result.status === 'submitted' ? 'user' : 'system',
2020
+ title: result.status === 'submitted' ? 'Your answers' : 'Question',
2021
+ });
2022
+ pending.resolve(result);
2023
+ scheduleLiveFrameRemount();
2024
+ };
2025
+ const openApprovalPrompt = (request, signal) => new Promise((resolve) => {
2026
+ const deny = { kind: 'deny' };
2027
+ if (exiting || signal?.aborted) {
2028
+ resolve(deny);
2029
+ return;
2030
+ }
2031
+ const onAbort = () => dismissPendingApproval();
2032
+ signal?.addEventListener('abort', onAbort, { once: true });
2033
+ resolvePermissionDecision = (decision) => {
2034
+ signal?.removeEventListener('abort', onAbort);
2035
+ resolve(decision);
2036
+ };
2037
+ store.update((current) => ({
2038
+ ...pauseBusyClock(current, Date.now()),
2039
+ ...closedJobsPickerFields(current),
2040
+ approvalCursor: getDefaultApprovalCursor(request.options.length),
2041
+ approvalOpenedAt: Date.now(),
2042
+ approvalScrollOffset: 0,
1760
2043
  approvalPrompt: {
1761
- title,
1762
- body,
1763
- diffPreview: options.diff && options.filePath
1764
- ? parseDiffPreview(options.diff)
2044
+ title: request.title,
2045
+ body: request.body,
2046
+ diffPreview: request.diff && request.filePath
2047
+ ? parseDiffPreview(request.diff)
1765
2048
  : undefined,
1766
- filePath: options.filePath,
1767
- returnStatus: current.status,
2049
+ filePath: request.filePath,
2050
+ options: request.options,
2051
+ returnStatus: statusBehindJobsPicker(current),
1768
2052
  },
1769
- status: title,
2053
+ status: request.title,
1770
2054
  }));
1771
2055
  });
1772
- const handleInlineApprovalChoice = async (choice) => {
2056
+ const handleInlineApprovalChoice = async (index) => {
1773
2057
  const current = store.getState();
1774
- const pendingResolve = resolveApprovalChoice;
1775
- resolveApprovalChoice = null;
2058
+ const options = current.approvalPrompt?.options ?? [];
2059
+ const chosen = options[index]?.decision ?? { kind: 'deny' };
2060
+ const pendingResolve = resolvePermissionDecision;
2061
+ resolvePermissionDecision = null;
1776
2062
  store.update((next) => ({
1777
- ...next,
1778
- approvalCursor: getDefaultApprovalCursor(),
2063
+ ...resumeBusyClock(next, Date.now()),
2064
+ approvalCursor: getDefaultApprovalCursor(options.length),
1779
2065
  approvalPrompt: null,
2066
+ approvalScrollOffset: 0,
1780
2067
  status: current.approvalPrompt?.returnStatus ?? next.status,
1781
2068
  }));
1782
- pendingResolve?.(choice);
2069
+ pendingResolve?.(chosen);
1783
2070
  };
1784
2071
  const refreshServerModels = async () => {
1785
2072
  currentServerModels = await models.fetchServerModels({ config: authConfig });
@@ -1798,15 +2085,19 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1798
2085
  input: '',
1799
2086
  modelPickerIndex: getDefaultModelPickerIndex(current.currentModelId, fresh.models),
1800
2087
  modelPickerOpen: true,
2088
+ modelPickerEfforts: readProjectModelEfforts(session.rootDir, authConfig.serverUrl, session.env),
1801
2089
  status: 'Select a model',
1802
2090
  }));
1803
2091
  };
1804
- const switchToModel = async (modelId) => {
2092
+ const switchToModel = async (modelId, effort) => {
1805
2093
  const requested = Number(modelId);
1806
2094
  const fresh = currentServerModels.models.some((model) => model.id === requested)
1807
2095
  ? currentServerModels
1808
2096
  : await refreshServerModels();
1809
2097
  const selected = models.validateServerModel(modelId, fresh);
2098
+ if (effort !== undefined) {
2099
+ saveProjectModelEffort(session.rootDir, selected, effort, authConfig.serverUrl, session.env);
2100
+ }
1810
2101
  session.modelId = selected;
1811
2102
  models.updateSelectedModelCache({
1812
2103
  config: authConfig,
@@ -1817,29 +2108,42 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1817
2108
  return;
1818
2109
  syncShellStateFromSession();
1819
2110
  appendStaticEntry({
1820
- body: `Switched to ${formatModelLabel(selected, fresh.models)}. Conversation history preserved.`,
2111
+ body: fresh.models.some((model) => model.id === selected && model.auto)
2112
+ ? formatModelLabel(selected, fresh.models)
2113
+ : `${formatModelLabel(selected, fresh.models)} · ${REASONING_EFFORT_LABELS[store.getState().reasoningEffort]} effort${effort === undefined ? '' : '\nSaved for this model in this project.'}`,
1821
2114
  kind: 'system',
1822
2115
  title: 'Model',
1823
2116
  });
1824
2117
  };
2118
+ const toggleNotifications = () => {
2119
+ const enabled = !store.getState().notificationsEnabled;
2120
+ store.update((current) => ({ ...current, notificationsEnabled: enabled }));
2121
+ try {
2122
+ writePreferences({ ...readPreferences(session.env), notifications: enabled }, session.env);
2123
+ }
2124
+ catch {
2125
+ }
2126
+ showTransientStatus(enabled ? 'Notifications on' : 'Notifications off');
2127
+ };
1825
2128
  const openJobsPicker = () => {
2129
+ if (store.getState().jobsPickerOpen)
2130
+ return;
1826
2131
  syncBackgroundJobsState();
1827
2132
  store.update((current) => ({
1828
2133
  ...current,
1829
2134
  commandCursor: 0,
1830
- cursor: 0,
1831
- input: '',
1832
2135
  jobsPickerExpandedId: null,
1833
2136
  jobsPickerIndex: 0,
1834
2137
  jobsPickerOpen: true,
2138
+ jobsPickerReturnStatus: current.status,
1835
2139
  status: 'Background jobs',
1836
2140
  }));
2141
+ scheduleLiveFrameRemount();
1837
2142
  };
1838
2143
  const appendJobOutputEntry = async (jobId) => {
1839
2144
  const id = jobId.trim();
1840
2145
  await collectBackgroundJobUiOutputMutations({
1841
2146
  session,
1842
- projectIndex,
1843
2147
  jobId: id,
1844
2148
  });
1845
2149
  const job = listBackgroundJobs().find((candidate) => candidate.id === id);
@@ -1865,32 +2169,51 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1865
2169
  const index = Math.min(Math.max(current.jobsPickerIndex, 0), current.backgroundJobs.length - 1);
1866
2170
  return current.backgroundJobs[index]?.id ?? null;
1867
2171
  };
2172
+ const deferredJobMutationIds = new Set();
2173
+ const drainDeferredJobMutations = async () => {
2174
+ if (deferredJobMutationIds.size === 0)
2175
+ return;
2176
+ const pending = [...deferredJobMutationIds];
2177
+ deferredJobMutationIds.clear();
2178
+ for (const jobId of pending) {
2179
+ await collectBackgroundJobUiOutputMutations({ session, jobId });
2180
+ }
2181
+ syncBackgroundJobsState();
2182
+ };
1868
2183
  const handleJobsPickerOutput = async () => {
1869
2184
  const jobId = selectedJobsPickerId();
1870
2185
  if (!jobId)
1871
2186
  return;
1872
- await collectBackgroundJobUiOutputMutations({
1873
- session,
1874
- projectIndex,
1875
- jobId,
1876
- });
1877
- syncBackgroundJobsState();
2187
+ if (store.getState().busy) {
2188
+ deferredJobMutationIds.add(jobId);
2189
+ }
2190
+ else {
2191
+ await collectBackgroundJobUiOutputMutations({
2192
+ session,
2193
+ jobId,
2194
+ });
2195
+ }
1878
2196
  store.update((current) => ({
1879
2197
  ...current,
1880
2198
  jobsPickerExpandedId: current.jobsPickerExpandedId === jobId ? null : jobId,
1881
2199
  }));
2200
+ syncBackgroundJobsState();
1882
2201
  };
1883
2202
  const handleJobsPickerKill = async () => {
1884
2203
  const jobId = selectedJobsPickerId();
1885
2204
  if (!jobId)
1886
2205
  return;
1887
2206
  const killed = await killBackgroundJob(jobId);
1888
- await collectBackgroundJobUiKillMutations({
1889
- session,
1890
- projectIndex,
1891
- jobId,
1892
- result: killed,
1893
- });
2207
+ if (store.getState().busy) {
2208
+ deferredJobMutationIds.add(jobId);
2209
+ }
2210
+ else {
2211
+ await collectBackgroundJobUiKillMutations({
2212
+ session,
2213
+ jobId,
2214
+ result: killed,
2215
+ });
2216
+ }
1894
2217
  syncBackgroundJobsState();
1895
2218
  if (!killed.ok) {
1896
2219
  appendError(killed.error ?? 'Background job kill failed.');
@@ -1921,16 +2244,8 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1921
2244
  });
1922
2245
  return;
1923
2246
  }
1924
- if (selected.id === current.currentModelId) {
1925
- appendStaticEntry({
1926
- body: `Already using ${formatModelLabel(selected.id, current.serverModels)}.`,
1927
- kind: 'system',
1928
- title: 'Model',
1929
- });
1930
- return;
1931
- }
1932
2247
  try {
1933
- await switchToModel(selected.id);
2248
+ await switchToModel(selected.id, projectModelEffort(current.modelPickerEfforts ?? {}, selected.id));
1934
2249
  }
1935
2250
  catch (error) {
1936
2251
  if (exitForAuthenticationError(error))
@@ -1984,15 +2299,24 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1984
2299
  store.update((next) => ({
1985
2300
  ...next,
1986
2301
  busy: true,
2302
+ busyPausedAt: null,
1987
2303
  busySince: resumeStartedAt,
1988
2304
  clockNow: resumeStartedAt,
1989
2305
  status: 'Loading session...',
1990
2306
  }));
1991
2307
  try {
1992
2308
  const snapshot = await loadInteractiveSession(selected.id);
1993
- applySessionSnapshot(session, snapshot);
2309
+ const requestedModelId = Number(snapshot.modelId);
2310
+ const knownModels = currentServerModels.models.some((model) => model.id === requestedModelId)
2311
+ ? currentServerModels
2312
+ : await refreshServerModels();
2313
+ const { modelId: resolvedModelId, fellBack } = models.resolveResumedSessionModel(requestedModelId, knownModels);
2314
+ applySessionSnapshot(session, snapshot, {
2315
+ modelOverride: fellBack ? resolvedModelId : undefined,
2316
+ });
1994
2317
  setBackgroundJobSession(session.sessionId);
1995
2318
  setScratchSession(session.sessionId);
2319
+ setImageStoreSession(session.sessionId);
1996
2320
  syncBackgroundJobsState();
1997
2321
  setTodoSession(session.sessionId);
1998
2322
  syncTodosState();
@@ -2000,6 +2324,7 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2000
2324
  store.update((next) => ({
2001
2325
  ...next,
2002
2326
  busy: false,
2327
+ busyPausedAt: null,
2003
2328
  busySince: null,
2004
2329
  resumePickerFilter: '',
2005
2330
  resumePickerIndex: 0,
@@ -2013,6 +2338,15 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2013
2338
  kind: 'system',
2014
2339
  title: 'Session',
2015
2340
  },
2341
+ ...(fellBack
2342
+ ? [
2343
+ {
2344
+ body: `This session's model is no longer available — switched to ${formatModelLabel(resolvedModelId, knownModels.models)}. Conversation history preserved.`,
2345
+ kind: 'system',
2346
+ title: 'Model',
2347
+ },
2348
+ ]
2349
+ : []),
2016
2350
  ...buildTranscriptFromSessionHistory(session.history),
2017
2351
  ]);
2018
2352
  await remountTui();
@@ -2023,6 +2357,7 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2023
2357
  store.update((next) => ({
2024
2358
  ...next,
2025
2359
  busy: false,
2360
+ busyPausedAt: null,
2026
2361
  busySince: null,
2027
2362
  resumePickerFilter: '',
2028
2363
  resumePickerIndex: 0,
@@ -2046,8 +2381,130 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2046
2381
  }));
2047
2382
  await handleSubmit(queued.body);
2048
2383
  };
2049
- const handleSubmit = async (rawInput) => {
2050
- const chunks = store.getState().pastedChunks;
2384
+ let turnMessageCounter = 0;
2385
+ const upsertTurnMessage = (id, patch) => {
2386
+ store.update((current) => ({
2387
+ ...current,
2388
+ turnMessages: current.turnMessages.map((message) => message.id === id ? { ...message, ...patch } : message),
2389
+ }));
2390
+ };
2391
+ const recoverUnacknowledgedMessages = (autoSubmits = true) => {
2392
+ if (unacknowledged.size === 0)
2393
+ return;
2394
+ const stranded = [...unacknowledged.values()];
2395
+ unacknowledged = new Map();
2396
+ for (const { row } of stranded) {
2397
+ upsertTurnMessage(row, {
2398
+ state: 'queued',
2399
+ note: autoSubmits
2400
+ ? 'not read — sending as the next prompt'
2401
+ : 'not read — left in the composer',
2402
+ });
2403
+ }
2404
+ const existing = store.getState().queuedMessage;
2405
+ const combined = [
2406
+ ...stranded.map((entry) => entry.queued),
2407
+ ...(existing ? [existing] : []),
2408
+ ];
2409
+ const body = combined
2410
+ .map((entry) => entry.body)
2411
+ .filter((entry) => entry.trim())
2412
+ .join('\n\n');
2413
+ if (!body.trim())
2414
+ return;
2415
+ scheduleLiveFrameRemount();
2416
+ store.update((current) => ({
2417
+ ...current,
2418
+ queuedMessage: {
2419
+ body,
2420
+ imageAttachments: combined.flatMap((entry) => entry.imageAttachments),
2421
+ pastedChunks: combined.flatMap((entry) => entry.pastedChunks),
2422
+ },
2423
+ }));
2424
+ };
2425
+ const fireQueuedMessage = async () => {
2426
+ const state = store.getState();
2427
+ const queued = state.queuedMessage;
2428
+ if (!queued || !state.busy || exiting)
2429
+ return;
2430
+ const text = (queued.pastedChunks.length
2431
+ ? expandPastedChunks(queued.body, queued.pastedChunks)
2432
+ : queued.body).trim();
2433
+ const images = queued.imageAttachments.filter((attachment) => queued.body.includes(`[Image #${attachment.index}]`));
2434
+ if (!text && images.length === 0)
2435
+ return;
2436
+ const turnId = activeServerTurnId;
2437
+ const blockedReason = !turnId ? 'waiting for the turn to end' : null;
2438
+ const existingRow = blockedRows.get(queued);
2439
+ if (existingRow !== undefined) {
2440
+ upsertTurnMessage(existingRow, {
2441
+ state: 'queued',
2442
+ ...(blockedReason ? { note: blockedReason } : {}),
2443
+ });
2444
+ if (blockedReason || !turnId)
2445
+ return;
2446
+ }
2447
+ const id = existingRow ?? ++turnMessageCounter;
2448
+ const messageId = `m${id}_${Date.now().toString(36)}`;
2449
+ if (existingRow === undefined) {
2450
+ scheduleLiveFrameRemount();
2451
+ store.update((current) => ({
2452
+ ...current,
2453
+ turnMessages: [
2454
+ ...current.turnMessages,
2455
+ {
2456
+ id,
2457
+ text,
2458
+ state: blockedReason ? 'queued' : 'sending',
2459
+ ...(blockedReason ? { note: blockedReason } : {}),
2460
+ },
2461
+ ],
2462
+ }));
2463
+ }
2464
+ if (blockedReason || !turnId) {
2465
+ blockedRows.set(queued, id);
2466
+ return;
2467
+ }
2468
+ blockedRows.delete(queued);
2469
+ unacknowledged.set(messageId, { row: id, queued });
2470
+ scheduleLiveFrameRemount();
2471
+ store.update((current) => current.queuedMessage === queued
2472
+ ? { ...current, queuedMessage: null }
2473
+ : current);
2474
+ queueTurnEntry({
2475
+ body: text,
2476
+ kind: 'user',
2477
+ preformatted: queued.pastedChunks.length > 0,
2478
+ title: 'You · sent mid-turn',
2479
+ });
2480
+ const rollback = (note) => {
2481
+ if (!unacknowledged.delete(messageId))
2482
+ return;
2483
+ upsertTurnMessage(id, { state: 'queued', note });
2484
+ scheduleLiveFrameRemount();
2485
+ store.update((current) => current.queuedMessage ? current : { ...current, queuedMessage: queued });
2486
+ };
2487
+ let outcome;
2488
+ try {
2489
+ outcome = await chat.postInterjection({
2490
+ config: authConfig,
2491
+ turnId,
2492
+ text,
2493
+ messageId,
2494
+ imageAttachments: images,
2495
+ });
2496
+ }
2497
+ catch (error) {
2498
+ rollback(`not sent — ${error?.message ?? 'request failed'}`);
2499
+ return;
2500
+ }
2501
+ if (outcome === 'stale') {
2502
+ rollback('turn ended — sending as the next prompt');
2503
+ }
2504
+ };
2505
+ const jobWait = createJobWaitTracker(() => session.sessionId);
2506
+ const handleSubmit = async (rawInput, { jobFollowUp = false } = {}) => {
2507
+ const chunks = jobFollowUp ? [] : store.getState().pastedChunks;
2051
2508
  const expanded = chunks.length
2052
2509
  ? expandPastedChunks(String(rawInput ?? ''), chunks)
2053
2510
  : String(rawInput ?? '');
@@ -2057,17 +2514,39 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2057
2514
  if (!input || exiting)
2058
2515
  return;
2059
2516
  if (input.startsWith('/')) {
2517
+ if (isJobsPickerCommand(input)) {
2518
+ store.update((current) => ({
2519
+ ...current,
2520
+ cursor: 0,
2521
+ input: '',
2522
+ pastedChunks: [],
2523
+ }));
2524
+ openJobsPicker();
2525
+ return;
2526
+ }
2527
+ if (input === '/notify') {
2528
+ store.update((current) => ({
2529
+ ...current,
2530
+ cursor: 0,
2531
+ input: '',
2532
+ pastedChunks: [],
2533
+ }));
2534
+ toggleNotifications();
2535
+ return;
2536
+ }
2060
2537
  appendTurnAwareEntry({
2061
- body: "Slash commands can't be queued while a turn is running.",
2538
+ body: "Slash commands can't be queued while a turn is running. " +
2539
+ 'Ctrl+B opens background jobs, Ctrl+G toggles notifications.',
2062
2540
  kind: 'system',
2063
2541
  title: 'Queued',
2064
2542
  });
2065
2543
  return;
2066
2544
  }
2067
2545
  const pending = store.getState();
2546
+ const body = String(rawInput ?? '');
2068
2547
  const snapshot = {
2069
- body: String(rawInput ?? ''),
2070
- imageAttachments: pending.imageAttachments,
2548
+ body,
2549
+ imageAttachments: pending.imageAttachments.filter((attachment) => body.includes(`[Image #${attachment.index}]`)),
2071
2550
  pastedChunks: pending.pastedChunks,
2072
2551
  };
2073
2552
  scheduleLiveFrameRemount();
@@ -2082,19 +2561,24 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2082
2561
  }));
2083
2562
  return;
2084
2563
  }
2085
- const imageAttachments = store.getState().imageAttachments;
2086
- scheduleLiveFrameRemount();
2087
- store.update((current) => ({
2088
- ...current,
2089
- cursor: 0,
2090
- input: '',
2091
- pastedChunks: [],
2092
- promptHistory: appendPromptToHistory(current.promptHistory, input),
2093
- promptHistoryCursor: null,
2094
- promptHistoryDraft: '',
2095
- }));
2096
- appendPromptHistory(input);
2097
- if (!input || exiting) {
2564
+ const imageAttachments = store
2565
+ .getState()
2566
+ .imageAttachments.filter((attachment) => input.includes(`[Image #${attachment.index}]`));
2567
+ if (!jobFollowUp) {
2568
+ scheduleLiveFrameRemount();
2569
+ store.update((current) => ({
2570
+ ...current,
2571
+ cursor: 0,
2572
+ imageAttachments: [],
2573
+ input: '',
2574
+ pastedChunks: [],
2575
+ promptHistory: appendPromptToHistory(current.promptHistory, input),
2576
+ promptHistoryCursor: null,
2577
+ promptHistoryDraft: '',
2578
+ }));
2579
+ appendPromptHistory(input);
2580
+ }
2581
+ if ((!input && !jobFollowUp) || exiting) {
2098
2582
  store.update((current) => ({ ...current, imageAttachments: [] }));
2099
2583
  return;
2100
2584
  }
@@ -2102,6 +2586,43 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2102
2586
  requestExit();
2103
2587
  return;
2104
2588
  }
2589
+ if (input === '/logout') {
2590
+ store.update((current) => ({
2591
+ ...current,
2592
+ busy: true,
2593
+ status: 'Signing out...',
2594
+ }));
2595
+ try {
2596
+ await logoutFromServer({ config: authConfig });
2597
+ }
2598
+ catch {
2599
+ }
2600
+ clearCliAuthConfig(session.env);
2601
+ signedOut = true;
2602
+ requestExit();
2603
+ return;
2604
+ }
2605
+ if (input === '/mcp') {
2606
+ const connections = sessionMcp(session);
2607
+ const controller = new AbortController();
2608
+ activeTurnAbort = controller;
2609
+ store.update((current) => ({ ...current, busy: true, status: 'Checking MCP servers...', activeTurnInput: '/mcp' }));
2610
+ try {
2611
+ await connections.discover(controller.signal, { force: true });
2612
+ appendStaticEntry({ body: connections.status(), kind: 'system', title: 'MCP servers' });
2613
+ }
2614
+ catch (error) {
2615
+ appendStaticEntry({ body: controller.signal.aborted ? 'MCP discovery cancelled.' : String(error.message), kind: 'system', title: 'MCP servers' });
2616
+ }
2617
+ finally {
2618
+ if (activeTurnAbort === controller)
2619
+ activeTurnAbort = null;
2620
+ store.update((current) => ({ ...current, busy: false, activeTurnInput: '', status: '' }));
2621
+ await remountTui();
2622
+ }
2623
+ await flushQueuedMessage();
2624
+ return;
2625
+ }
2105
2626
  if (input === '/help') {
2106
2627
  appendStaticEntry({
2107
2628
  body: formatInteractiveHelpText(),
@@ -2118,6 +2639,15 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2118
2639
  });
2119
2640
  return;
2120
2641
  }
2642
+ if (input === '/report') {
2643
+ const opened = await openUrl(REPORT_ISSUE_URL);
2644
+ appendStaticEntries(buildReportTranscriptEntries(opened));
2645
+ return;
2646
+ }
2647
+ if (input === '/notify') {
2648
+ toggleNotifications();
2649
+ return;
2650
+ }
2121
2651
  if (input === '/jobs' || input.startsWith('/jobs ')) {
2122
2652
  const jobsArgs = input.slice('/jobs'.length).trim();
2123
2653
  if (!jobsArgs) {
@@ -2130,7 +2660,6 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2130
2660
  const killed = await killBackgroundJob(jobId);
2131
2661
  await collectBackgroundJobUiKillMutations({
2132
2662
  session,
2133
- projectIndex,
2134
2663
  jobId,
2135
2664
  result: killed,
2136
2665
  });
@@ -2243,34 +2772,71 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2243
2772
  }
2244
2773
  return;
2245
2774
  }
2246
- if (input === '/clear') {
2247
- clearConversation(session);
2775
+ if (input === '/new') {
2776
+ newConversationInFlight = true;
2777
+ store.update((current) => ({
2778
+ ...current,
2779
+ busy: true,
2780
+ busyPausedAt: null,
2781
+ busySince: Date.now(),
2782
+ imageAttachments: [],
2783
+ queuedMessage: null,
2784
+ status: 'Starting a new conversation...',
2785
+ }));
2786
+ if (!(await saveActiveSessionOrAbort())) {
2787
+ newConversationInFlight = false;
2788
+ store.update((current) => ({
2789
+ ...current,
2790
+ busy: false,
2791
+ busyPausedAt: null,
2792
+ busySince: null,
2793
+ status: 'Ready',
2794
+ }));
2795
+ await flushQueuedMessage();
2796
+ return;
2797
+ }
2798
+ startNewConversation(session);
2799
+ setBackgroundJobSession(session.sessionId);
2800
+ setScratchSession(session.sessionId);
2801
+ setImageStoreSession(session.sessionId);
2802
+ setTodoSession(session.sessionId);
2248
2803
  clearTodos();
2804
+ syncBackgroundJobsState();
2249
2805
  syncTodosState();
2250
2806
  latestUsageSummary = null;
2251
- if (!(await saveActiveSession()))
2252
- return;
2253
2807
  store.replaceTranscript([
2254
2808
  {
2255
- body: 'Conversation cleared.',
2809
+ body: 'Started a new conversation. The previous session remains saved.',
2256
2810
  kind: 'system',
2257
- title: 'System',
2811
+ title: 'Session',
2258
2812
  },
2259
2813
  ]);
2814
+ await saveActiveSession();
2260
2815
  syncShellStateFromSession();
2261
- store.update((current) => ({ ...current, queuedMessage: null }));
2816
+ newConversationInFlight = false;
2817
+ store.update((current) => ({
2818
+ ...current,
2819
+ busy: false,
2820
+ busyPausedAt: null,
2821
+ busySince: null,
2822
+ status: 'Ready',
2823
+ }));
2262
2824
  await remountTui();
2825
+ await flushQueuedMessage();
2263
2826
  return;
2264
2827
  }
2828
+ jobWait.turnStarted(jobFollowUp);
2265
2829
  latestUsageSummary = null;
2266
2830
  disarmExitConfirm();
2831
+ unacknowledged = new Map();
2267
2832
  const turnStartedAt = Date.now();
2268
2833
  const turnGeneration = ++activeTurnGeneration;
2269
2834
  const turnAbort = new AbortController();
2270
2835
  activeTurnAbort = turnAbort;
2271
2836
  lastTurnStartedAt = turnStartedAt;
2272
2837
  todosTouchedThisTurn = false;
2273
- clearTodos();
2838
+ if (!jobFollowUp)
2839
+ clearTodos();
2274
2840
  syncTodosState();
2275
2841
  const userEntry = {
2276
2842
  body: input,
@@ -2279,30 +2845,58 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2279
2845
  title: 'You',
2280
2846
  };
2281
2847
  pendingTurnEntries = [];
2282
- queueTurnEntry(userEntry);
2848
+ if (!jobFollowUp)
2849
+ queueTurnEntry(userEntry);
2850
+ resetThinkingPacer();
2851
+ activeTurnImageAttachments = imageAttachments;
2283
2852
  store.update((current) => ({
2284
2853
  ...current,
2285
2854
  activeTurnInput: input,
2286
2855
  activeTurnInputPreformatted: preformatted,
2856
+ analyzingImages: 0,
2857
+ generatingImage: false,
2287
2858
  busy: true,
2859
+ busyPausedAt: null,
2288
2860
  busySince: turnStartedAt,
2289
2861
  clockNow: turnStartedAt,
2862
+ recoveryStatus: '',
2290
2863
  status: 'Running turn...',
2864
+ usageNotice: null,
2291
2865
  thinkingTitle: '',
2292
2866
  thinkingNotes: [],
2293
2867
  transcriptScrollOffset: 0,
2294
2868
  tokenUsage: formatClientTokenUsage(0, latestUsageSummary),
2295
2869
  turnCounter: current.turnCounter + 1,
2870
+ turnMessages: [],
2296
2871
  workingTools: [],
2297
2872
  }));
2298
2873
  try {
2299
2874
  const result = await chat.sendServerUserMessage({
2300
2875
  config: authConfig,
2301
- projectIndex,
2302
2876
  session,
2303
2877
  input,
2878
+ jobFollowUp,
2304
2879
  imageAttachments,
2305
2880
  signal: turnAbort.signal,
2881
+ onTurnStart: (serverTurnId) => {
2882
+ if (turnGeneration !== activeTurnGeneration)
2883
+ return;
2884
+ activeServerTurnId = serverTurnId;
2885
+ },
2886
+ onInterjectionDelivered: (event) => {
2887
+ if (turnGeneration !== activeTurnGeneration)
2888
+ return;
2889
+ for (const messageId of event.messageIds ?? []) {
2890
+ const pending = unacknowledged.get(messageId);
2891
+ if (!pending)
2892
+ continue;
2893
+ unacknowledged.delete(messageId);
2894
+ upsertTurnMessage(pending.row, {
2895
+ state: 'delivered',
2896
+ note: undefined,
2897
+ });
2898
+ }
2899
+ },
2306
2900
  });
2307
2901
  if (turnGeneration !== activeTurnGeneration)
2308
2902
  return;
@@ -2311,6 +2905,7 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2311
2905
  if (!(await saveActiveSession()))
2312
2906
  return;
2313
2907
  syncShellStateFromSession();
2908
+ activeTurnImageAttachments = [];
2314
2909
  store.update((current) => ({
2315
2910
  ...current,
2316
2911
  activeTurnInput: '',
@@ -2319,6 +2914,7 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2319
2914
  commandLog: [],
2320
2915
  imageAttachments: [],
2321
2916
  status: result.waitingForApproval ? 'Awaiting approval' : 'Finishing response...',
2917
+ usageNotice: null,
2322
2918
  thinkingTitle: '',
2323
2919
  thinkingNotes: [],
2324
2920
  tokenUsage: formatClientTokenUsage(Date.now() - turnStartedAt, latestUsageSummary),
@@ -2346,10 +2942,14 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2346
2942
  store.update((current) => ({
2347
2943
  ...current,
2348
2944
  busy: false,
2945
+ busyPausedAt: null,
2349
2946
  busySince: null,
2947
+ recoveryStatus: '',
2350
2948
  status: result.waitingForApproval ? 'Awaiting approval' : 'Ready',
2351
2949
  tokenUsage: formatClientTokenUsage(Date.now() - turnStartedAt, latestUsageSummary),
2352
2950
  }));
2951
+ jobWait.turnEnded(result.waitingForJobs);
2952
+ recoverUnacknowledgedMessages();
2353
2953
  await flushQueuedMessage();
2354
2954
  }
2355
2955
  catch (error) {
@@ -2362,15 +2962,27 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2362
2962
  const cancelled = isTurnCancelledError(error);
2363
2963
  if (exitForAuthenticationError(error))
2364
2964
  return;
2965
+ dismissPendingApproval();
2966
+ dismissPendingSudoPassword();
2967
+ dismissPendingUserInput();
2968
+ const failedTurnAttachments = activeTurnImageAttachments;
2969
+ activeTurnImageAttachments = [];
2970
+ const quotaNotice = cancelled ? null : buildQuotaNotice(error);
2365
2971
  store.update((current) => ({
2366
2972
  ...current,
2367
2973
  activeTurnInput: '',
2368
2974
  activeTurnInputPreformatted: false,
2369
2975
  busy: false,
2976
+ busyPausedAt: null,
2370
2977
  busySince: null,
2371
2978
  commandLog: [],
2372
- imageAttachments: [],
2373
- status: cancelled ? 'Ready' : 'Turn failed',
2979
+ imageAttachments: failedTurnAttachments,
2980
+ recoveryStatus: '',
2981
+ status: cancelled
2982
+ ? 'Ready'
2983
+ : quotaNotice
2984
+ ? quotaNotice.title
2985
+ : 'Turn failed',
2374
2986
  thinkingTitle: '',
2375
2987
  thinkingNotes: [],
2376
2988
  tokenUsage: formatClientTokenUsage(Date.now() - turnStartedAt, latestUsageSummary),
@@ -2389,12 +3001,25 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2389
3001
  if (!(await saveActiveSession()))
2390
3002
  return;
2391
3003
  }
3004
+ else if (quotaNotice) {
3005
+ appendStaticEntries([
3006
+ ...turnEntries,
3007
+ {
3008
+ body: quotaNotice.body,
3009
+ kind: 'system',
3010
+ title: quotaNotice.title,
3011
+ },
3012
+ ]);
3013
+ }
2392
3014
  else {
2393
3015
  appendStaticEntries(turnEntries);
2394
3016
  appendError(error.message);
3017
+ appendStaticEntries(buildTurnFailureHintEntries(cancelled));
2395
3018
  }
2396
3019
  await remountTui();
2397
- if (!cancelled && turnGeneration === activeTurnGeneration) {
3020
+ const autoSubmits = !cancelled && isTurnOutcomeKnown(error);
3021
+ recoverUnacknowledgedMessages(autoSubmits);
3022
+ if (autoSubmits && turnGeneration === activeTurnGeneration) {
2398
3023
  await flushQueuedMessage();
2399
3024
  }
2400
3025
  }
@@ -2404,24 +3029,72 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2404
3029
  }
2405
3030
  if (turnGeneration === activeTurnGeneration) {
2406
3031
  lastTurnStartedAt = null;
3032
+ activeServerTurnId = null;
2407
3033
  }
3034
+ recoverUnacknowledgedMessages();
3035
+ await drainDeferredJobMutations();
3036
+ if (turnGeneration === activeTurnGeneration)
3037
+ scheduleJobFollowUp();
3038
+ }
3039
+ };
3040
+ session.onAccountUsage = (usage) => {
3041
+ const notice = usageNotice(usage);
3042
+ if (!notice)
3043
+ return;
3044
+ const entry = { ...notice, kind: 'system' };
3045
+ appendTurnAwareEntry(entry);
3046
+ if (store.getState().busy) {
3047
+ store.update((current) => ({ ...current, usageNotice: entry }));
2408
3048
  }
2409
3049
  };
3050
+ session.onImageAnalysis = (activeImageCount) => {
3051
+ store.update((current) => ({
3052
+ ...current,
3053
+ analyzingImages: Math.max(0, activeImageCount),
3054
+ generatingImage: activeImageCount > 0 ? false : current.generatingImage,
3055
+ }));
3056
+ };
3057
+ session.onRecovery = (status) => {
3058
+ if (status.phase === 'restored' || status.phase === 'continued') {
3059
+ store.update((current) => ({ ...current, recoveryStatus: '' }));
3060
+ appendTurnAwareEntry(status.phase === 'restored'
3061
+ ? { body: 'Continued the same turn.', kind: 'system', title: 'Connection restored' }
3062
+ : {
3063
+ body: 'Continued from the steps that had finished.',
3064
+ kind: 'system',
3065
+ title: 'Server restarted',
3066
+ });
3067
+ return;
3068
+ }
3069
+ store.update((current) => ({
3070
+ ...current,
3071
+ recoveryStatus: status.phase === 'reconnected' ? '' : formatTurnRecoveryStatus(status),
3072
+ }));
3073
+ };
3074
+ session.onImageGeneration = (active) => {
3075
+ store.update((current) => ({
3076
+ ...current,
3077
+ generatingImage: Boolean(active),
3078
+ analyzingImages: active ? 0 : current.analyzingImages,
3079
+ }));
3080
+ };
2410
3081
  session.onStatus = (message) => {
2411
3082
  const panel = thinkingPanelFromStatus(message);
2412
3083
  store.update((current) => ({
2413
3084
  ...current,
2414
3085
  status: message,
2415
- thinkingTitle: panel?.title ?? current.thinkingTitle,
2416
- thinkingNotes: panel?.notes ?? current.thinkingNotes,
2417
- tokenUsage: formatClientTokenUsage(current.busySince == null ? null : Date.now() - current.busySince, latestUsageSummary),
3086
+ tokenUsage: formatClientTokenUsage(busyElapsedMs(current, Date.now()), latestUsageSummary),
2418
3087
  }));
3088
+ queueThinkingUpdate({
3089
+ title: panel ? panel.title : liveStatusPanelTitle(message),
3090
+ notes: panel ? panel.notes : [],
3091
+ });
2419
3092
  };
2420
3093
  session.onContextLog = (message) => {
2421
3094
  store.update((current) => ({
2422
3095
  ...current,
2423
3096
  contextStatus: message,
2424
- tokenUsage: formatClientTokenUsage(current.busySince == null ? null : Date.now() - current.busySince, latestUsageSummary),
3097
+ tokenUsage: formatClientTokenUsage(busyElapsedMs(current, Date.now()), latestUsageSummary),
2425
3098
  }));
2426
3099
  };
2427
3100
  session.onToolEvent = (event) => {
@@ -2436,31 +3109,27 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2436
3109
  if (isFileChangeTool(event.call.name)) {
2437
3110
  const entry = buildFileChangeEntry(event);
2438
3111
  store.appendWorkingTool(entry);
2439
- appendTurnAwareEntry(entry);
3112
+ const result = event.result;
3113
+ if (result?.ok === true || result?.skipped === true)
3114
+ appendTurnAwareEntry(entry);
2440
3115
  return;
2441
3116
  }
2442
- store.appendWorkingTool(buildWorkingToolEntry(event));
2443
- };
2444
- const jobDetailLines = (jobId) => {
2445
- const buffered = getJobBufferedOutput(jobId);
2446
- if (!buffered)
2447
- return [];
2448
- const lines = buffered.output
2449
- .replace(/\r\n/g, '\n')
2450
- .replace(/\r/g, '\n')
2451
- .split('\n')
2452
- .filter((line) => line.trim().length > 0);
2453
- const visible = lines.slice(-20);
2454
- return buffered.droppedChars > 0
2455
- ? [
2456
- `... (${buffered.droppedChars} chars of older output dropped) ...`,
2457
- ...visible,
2458
- ]
2459
- : visible;
3117
+ store.appendWorkingTool(buildWorkingToolEntry(event, session.mcp?.label(event.call.name)));
2460
3118
  };
2461
3119
  const syncBackgroundJobsState = () => {
3120
+ const expandedId = store.getState().jobsPickerExpandedId;
2462
3121
  const jobsForDisplay = listBackgroundJobs().map((job) => {
2463
- const preview = getJobOutputPreview(job.id, 3);
3122
+ const expanded = job.id === expandedId;
3123
+ const preview = getJobOutputPreview(job.id, expanded ? 20 : 3);
3124
+ const dropped = preview?.droppedChars ?? 0;
3125
+ const detailLines = !expanded
3126
+ ? []
3127
+ : dropped > 0
3128
+ ? [
3129
+ `... (${dropped} chars of older output dropped) ...`,
3130
+ ...(preview?.tailLines ?? []),
3131
+ ]
3132
+ : (preview?.tailLines ?? []);
2464
3133
  return {
2465
3134
  id: job.id,
2466
3135
  command: job.command,
@@ -2469,8 +3138,8 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2469
3138
  startedAt: job.startedAt,
2470
3139
  endedAt: job.endedAt,
2471
3140
  firstOutputLine: preview?.firstLine ?? '',
2472
- tailLines: preview?.tailLines ?? [],
2473
- detailLines: jobDetailLines(job.id),
3141
+ tailLines: (preview?.tailLines ?? []).slice(-3),
3142
+ detailLines,
2474
3143
  };
2475
3144
  });
2476
3145
  store.update((current) => ({
@@ -2481,82 +3150,122 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2481
3150
  : null,
2482
3151
  }));
2483
3152
  };
3153
+ const scheduleJobFollowUp = () => {
3154
+ if (jobWait.waiting.length === 0)
3155
+ return;
3156
+ setTimeout(async () => {
3157
+ const state = store.getState();
3158
+ if (exiting || state.busy || state.modelPickerOpen || state.resumePickerOpen)
3159
+ return;
3160
+ const decision = jobWait.takeDecision();
3161
+ if (decision === 'wait')
3162
+ return;
3163
+ if (decision === 'stop') {
3164
+ appendStaticEntry({
3165
+ body: 'A background job finished. Send a message to continue.',
3166
+ kind: 'system',
3167
+ title: 'Background job',
3168
+ });
3169
+ return;
3170
+ }
3171
+ await drainDeferredJobMutations();
3172
+ if (exiting || store.getState().busy)
3173
+ return;
3174
+ void handleSubmit('', { jobFollowUp: true });
3175
+ }, 0);
3176
+ };
2484
3177
  setBackgroundJobUpdateHook((snapshot) => {
2485
3178
  syncBackgroundJobsState();
2486
3179
  if (snapshot.status !== 'running') {
2487
3180
  appendTurnAwareEntry(buildBackgroundJobNoticeEntry(snapshot));
3181
+ scheduleJobFollowUp();
2488
3182
  }
2489
3183
  });
2490
- projectIndex.onStatus = session.onStatus;
2491
- projectIndex.onContextLog = session.onContextLog;
2492
3184
  session.requestSudoPassword = async ({ command, prompt, signal }) => openSudoPasswordPrompt(command, prompt, signal);
2493
- session.confirmCommand = async (command) => {
3185
+ session.requestUserInput = async (request, signal) => openUserInputPrompt(request.questions, signal);
3186
+ session.requestPermission = async (request) => {
3187
+ const deny = { kind: 'deny' };
2494
3188
  if (exiting)
2495
- return false;
3189
+ return deny;
2496
3190
  if (sessionAutoYes)
2497
- return true;
2498
- const choice = await openApprovalPrompt('Approve command?', command);
2499
- if (choice === 'a') {
2500
- setAgentMode('auto-accept');
2501
- syncShellStateFromSession();
3191
+ return { kind: 'once' };
3192
+ const decision = await openApprovalPrompt(request, session.turnAbortSignal);
3193
+ if (decision.kind === 'always-bucket') {
2502
3194
  appendTurnAwareEntry({
2503
- body: 'Auto-approve enabled for the rest of this session.',
3195
+ body: `Allowed for the rest of this session: ${bucketActionLabel(request.bucket)}.`,
2504
3196
  kind: 'system',
2505
3197
  title: 'Approvals',
2506
3198
  });
2507
- return true;
2508
3199
  }
2509
- return choice === 'y';
2510
- };
2511
- session.confirmPatch = async (filePath, patch) => {
2512
- if (exiting)
2513
- return false;
2514
- if (sessionAutoYes)
2515
- return true;
2516
- const choice = await openApprovalPrompt('Approve patch?', 'Review changes before applying.', {
2517
- diff: patch,
2518
- filePath,
2519
- });
2520
- if (choice === 'a') {
2521
- setAgentMode('auto-accept');
2522
- syncShellStateFromSession();
3200
+ else if (decision.kind === 'always-prefix') {
2523
3201
  appendTurnAwareEntry({
2524
- body: 'Auto-approve enabled for the rest of this session.',
3202
+ body: `Allowed for the rest of this session: commands starting with \`${decision.prefix}\`.`,
2525
3203
  kind: 'system',
2526
3204
  title: 'Approvals',
2527
3205
  });
2528
- return true;
2529
3206
  }
2530
- return choice === 'y';
3207
+ else if (decision.kind === 'always-mcp-tool') {
3208
+ appendTurnAwareEntry({
3209
+ body: `Allowed for the rest of this session: ${request.mcpLabel ?? request.title}.`,
3210
+ kind: 'system',
3211
+ title: 'Approvals',
3212
+ });
3213
+ }
3214
+ else if (decision.kind === 'always-origin') {
3215
+ appendTurnAwareEntry({
3216
+ body: `Allowed for the rest of this session: browser actions on ${decision.origin}.`,
3217
+ kind: 'system',
3218
+ title: 'Approvals',
3219
+ });
3220
+ }
3221
+ return decision;
2531
3222
  };
2532
3223
  const shellInputHandlers = {
3224
+ getApprovalScrollLimit: () => {
3225
+ const contentWidth = frameContentWidth(terminalCols);
3226
+ return approvalScrollLimit(store.getState().approvalPrompt, contentWidth, terminalRows);
3227
+ },
3228
+ getComposerInputWidth: () => composerInputWidth(terminalCols, store.getState()),
2533
3229
  getTranscriptScrollLimit: () => {
2534
- const contentWidth = Math.max(20, Math.floor(terminalCols * 0.95) - 2);
3230
+ const contentWidth = frameContentWidth(terminalCols);
2535
3231
  const blocks = store.getState().transcript.map((entry) => renderTranscriptEntryLines(entry, contentWidth));
2536
3232
  return blocks.reduce((total, block, index) => total + block.length + (index > 0 ? 1 : 0), 0);
2537
3233
  },
3234
+ getUserInputViewport: () => {
3235
+ const nowMs = Date.now();
3236
+ const state = store.getState();
3237
+ return userInputViewportForFrame(state, terminalCols, terminalRows, spinnerFrame, busyElapsedSeconds(state, nowMs), nowMs);
3238
+ },
2538
3239
  onCancelTurn: cancelActiveTurn,
2539
3240
  onCycleAgentMode: cycleAgentMode,
3241
+ onAgentModeChangeBlocked: reportAgentModeLocked,
2540
3242
  onCtrlC: handleCtrlC,
2541
3243
  onLinkCopy: handleLinkCopy,
2542
3244
  onLinkOpen: handleLinkOpen,
2543
3245
  onLiveFrameShapeChange: scheduleLiveFrameRemount,
2544
3246
  onRequestExit: requestExit,
2545
3247
  onResolveApproval: handleInlineApprovalChoice,
3248
+ onResolveUserInput: handleInlineUserInput,
2546
3249
  onResumeSession: handleInlineResumeSelection,
2547
3250
  onSelectionCopy: handleAppSelectionCopy,
2548
3251
  onSelectModel: handleInlineModelSelection,
3252
+ onOpenJobsPicker: openJobsPicker,
3253
+ onToggleNotifications: toggleNotifications,
2549
3254
  onJobsPickerOutput: handleJobsPickerOutput,
2550
3255
  onJobsPickerKill: handleJobsPickerKill,
2551
3256
  onSudoPasswordInput: handleSudoPasswordInput,
2552
3257
  onSubmit: handleSubmit,
3258
+ onFireQueuedMessage: fireQueuedMessage,
2553
3259
  };
2554
3260
  const unsubscribe = store.subscribe(() => {
2555
3261
  renderCurrentFrame();
3262
+ if (jobWait.waiting.length > 0 && !store.getState().busy)
3263
+ scheduleJobFollowUp();
2556
3264
  });
2557
3265
  const spinnerTimer = setInterval(() => {
2558
3266
  spinnerFrame = (spinnerFrame + 1) % 6;
2559
3267
  if (store.getState().busy) {
3268
+ flushPendingThinking();
2560
3269
  renderCurrentFrame();
2561
3270
  }
2562
3271
  }, 120);
@@ -2587,6 +3296,13 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2587
3296
  return;
2588
3297
  }
2589
3298
  if (message.op === 'event') {
3299
+ if (message.kind === 'focus') {
3300
+ store.update((current) => current.terminalFocused === message.focused
3301
+ ? current
3302
+ : { ...current, terminalFocused: message.focused });
3303
+ renderCurrentFrame();
3304
+ return;
3305
+ }
2590
3306
  if (message.kind === 'resize') {
2591
3307
  terminalCols = message.cols;
2592
3308
  terminalRows = message.rows;
@@ -2612,6 +3328,7 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2612
3328
  killAllBackgroundJobs();
2613
3329
  setBackgroundJobSession(null);
2614
3330
  setScratchSession(null);
3331
+ setImageStoreSession(null);
2615
3332
  setTodoSession(null);
2616
3333
  setBackgroundJobUpdateHook(null);
2617
3334
  await bridge.close();
@@ -2621,4 +3338,5 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2621
3338
  });
2622
3339
  if (fatalError)
2623
3340
  throw fatalError;
3341
+ return { signedOut };
2624
3342
  }