@thegitai/cli 1.0.0-preview.8 → 1.0.0

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 (100) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +301 -15
  3. package/dist/bin/ai.js +142 -112
  4. package/dist/bin/browser-host.js +284 -0
  5. package/dist/src/agent-mode.js +33 -7
  6. package/dist/src/api/auth.js +8 -2
  7. package/dist/src/api/browser-login.js +147 -35
  8. package/dist/src/api/chat.js +703 -166
  9. package/dist/src/api/contracts.js +55 -1
  10. package/dist/src/api/default-host.js +1 -0
  11. package/dist/src/api/http.js +168 -8
  12. package/dist/src/api/models.js +47 -9
  13. package/dist/src/api/startup-handshake.js +36 -0
  14. package/dist/src/api/turn-recovery.js +189 -0
  15. package/dist/src/background-jobs.js +8 -2
  16. package/dist/src/browser/bridge.js +268 -0
  17. package/dist/src/browser/chrome-profiles.js +73 -0
  18. package/dist/src/browser/framing.js +42 -0
  19. package/dist/src/browser/native-host.js +219 -0
  20. package/dist/src/browser/protocol.js +46 -0
  21. package/dist/src/browser/session-bridge.js +130 -0
  22. package/dist/src/cli-args.js +19 -5
  23. package/dist/src/client-environment.js +2 -0
  24. package/dist/src/core/clipboard.js +8 -14
  25. package/dist/src/core/image-limits.js +56 -0
  26. package/dist/src/core/image-path-extractor.js +70 -3
  27. package/dist/src/core/session-image-store.js +246 -0
  28. package/dist/src/edit-journal.js +33 -2
  29. package/dist/src/executor.js +26 -4
  30. package/dist/src/help-text.js +152 -41
  31. package/dist/src/install-id.js +32 -0
  32. package/dist/src/job-follow-up.js +40 -0
  33. package/dist/src/mcp-client.js +335 -0
  34. package/dist/src/mcp-command.js +176 -0
  35. package/dist/src/mcp-config.js +123 -0
  36. package/dist/src/mcp-sdk.js +3 -0
  37. package/dist/src/mcp-types.js +26 -0
  38. package/dist/src/patcher.js +46 -4
  39. package/dist/src/permissions.js +301 -0
  40. package/dist/src/preferences.js +39 -0
  41. package/dist/src/project-key.js +11 -0
  42. package/dist/src/project-model-preferences.js +74 -0
  43. package/dist/src/quota-notice.js +62 -0
  44. package/dist/src/reasoning-effort.js +27 -0
  45. package/dist/src/session-safety.js +0 -12
  46. package/dist/src/session-store.js +123 -30
  47. package/dist/src/session.js +12 -4
  48. package/dist/src/signin.js +58 -0
  49. package/dist/src/skills/discovery.js +280 -0
  50. package/dist/src/skills/frontmatter.js +192 -0
  51. package/dist/src/skills/install.js +394 -0
  52. package/dist/src/skills/types.js +43 -0
  53. package/dist/src/skills-command.js +71 -0
  54. package/dist/src/tool-executor.js +41 -51
  55. package/dist/src/tools/browser.js +928 -0
  56. package/dist/src/tools/delete-file.js +21 -5
  57. package/dist/src/tools/index.js +34 -10
  58. package/dist/src/tools/patch-file.js +14 -29
  59. package/dist/src/tools/read-file.js +7 -1
  60. package/dist/src/tools/read-image-file.js +85 -0
  61. package/dist/src/tools/replace-document-text.js +28 -18
  62. package/dist/src/tools/restore-checkpoint.js +1 -2
  63. package/dist/src/tools/run-command.js +14 -71
  64. package/dist/src/tools/run-node-script.js +12 -81
  65. package/dist/src/tools/save-generated-image.js +120 -0
  66. package/dist/src/tools/shell-diagnostics.js +246 -72
  67. package/dist/src/tools/str-replace.js +14 -29
  68. package/dist/src/tools/undo-edit.js +2 -7
  69. package/dist/src/tools/use-skill.js +38 -0
  70. package/dist/src/tools/write-file.js +69 -14
  71. package/dist/src/ui/prompt-history-store.js +1 -1
  72. package/dist/src/ui/repl.js +1155 -301
  73. package/dist/src/ui/slash-commands.js +140 -0
  74. package/dist/src/ui/tui/attention.js +25 -0
  75. package/dist/src/ui/tui/bridge.js +38 -5
  76. package/dist/src/ui/tui/build-frame.js +903 -304
  77. package/dist/src/ui/tui/composer-layout.js +76 -0
  78. package/dist/src/ui/tui/desktop-notification.js +118 -0
  79. package/dist/src/ui/tui/markdown-render.js +21 -11
  80. package/dist/src/ui/tui/model-label.js +13 -0
  81. package/dist/src/ui/tui/shell-input.js +266 -61
  82. package/dist/src/ui/tui/shortcuts.js +61 -0
  83. package/dist/src/ui/tui/terminal-theme.js +28 -0
  84. package/dist/src/ui/tui/text.js +31 -6
  85. package/dist/src/ui/tui/user-input.js +593 -0
  86. package/dist/src/update-check.js +205 -0
  87. package/dist/src/usage-notice.js +52 -0
  88. package/dist/src/usage.js +25 -2
  89. package/dist/src/utils.js +13 -0
  90. package/dist/src/version.js +52 -2
  91. package/dist/vendor/mcp/LICENSES.txt +414 -0
  92. package/dist/vendor/mcp/client.cjs +82 -0
  93. package/package.json +22 -9
  94. package/dist/src/project-index.js +0 -233
  95. package/dist/src/tools/code-intel.js +0 -472
  96. package/dist/src/tools/find-symbol.js +0 -70
  97. package/dist/src/tools/hover-symbol.js +0 -95
  98. package/dist/src/tools/list-symbols.js +0 -55
  99. package/dist/src/tools/search-code.js +0 -37
  100. package/dist/src/tools/signature-help.js +0 -118
@@ -1,22 +1,42 @@
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, join as joinPath } 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, isSkillSlashCommand, setSkillSlashCommands, SLASH_COMMANDS, slashCommandMatchesToken, } from './slash-commands.js';
14
+ import { buildSkillsPickerItems, SKILLS_ADD_USAGE } from '../skills-command.js';
15
+ import { discoverSkills, personalSkillsRoot, projectSkillsRoot, skillCatalogue, } from '../skills/discovery.js';
16
+ import { installPreparedSkill, parseSkillSource, prepareSkillInstall, preparedSkillHasScripts, } from '../skills/install.js';
17
+ import { BUNDLED_SKILLS } from '../skills/types.js';
18
+ export { getInputCommandToken, getSlashCommandSuggestions, SLASH_COMMANDS, slashCommandMatchesToken, };
19
+ import { composerInputWidth, frameContentWidth } from './tui/composer-layout.js';
6
20
  import { agentModeLabel, nextAgentMode, } from '../agent-mode.js';
7
21
  import { chat, models } from '../api/index.js';
8
- import { isTurnCancelledError } from '../api/chat.js';
22
+ import { isTurnCancelledError, isTurnOutcomeKnown } from '../api/chat.js';
23
+ import { formatTurnRecoveryStatus } from '../api/turn-recovery.js';
24
+ import { createJobWaitTracker } from '../job-follow-up.js';
9
25
  import { getJobBufferedOutput, getJobOutputPreview, hasRunningBackgroundJobs, killAllBackgroundJobs, killBackgroundJob, listBackgroundJobs, setBackgroundJobSession, setBackgroundJobUpdateHook, } from '../background-jobs.js';
10
26
  import { clearTodos, listTodos, setTodoSession } from '../todo-list.js';
11
27
  import { setScratchSession } from '../scratch-dir.js';
28
+ import { setImageStoreSession } from '../core/session-image-store.js';
12
29
  import { cancelActiveCommand } from '../executor.js';
13
30
  import { isTurnFailureMarker } from '../turn-failure-marker.js';
14
- import { clearCliAuthConfig } from '../api/auth.js';
31
+ import { clearCliAuthConfig, logoutFromServer, } from '../api/auth.js';
15
32
  import { authenticationErrorMessage, isAuthenticationError, } from '../api/http.js';
33
+ import { buildRefusalNotice } from '../quota-notice.js';
34
+ import { createUsageNoticeTracker } from '../usage-notice.js';
35
+ import { createUserInputPromptState, formatUserInputTranscript, } from './tui/user-input.js';
16
36
  import { setCommandOutputHook, withTuiMode } from '../runtime-mode.js';
17
37
  import { collectBackgroundJobUiKillMutations, collectBackgroundJobUiOutputMutations, } from '../tool-executor.js';
18
38
  import { startNewConversation, } from '../session.js';
19
- import { applySessionSnapshot, listSessionMetadata, loadSessionSnapshot, saveSessionState, } from '../session-store.js';
39
+ import { applySessionSnapshot, listSessionMetadata, loadSessionSnapshot, saveSessionState, sessionHasUserMessage, } from '../session-store.js';
20
40
  import { truncate } from '../utils.js';
21
41
  import { writeClipboardText } from '../core/clipboard.js';
22
42
  import { openUrl } from '../core/open-url.js';
@@ -72,58 +92,46 @@ const TRANSCRIPT_DIFF_PREVIEW_LINES = 24;
72
92
  const WORKING_TOOL_PREVIEW_ITEMS = 4;
73
93
  const THINKING_NOTE_PREVIEW_ROWS = 3;
74
94
  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: '/new',
120
- description: 'start a new conversation; this session remains saved',
121
- },
122
- {
123
- command: '/exit',
124
- description: 'Quit the current session',
125
- },
126
- ];
95
+ export const REPORT_ISSUE_URL = 'https://thegit.ai/report';
96
+ export function buildReportTranscriptEntries(openedUrl) {
97
+ return openedUrl
98
+ ? [
99
+ {
100
+ body: `Opening the private bug report form in your browser. If nothing opened, visit:\n\n${REPORT_ISSUE_URL}\n`,
101
+ kind: 'system',
102
+ title: 'Report',
103
+ },
104
+ ]
105
+ : [
106
+ {
107
+ body: `Could not open a browser. Report the bug manually at:\n\n${REPORT_ISSUE_URL}\n`,
108
+ kind: 'error',
109
+ title: 'Report',
110
+ },
111
+ ];
112
+ }
113
+ export function buildTurnFailureHintEntries(cancelled) {
114
+ if (cancelled)
115
+ return [];
116
+ return [
117
+ {
118
+ body: 'Something went wrong? Use /report to submit the issue.',
119
+ kind: 'error',
120
+ title: 'Report',
121
+ },
122
+ ];
123
+ }
124
+ export function composerAttachmentsAfterCancel(queuedAttachments, inFlightAttachments) {
125
+ const seen = new Set();
126
+ const kept = [];
127
+ for (const attachment of [...queuedAttachments, ...inFlightAttachments]) {
128
+ if (seen.has(attachment.index))
129
+ continue;
130
+ seen.add(attachment.index);
131
+ kept.push(attachment);
132
+ }
133
+ return kept;
134
+ }
127
135
  function getShellWidth(columns) {
128
136
  const safeColumns = Math.max(columns, 20);
129
137
  const targetWidth = Math.floor(safeColumns * TUI_WIDTH_RATIO);
@@ -492,11 +500,43 @@ function buildWriteFileDiff(content) {
492
500
  return '';
493
501
  return `@@ -0,0 +1,${lines.length} @@\n${lines.map((line) => `+${line}`).join('\n')}`;
494
502
  }
503
+ const MAX_DELETE_PREVIEW_LINES = 400;
495
504
  function buildDeleteFileDiff(content) {
496
505
  const lines = splitDiffLines(String(content ?? ''));
497
- if (lines.length === 0)
506
+ if (lines.length === 0) {
507
+ return { removed: 0, text: '' };
508
+ }
509
+ const shown = lines.slice(0, MAX_DELETE_PREVIEW_LINES);
510
+ const rows = [
511
+ `@@ -1,${lines.length} +0,0 @@`,
512
+ ...shown.map((line) => `-${line}`),
513
+ ];
514
+ const omitted = lines.length - shown.length;
515
+ if (omitted > 0) {
516
+ rows.push(`@@ ${omitted} more removed line(s) not shown @@`);
517
+ }
518
+ return { removed: lines.length, text: rows.join('\n') };
519
+ }
520
+ function deletedFileSummary(result) {
521
+ const bytes = typeof result?.bytes === 'number' ? result.bytes : null;
522
+ if (bytes === null) {
498
523
  return '';
499
- return `@@ -1,${lines.length} +0,0 @@\n${lines.map((line) => `-${line}`).join('\n')}`;
524
+ }
525
+ const reason = result?.contentOmitted === 'binary' ? ', binary' : '';
526
+ return ` (${formatFileSize(bytes)}${reason})`;
527
+ }
528
+ function formatFileSize(bytes) {
529
+ if (bytes < 1024) {
530
+ return `${bytes} B`;
531
+ }
532
+ const units = ['KiB', 'MiB', 'GiB', 'TiB'];
533
+ let value = bytes / 1024;
534
+ let unit = 0;
535
+ while (value >= 1024 && unit < units.length - 1) {
536
+ value /= 1024;
537
+ unit += 1;
538
+ }
539
+ return `${value >= 10 ? Math.round(value) : value.toFixed(1)} ${units[unit]}`;
500
540
  }
501
541
  function isFileChangeTool(name) {
502
542
  return (name === 'patch_file' ||
@@ -512,13 +552,7 @@ function getToolFilePath(call, result) {
512
552
  '').trim();
513
553
  }
514
554
  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';
555
+ return result?.skipped ? 'Skipped' : 'OK';
522
556
  }
523
557
  function formatRunCommandResultState(result) {
524
558
  if (result?.timedOut)
@@ -556,12 +590,15 @@ function buildFileChangeEntry(event) {
556
590
  : call.name === 'undo_edit'
557
591
  ? 'Undo'
558
592
  : '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
- };
593
+ if (skipped) {
594
+ return {
595
+ body: error || `${call.name} ${filePath}`,
596
+ filePath,
597
+ kind: 'system',
598
+ title: `${verb} skipped: ${filePath}`,
599
+ };
600
+ }
601
+ return { body: '', filePath, kind: 'system', title: `${verb}: ${filePath}` };
565
602
  }
566
603
  if (result?.scratch === true) {
567
604
  const scratchName = truncate(filePath.split(/[\\/]/).filter(Boolean).at(-1) ?? filePath, 72);
@@ -622,9 +659,11 @@ function buildFileChangeEntry(event) {
622
659
  };
623
660
  }
624
661
  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})` : '';
662
+ const diff = buildDeleteFileDiff(content);
663
+ const preview = diff.text ? parseDiffPreview(diff.text) : undefined;
664
+ const summary = preview
665
+ ? ` (+0 -${diff.removed})`
666
+ : deletedFileSummary(result);
628
667
  return {
629
668
  body: '',
630
669
  diffPreview: preview,
@@ -674,24 +713,27 @@ function buildFileChangeEntry(event) {
674
713
  title: `Edited ${filePath}${summary}`,
675
714
  };
676
715
  }
677
- function buildWorkingToolEntry(event) {
716
+ export function buildWorkingToolEntry(event, label = event.call.name) {
678
717
  const { call, result } = event;
679
- const error = typeof result?.error === 'string' && result.error.trim()
718
+ const failed = result?.ok !== true && result?.skipped !== true;
719
+ const kind = result?.ok === true ? 'tool' : 'system';
720
+ const state = (text) => (failed ? '' : text);
721
+ const error = !failed && typeof result?.error === 'string' && result.error.trim()
680
722
  ? `\n${truncate(result.error.trim(), 180)}`
681
723
  : '';
682
724
  if (call.name === 'run_command') {
683
725
  const command = String(call.args?.command ?? result?.command ?? '').trim();
684
726
  if (result?.backgrounded === true && result?.jobId) {
685
727
  return {
686
- body: `$ ${truncate(command, 180)}\nBackground job ${String(result.jobId)} started.${error}`,
687
- kind: result?.ok === true ? 'tool' : 'error',
728
+ body: `$ ${truncate(command, 180)}${state(`\nBackground job ${String(result.jobId)} started.`)}${error}`,
729
+ kind,
688
730
  preformatted: true,
689
731
  title: 'Shell',
690
732
  };
691
733
  }
692
734
  return {
693
- body: `$ ${truncate(command, 180)}\n${formatRunCommandResultState(result)}${error}`,
694
- kind: result?.ok === true ? 'tool' : 'error',
735
+ body: `$ ${truncate(command, 180)}${state(`\n${formatRunCommandResultState(result)}`)}${error}`,
736
+ kind,
695
737
  title: 'Shell',
696
738
  };
697
739
  }
@@ -703,15 +745,23 @@ function buildWorkingToolEntry(event) {
703
745
  ? `${status}${exitCode != null ? ` (code ${exitCode})` : ''}`
704
746
  : formatToolResultState(result);
705
747
  return {
706
- body: `${jobId || '(unknown job)'} · ${stateText}${error}`,
707
- kind: result?.ok === true ? 'tool' : 'error',
748
+ body: `${jobId || '(unknown job)'}${state(` · ${stateText}`)}${error}`,
749
+ kind,
708
750
  title: call.name === 'shell_job_kill' ? 'Kill job' : 'Job output',
709
751
  };
710
752
  }
753
+ if (call.name === 'use_skill') {
754
+ const name = String(result?.name ?? call.args?.name ?? '').trim().replace(/^\//, '');
755
+ return {
756
+ body: `/${name || 'skill'}${state(result?.alreadyLoaded === true ? ' · already loaded' : ' · loaded')}`,
757
+ kind,
758
+ title: 'Skill',
759
+ };
760
+ }
711
761
  if (call.name === 'run_node_script') {
712
762
  return {
713
- body: `node --input-type=module <script via stdin>\n${formatRunCommandResultState(result)}${error}`,
714
- kind: result?.ok === true ? 'tool' : 'error',
763
+ body: `node --input-type=module <script via stdin>${state(`\n${formatRunCommandResultState(result)}`)}${error}`,
764
+ kind,
715
765
  title: 'Node',
716
766
  };
717
767
  }
@@ -720,8 +770,8 @@ function buildWorkingToolEntry(event) {
720
770
  }
721
771
  const args = formatToolArgs(call, result);
722
772
  return {
723
- body: `${call.name}${args ? ` ${args}` : ''} -> ${formatToolResultState(result)}${error}`,
724
- kind: result?.ok === true ? 'tool' : 'error',
773
+ body: `${label}${args ? ` ${args}` : ''}${state(` -> ${formatToolResultState(result)}`)}${error}`,
774
+ kind,
725
775
  title: 'Tool',
726
776
  };
727
777
  }
@@ -787,10 +837,18 @@ function displayUserTextFromHistoryEntry(entry) {
787
837
  export function buildTranscriptFromSessionHistory(history) {
788
838
  const entries = [];
789
839
  const pendingCalls = new Map();
840
+ const pendingUserInputRequests = new Map();
790
841
  for (const entry of history) {
791
842
  if (!entry?.parts?.length)
792
843
  continue;
793
844
  for (const part of entry.parts) {
845
+ const userInputRequest = part?.userInputRequest;
846
+ if (userInputRequest && typeof userInputRequest === 'object') {
847
+ const requestId = String(userInputRequest.requestId ?? '').trim();
848
+ if (requestId && Array.isArray(userInputRequest.questions)) {
849
+ pendingUserInputRequests.set(requestId, userInputRequest.questions);
850
+ }
851
+ }
794
852
  const call = part?.functionCall;
795
853
  if (!call || typeof call !== 'object')
796
854
  continue;
@@ -800,6 +858,21 @@ export function buildTranscriptFromSessionHistory(history) {
800
858
  pendingCalls.set(callId, call);
801
859
  }
802
860
  for (const part of entry.parts) {
861
+ const userInputResult = part?.userInputResult;
862
+ if (userInputResult && typeof userInputResult === 'object') {
863
+ const requestId = String(userInputResult.requestId ?? '').trim();
864
+ const questions = pendingUserInputRequests.get(requestId);
865
+ const result = userInputResult.result;
866
+ if (questions &&
867
+ (result?.status === 'submitted' || result?.status === 'cancelled')) {
868
+ pendingUserInputRequests.delete(requestId);
869
+ entries.push({
870
+ body: formatUserInputTranscript(questions, result),
871
+ kind: result.status === 'submitted' ? 'user' : 'system',
872
+ title: result.status === 'submitted' ? 'Your answers' : 'Question',
873
+ });
874
+ }
875
+ }
803
876
  const functionResponse = part?.functionResponse;
804
877
  if (!functionResponse || typeof functionResponse !== 'object')
805
878
  continue;
@@ -816,10 +889,10 @@ export function buildTranscriptFromSessionHistory(history) {
816
889
  }
817
890
  if (!call || !isFileChangeTool(call.name))
818
891
  continue;
819
- entries.push(buildFileChangeEntry({
820
- call,
821
- result: functionResponse.response ?? {},
822
- }));
892
+ const result = (functionResponse.response ?? {});
893
+ if (result.ok !== true && result.skipped !== true)
894
+ continue;
895
+ entries.push(buildFileChangeEntry({ call, result }));
823
896
  }
824
897
  if (entry.role === 'user' && entry.kind === 'turnStart') {
825
898
  const text = displayUserTextFromHistoryEntry(entry);
@@ -828,6 +901,13 @@ export function buildTranscriptFromSessionHistory(history) {
828
901
  }
829
902
  continue;
830
903
  }
904
+ if (entry.role === 'user' && entry.kind === 'userInterjection') {
905
+ const text = String(entry.userInput ?? '').trim();
906
+ if (text) {
907
+ entries.push({ body: text, kind: 'user', title: 'You · sent mid-turn' });
908
+ }
909
+ continue;
910
+ }
831
911
  const text = textFromHistoryEntry(entry);
832
912
  if ((entry.role === 'model' || entry.role === 'assistant') && text) {
833
913
  if (isTurnFailureMarker(text)) {
@@ -856,7 +936,24 @@ function createSessionTranscript(session) {
856
936
  const transcript = buildTranscriptFromSessionHistory(session.history);
857
937
  return transcript.length ? transcript : createInitialTranscript();
858
938
  }
859
- function createShellStore(initialState) {
939
+ export function isJobsPickerCommand(input) {
940
+ return String(input ?? '').trim() === '/jobs';
941
+ }
942
+ export function statusBehindJobsPicker(state) {
943
+ return state.jobsPickerOpen
944
+ ? (state.jobsPickerReturnStatus ?? 'Ready')
945
+ : state.status;
946
+ }
947
+ export function closedJobsPickerFields(state) {
948
+ if (!state.jobsPickerOpen)
949
+ return {};
950
+ return {
951
+ jobsPickerExpandedId: null,
952
+ jobsPickerOpen: false,
953
+ jobsPickerReturnStatus: null,
954
+ };
955
+ }
956
+ export function createShellStore(initialState) {
860
957
  let state = initialState;
861
958
  let nextEntryId = 1;
862
959
  const listeners = new Set();
@@ -864,6 +961,10 @@ function createShellStore(initialState) {
864
961
  for (const listener of listeners)
865
962
  listener();
866
963
  };
964
+ const setState = (nextState) => {
965
+ state = nextState.busy ? nextState : { ...nextState, usageNotice: null };
966
+ notify();
967
+ };
867
968
  return {
868
969
  getState: () => state,
869
970
  subscribe: (listener) => {
@@ -872,14 +973,8 @@ function createShellStore(initialState) {
872
973
  listeners.delete(listener);
873
974
  };
874
975
  },
875
- setState: (nextState) => {
876
- state = nextState;
877
- notify();
878
- },
879
- update: (updater) => {
880
- state = updater(state);
881
- notify();
882
- },
976
+ setState,
977
+ update: (updater) => setState(updater(state)),
883
978
  appendEntry: (entry) => {
884
979
  const id = nextEntryId++;
885
980
  state = {
@@ -958,31 +1053,43 @@ function shallowArrayEqual(a, b) {
958
1053
  }
959
1054
  return true;
960
1055
  }
961
- function createInitialShellState(session, serverModels, debugUi) {
1056
+ function createInitialShellState(session, serverModels, debugUi, serverUrl) {
962
1057
  return {
963
1058
  activeTurnInput: '',
964
1059
  activeTurnInputPreformatted: false,
965
1060
  agentMode: session.agentMode,
966
- approvalCursor: getDefaultApprovalCursor(),
1061
+ analyzingImages: 0,
1062
+ generatingImage: false,
1063
+ approvalCursor: 0,
967
1064
  approvalPrompt: null,
1065
+ approvalScrollOffset: 0,
968
1066
  autoYes: session.autoYes,
969
1067
  backgroundJobs: [],
970
1068
  busy: false,
1069
+ busyPausedAt: null,
971
1070
  busySince: null,
972
1071
  clockNow: Date.now(),
973
1072
  commandCursor: 0,
974
1073
  commandLog: [],
975
1074
  contextStatus: 'Idle',
976
1075
  currentModelId: session.modelId,
1076
+ reasoningEffort: projectModelEffort(readProjectModelEfforts(session.rootDir, serverUrl, session.env), session.modelId),
977
1077
  cursor: 0,
978
1078
  exiting: false,
979
1079
  input: '',
980
1080
  maxToolSteps: session.maxToolSteps,
1081
+ notificationsEnabled: readPreferences(session.env).notifications,
1082
+ terminalFocused: INITIAL_TERMINAL_FOCUS,
981
1083
  jobsPickerExpandedId: null,
982
1084
  jobsPickerIndex: 0,
983
1085
  jobsPickerOpen: false,
984
1086
  modelPickerIndex: getDefaultModelPickerIndex(session.modelId, serverModels.models),
985
1087
  modelPickerOpen: false,
1088
+ shortcutsOpen: false,
1089
+ skillsPickerIndex: 0,
1090
+ skillsPickerItems: [],
1091
+ skillsPickerOpen: false,
1092
+ transientStatus: null,
986
1093
  projectRoot: session.rootDir,
987
1094
  sessionId: session.sessionId,
988
1095
  showSessionId: debugUi.showSessionId,
@@ -995,6 +1102,7 @@ function createInitialShellState(session, serverModels, debugUi) {
995
1102
  resumePickerSessions: [],
996
1103
  transcriptScrollOffset: 0,
997
1104
  queuedMessage: null,
1105
+ turnMessages: [],
998
1106
  serverModels: serverModels.models,
999
1107
  sudoPrompt: null,
1000
1108
  status: 'Ready',
@@ -1005,6 +1113,7 @@ function createInitialShellState(session, serverModels, debugUi) {
1005
1113
  tokenUsage: formatClientTokenUsage(null),
1006
1114
  transcript: [],
1007
1115
  turnCounter: Math.max(0, session.history.filter((entry) => entry.role === 'user').length),
1116
+ userInputPrompt: null,
1008
1117
  pastedChunks: [],
1009
1118
  imageAttachments: [],
1010
1119
  workingTools: [],
@@ -1021,7 +1130,6 @@ export function formatClientTokenUsage(_responseTimeMs, usageSummary = null) {
1021
1130
  const reasoningTokens = usageSummary?.reasoningTokens ?? 0;
1022
1131
  const cacheTokens = usageSummary?.cacheTokens ?? 0;
1023
1132
  const cacheWriteTokens = usageSummary?.cacheWriteTokens ?? 0;
1024
- const indexTokens = usageSummary?.indexTokens ?? 0;
1025
1133
  return [
1026
1134
  'Session tokens',
1027
1135
  `in ${formatTokenCount(inputTokens)}`,
@@ -1029,7 +1137,6 @@ export function formatClientTokenUsage(_responseTimeMs, usageSummary = null) {
1029
1137
  ...(reasoningTokens > 0 ? [`think ${formatTokenCount(reasoningTokens)}`] : []),
1030
1138
  `cache ${formatTokenCount(cacheTokens)}`,
1031
1139
  `write ${formatTokenCount(cacheWriteTokens)}`,
1032
- `index ${formatTokenCount(indexTokens)}`,
1033
1140
  ].join(' • ');
1034
1141
  }
1035
1142
  export function formatPromptDirectoryLabel(projectRoot, homeDir = process.env.HOME ?? '') {
@@ -1072,6 +1179,24 @@ function splitThinkingLines(text) {
1072
1179
  .map((part) => part.trim())
1073
1180
  .filter(Boolean));
1074
1181
  }
1182
+ const LIVE_STATUS_PANEL_MAX_CHARS = 72;
1183
+ const TOOL_PROGRESS_STATUS_PATTERN = /^(?:Tool:\s|Running\s\S+(?:\slocally)?\.\.\.$)/i;
1184
+ export function isToolProgressStatus(status) {
1185
+ return TOOL_PROGRESS_STATUS_PATTERN.test(String(status ?? '').trim());
1186
+ }
1187
+ function holdOrPickFallback(currentTitle) {
1188
+ return THINKING_FALLBACK_PHRASES.includes(currentTitle.trim())
1189
+ ? currentTitle
1190
+ : pickThinkingFallbackPhrase();
1191
+ }
1192
+ function liveStatusPanelTitle(status) {
1193
+ const text = String(status ?? '').trim();
1194
+ if (!text || text.includes('\n'))
1195
+ return '';
1196
+ if (isToolProgressStatus(text))
1197
+ return '';
1198
+ return text.length <= LIVE_STATUS_PANEL_MAX_CHARS ? text : '';
1199
+ }
1075
1200
  function thinkingPanelFromStatus(status) {
1076
1201
  const rawText = thinkingNoteFromStatus(status);
1077
1202
  if (!rawText)
@@ -1095,7 +1220,7 @@ function thinkingPanelFromStatus(status) {
1095
1220
  const bodyLines = rawLines.length > 1 && rawLines[0].length <= 72 ? rawLines.slice(1) : rawLines;
1096
1221
  return {
1097
1222
  title,
1098
- notes: splitThinkingLines(bodyLines.join('\n')).slice(-3),
1223
+ notes: splitThinkingLines(bodyLines.join('\n')).slice(0, 3),
1099
1224
  };
1100
1225
  }
1101
1226
  export const EXIT_CTRL_C_CONFIRM_MESSAGE = 'Press Ctrl+C again to quit.';
@@ -1103,16 +1228,6 @@ export const EXIT_CTRL_C_CONFIRM_MS = 3000;
1103
1228
  export function isExitConfirmActive(exitConfirmUntil, now = Date.now()) {
1104
1229
  return exitConfirmUntil != null && now < exitConfirmUntil;
1105
1230
  }
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
1231
  function shouldShowCommandPalette(state) {
1117
1232
  const trimmed = String(state.input ?? '').trim();
1118
1233
  return (!state.busy &&
@@ -1120,8 +1235,9 @@ function shouldShowCommandPalette(state) {
1120
1235
  !state.modelPickerOpen &&
1121
1236
  !state.resumePickerOpen &&
1122
1237
  trimmed.startsWith('/') &&
1123
- !trimmed.includes(' ') &&
1124
- getInputCommandToken(trimmed) !== '');
1238
+ !String(state.input ?? '').includes(' ') &&
1239
+ getInputCommandToken(trimmed) !== '' &&
1240
+ getSlashCommandSuggestions(trimmed).length > 0);
1125
1241
  }
1126
1242
  export function shouldRemountLiveFrameForComposerInputChange(current, nextInput) {
1127
1243
  const currentShowsCommands = shouldShowCommandPalette(current);
@@ -1133,20 +1249,19 @@ export function shouldRemountLiveFrameForComposerInputChange(current, nextInput)
1133
1249
  }
1134
1250
  export function applySlashCommandSuggestion(currentInput, suggestion) {
1135
1251
  const token = getInputCommandToken(currentInput);
1252
+ const command = isSkillSlashCommand(suggestion) ? `${suggestion.command} ` : suggestion.command;
1136
1253
  if (!token) {
1137
- return { cursor: suggestion.command.length, input: suggestion.command };
1254
+ return { cursor: command.length, input: command };
1138
1255
  }
1139
1256
  const tokenStart = currentInput.indexOf(token);
1140
1257
  const before = currentInput.slice(0, tokenStart);
1141
1258
  const after = currentInput.slice(tokenStart + token.length);
1259
+ const inserted = after.startsWith(' ') ? suggestion.command : command;
1142
1260
  return {
1143
- cursor: before.length + suggestion.command.length,
1144
- input: `${before}${suggestion.command}${after}`,
1261
+ cursor: before.length + inserted.length,
1262
+ input: `${before}${inserted}${after}`,
1145
1263
  };
1146
1264
  }
1147
- export function isExactSlashCommandToken(token) {
1148
- return SLASH_COMMANDS.some((command) => command.command === token);
1149
- }
1150
1265
  export function insertAtCursor(state, text) {
1151
1266
  const before = state.input.slice(0, state.cursor);
1152
1267
  const after = state.input.slice(state.cursor);
@@ -1225,38 +1340,84 @@ export function navigatePromptHistory(state, direction) {
1225
1340
  promptHistoryCursor: nextCursor,
1226
1341
  };
1227
1342
  }
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;
1343
+ export function getDefaultApprovalCursor(optionCount) {
1344
+ return Math.max(0, optionCount - 1);
1345
+ }
1346
+ export function getNextApprovalCursor(currentIndex, direction, optionCount) {
1347
+ if (optionCount <= 0)
1348
+ return 0;
1349
+ return (currentIndex + direction + optionCount) % optionCount;
1350
+ }
1351
+ export function pauseBusyClock(state, nowMs) {
1352
+ if (state.busySince === null || state.busyPausedAt !== null)
1353
+ return state;
1354
+ return { ...state, busyPausedAt: nowMs };
1355
+ }
1356
+ export function resumeBusyClock(state, nowMs) {
1357
+ if (state.busyPausedAt === null)
1358
+ return state;
1359
+ return {
1360
+ ...state,
1361
+ busyPausedAt: null,
1362
+ busySince: state.busySince === null
1363
+ ? null
1364
+ : state.busySince + Math.max(0, nowMs - state.busyPausedAt),
1365
+ };
1366
+ }
1367
+ export function busyElapsedMs(state, nowMs) {
1368
+ if (state.busySince === null)
1369
+ return null;
1370
+ return Math.max(0, (state.busyPausedAt ?? nowMs) - state.busySince);
1371
+ }
1372
+ export function busyElapsedSeconds(state, nowMs) {
1373
+ return Math.floor((busyElapsedMs(state, nowMs) ?? 0) / 1000);
1248
1374
  }
1249
1375
  export function buildModelPickerOptions(currentModelId, serverModels) {
1250
- return serverModels.map((model) => ({
1376
+ const listed = serverModels.filter((model) => model.locked !== 'auto-only');
1377
+ return [
1378
+ ...listed.filter((model) => model.auto),
1379
+ ...listed.filter((model) => !model.auto),
1380
+ ].map((model) => ({
1251
1381
  id: model.id,
1252
- label: model.label,
1382
+ label: model.auto ? autoOptionLabel(model.label) : model.label,
1253
1383
  publicId: model.id,
1254
1384
  costRating: model.costRating,
1255
1385
  current: model.id === currentModelId,
1256
- disabled: false,
1257
- note: model.description,
1386
+ disabled: Boolean(model.locked),
1387
+ group: model.auto ? 'auto' : 'models',
1388
+ note: model.locked ? MODEL_LOCK_NOTES[model.locked] : model.description,
1258
1389
  }));
1259
1390
  }
1391
+ export function pausedModelCount(serverModels) {
1392
+ return serverModels.filter((model) => model.locked === 'auto-only').length;
1393
+ }
1394
+ export async function modelsForSwitch(requestedModelId, cached, refresh) {
1395
+ try {
1396
+ return await refresh();
1397
+ }
1398
+ catch (error) {
1399
+ if (cached.models.some((model) => model.id === requestedModelId))
1400
+ return cached;
1401
+ throw error;
1402
+ }
1403
+ }
1404
+ export const PAUSED_MODELS_NOTE = 'Named models return when your plan renews.';
1405
+ function autoOptionLabel(label) {
1406
+ return /^Auto \((.+)\)$/.exec(label)?.[1] ?? label;
1407
+ }
1408
+ const MODEL_LOCK_NOTES = {
1409
+ plan: 'Needs a Plus or Pro plan',
1410
+ 'auto-only': 'Auto options only until your plan renews',
1411
+ };
1412
+ export function modelLockMessage(model) {
1413
+ if (model.locked === 'auto-only') {
1414
+ return `Only Auto options run until your plan renews. Pick one of them instead of ${pickerLabel(model.label)}.`;
1415
+ }
1416
+ return `${pickerLabel(model.label)} needs a Plus or Pro plan.`;
1417
+ }
1418
+ function pickerLabel(label) {
1419
+ return label.replace(/\s*\([^)]*\)\s*$/, '');
1420
+ }
1260
1421
  function getDefaultModelPickerIndex(currentModelId, serverModels) {
1261
1422
  const options = buildModelPickerOptions(currentModelId, serverModels);
1262
1423
  const currentIndex = options.findIndex((option) => option.id === currentModelId);
@@ -1282,10 +1443,12 @@ function appendCommandLog(state, text) {
1282
1443
  };
1283
1444
  }
1284
1445
  async function saveSessionBoth({ serverSessionClient, session, }) {
1446
+ if (!sessionHasUserMessage(session))
1447
+ return;
1285
1448
  saveSessionState(session);
1286
1449
  await serverSessionClient.save(session);
1287
1450
  }
1288
- export async function runClientInteractive({ appendPromptHistory, authConfig, debugUi, projectIndex, serverModels, serverSessionClient, session, usageText, initialPrompt, }) {
1451
+ export async function runClientInteractive({ appendPromptHistory, authConfig, debugUi, plan, serverModels, serverSessionClient, session, usageText, initialPrompt, }) {
1289
1452
  if (process.stdin.isTTY !== true) {
1290
1453
  throw new Error('stdin is not a terminal');
1291
1454
  }
@@ -1293,17 +1456,23 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1293
1456
  throw new Error('stdout is not a terminal');
1294
1457
  }
1295
1458
  let fatalError = null;
1459
+ let signedOut = false;
1296
1460
  await withTuiMode(async () => {
1297
1461
  setBackgroundJobSession(session.sessionId);
1298
1462
  setScratchSession(session.sessionId);
1463
+ setImageStoreSession(session.sessionId);
1299
1464
  setTodoSession(session.sessionId);
1300
- const store = createShellStore(createInitialShellState(session, serverModels, debugUi));
1465
+ const store = createShellStore({
1466
+ ...createInitialShellState(session, serverModels, debugUi, authConfig.serverUrl),
1467
+ plan,
1468
+ });
1301
1469
  store.replaceTranscript(createSessionTranscript(session));
1302
1470
  let currentServerModels = serverModels;
1303
1471
  let sessionAutoYes = session.autoYes;
1304
1472
  let resolveDone = null;
1305
- let resolveApprovalChoice = null;
1473
+ let resolvePermissionDecision = null;
1306
1474
  let resolveSudoPassword = null;
1475
+ let pendingUserInput = null;
1307
1476
  let cleanupSudoPasswordPrompt = null;
1308
1477
  let sudoPasswordBuffer = '';
1309
1478
  const bridge = createRatatuiBridge();
@@ -1318,8 +1487,13 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1318
1487
  let tuiReady = false;
1319
1488
  let lastTurnStartedAt = null;
1320
1489
  let latestUsageSummary = null;
1490
+ const usageNotice = createUsageNoticeTracker();
1321
1491
  let pendingTurnEntries = [];
1322
1492
  let activeTurnAbort = null;
1493
+ let activeTurnImageAttachments = [];
1494
+ let activeServerTurnId = null;
1495
+ let unacknowledged = new Map();
1496
+ const blockedRows = new WeakMap();
1323
1497
  let newConversationInFlight = false;
1324
1498
  let todosTouchedThisTurn = false;
1325
1499
  const syncTodosState = () => {
@@ -1329,6 +1503,36 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1329
1503
  let exitCtrlCArmed = false;
1330
1504
  let exitCtrlCTimer = null;
1331
1505
  let transientStatusTimer = null;
1506
+ const THINKING_MIN_DWELL_MS = 3_000;
1507
+ let thinkingAppliedAt = 0;
1508
+ let pendingThinking = null;
1509
+ const applyThinking = (next) => {
1510
+ thinkingAppliedAt = Date.now();
1511
+ pendingThinking = null;
1512
+ store.update((current) => ({
1513
+ ...current,
1514
+ thinkingTitle: next.title || holdOrPickFallback(current.thinkingTitle),
1515
+ thinkingNotes: next.notes,
1516
+ }));
1517
+ };
1518
+ const queueThinkingUpdate = (next) => {
1519
+ if (Date.now() - thinkingAppliedAt >= THINKING_MIN_DWELL_MS) {
1520
+ applyThinking(next);
1521
+ return;
1522
+ }
1523
+ pendingThinking = next;
1524
+ };
1525
+ const flushPendingThinking = () => {
1526
+ if (!pendingThinking)
1527
+ return;
1528
+ if (Date.now() - thinkingAppliedAt < THINKING_MIN_DWELL_MS)
1529
+ return;
1530
+ applyThinking(pendingThinking);
1531
+ };
1532
+ const resetThinkingPacer = () => {
1533
+ thinkingAppliedAt = 0;
1534
+ pendingThinking = null;
1535
+ };
1332
1536
  const done = new Promise((resolve) => {
1333
1537
  resolveDone = resolve;
1334
1538
  });
@@ -1342,15 +1546,17 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1342
1546
  void remountTui();
1343
1547
  }, 0);
1344
1548
  };
1345
- const showTransientStatus = (status) => {
1549
+ const showTransientStatus = (transientStatus) => {
1346
1550
  if (transientStatusTimer) {
1347
1551
  clearTimeout(transientStatusTimer);
1348
1552
  transientStatusTimer = null;
1349
1553
  }
1350
- store.update((current) => ({ ...current, status }));
1554
+ store.update((current) => ({ ...current, transientStatus }));
1351
1555
  transientStatusTimer = setTimeout(() => {
1352
1556
  transientStatusTimer = null;
1353
- store.update((current) => current.status === status ? { ...current, status: 'Ready' } : current);
1557
+ store.update((current) => current.transientStatus === transientStatus
1558
+ ? { ...current, transientStatus: null }
1559
+ : current);
1354
1560
  }, 2500);
1355
1561
  };
1356
1562
  const terminalTitle = createTerminalTitleController({
@@ -1363,14 +1569,43 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1363
1569
  busy: state.busy,
1364
1570
  });
1365
1571
  };
1572
+ const notifier = backendFor();
1573
+ let notificationHandle = null;
1574
+ const projectLabel = basename(session.rootDir) || 'TheGitAI';
1575
+ const notifications = createNotificationQueue();
1576
+ const attention = createAttentionController({
1577
+ notify: (kind) => {
1578
+ notifications.run(async () => {
1579
+ notificationHandle = await notifier.post({
1580
+ title: projectLabel,
1581
+ body: kind === 'blocked'
1582
+ ? 'Waiting for your answer'
1583
+ : 'Finished - your turn',
1584
+ }, notificationHandle);
1585
+ });
1586
+ },
1587
+ withdraw: () => {
1588
+ notifications.run(async () => {
1589
+ notifier.withdraw(notificationHandle);
1590
+ notificationHandle = null;
1591
+ });
1592
+ },
1593
+ });
1594
+ const syncAttention = () => {
1595
+ const state = store.getState();
1596
+ attention.sync({
1597
+ awaitingAnswer: Boolean(state.approvalPrompt || state.sudoPrompt || state.userInputPrompt),
1598
+ busy: state.busy,
1599
+ focused: state.terminalFocused,
1600
+ }, state.notificationsEnabled);
1601
+ };
1366
1602
  const renderCurrentFrame = () => {
1367
1603
  if (!tuiReady)
1368
1604
  return;
1369
1605
  const state = store.getState();
1370
1606
  syncTerminalTitle();
1371
- const elapsedSeconds = state.busySince
1372
- ? Math.max(0, Math.floor((Date.now() - state.busySince) / 1000))
1373
- : 0;
1607
+ syncAttention();
1608
+ const elapsedSeconds = busyElapsedSeconds(state, Date.now());
1374
1609
  bridge.render(buildTuiFrame(state, terminalCols, terminalRows, spinnerFrame, elapsedSeconds, Date.now()));
1375
1610
  };
1376
1611
  const remountTui = async () => {
@@ -1496,15 +1731,16 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1496
1731
  }
1497
1732
  };
1498
1733
  const dismissPendingApproval = () => {
1499
- if (!resolveApprovalChoice)
1734
+ if (!resolvePermissionDecision)
1500
1735
  return;
1501
- const pendingResolve = resolveApprovalChoice;
1502
- resolveApprovalChoice = null;
1503
- pendingResolve('n');
1736
+ const pendingResolve = resolvePermissionDecision;
1737
+ resolvePermissionDecision = null;
1738
+ pendingResolve({ kind: 'deny' });
1504
1739
  store.update((current) => ({
1505
- ...current,
1506
- approvalCursor: getDefaultApprovalCursor(),
1740
+ ...resumeBusyClock(current, Date.now()),
1741
+ approvalCursor: 0,
1507
1742
  approvalPrompt: null,
1743
+ approvalScrollOffset: 0,
1508
1744
  }));
1509
1745
  };
1510
1746
  const dismissPendingSudoPassword = () => {
@@ -1517,21 +1753,40 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1517
1753
  sudoPasswordBuffer = '';
1518
1754
  pendingResolve(null);
1519
1755
  store.update((current) => ({
1520
- ...current,
1756
+ ...resumeBusyClock(current, Date.now()),
1521
1757
  sudoPrompt: null,
1522
1758
  }));
1523
1759
  };
1760
+ const dismissPendingUserInput = () => {
1761
+ const pending = pendingUserInput;
1762
+ if (!pending)
1763
+ return;
1764
+ pendingUserInput = null;
1765
+ pending.signal?.removeEventListener('abort', pending.onAbort);
1766
+ const error = new Error('Turn cancelled.');
1767
+ error.name = 'AbortError';
1768
+ pending.reject(error);
1769
+ store.update((current) => ({
1770
+ ...resumeBusyClock(current, Date.now()),
1771
+ status: current.userInputPrompt?.returnStatus ?? current.status,
1772
+ userInputPrompt: null,
1773
+ }));
1774
+ };
1524
1775
  const cancelActiveTurn = () => {
1525
1776
  if (!store.getState().busy || newConversationInFlight)
1526
1777
  return;
1527
1778
  disarmExitConfirm();
1528
1779
  dismissPendingApproval();
1529
1780
  dismissPendingSudoPassword();
1781
+ dismissPendingUserInput();
1530
1782
  activeTurnGeneration += 1;
1783
+ resetThinkingPacer();
1531
1784
  activeTurnAbort?.abort();
1532
1785
  activeTurnAbort = null;
1533
1786
  cancelActiveCommand();
1534
1787
  const queued = store.getState().queuedMessage;
1788
+ const restoredAttachments = composerAttachmentsAfterCancel(queued ? queued.imageAttachments : [], activeTurnImageAttachments);
1789
+ activeTurnImageAttachments = [];
1535
1790
  const cancelledEntries = [
1536
1791
  ...takePendingTurnEntries(),
1537
1792
  {
@@ -1545,20 +1800,23 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1545
1800
  activeTurnInput: '',
1546
1801
  activeTurnInputPreformatted: false,
1547
1802
  busy: false,
1803
+ busyPausedAt: null,
1548
1804
  busySince: null,
1549
1805
  commandLog: [],
1550
1806
  cursor: queued ? queued.body.length : current.cursor,
1551
- imageAttachments: queued ? queued.imageAttachments : [],
1807
+ imageAttachments: restoredAttachments,
1552
1808
  input: queued ? queued.body : current.input,
1553
1809
  pastedChunks: queued ? queued.pastedChunks : current.pastedChunks,
1554
1810
  promptHistoryCursor: queued ? null : current.promptHistoryCursor,
1555
1811
  promptHistoryDraft: queued ? '' : current.promptHistoryDraft,
1556
1812
  queuedMessage: null,
1813
+ recoveryStatus: '',
1557
1814
  status: 'Ready',
1558
1815
  thinkingTitle: '',
1559
1816
  thinkingNotes: [],
1817
+ turnMessages: [],
1560
1818
  workingTools: [],
1561
- tokenUsage: formatClientTokenUsage(current.busySince == null ? null : Date.now() - current.busySince, latestUsageSummary),
1819
+ tokenUsage: formatClientTokenUsage(busyElapsedMs(current, Date.now()), latestUsageSummary),
1562
1820
  }));
1563
1821
  appendStaticEntries(cancelledEntries);
1564
1822
  lastTurnStartedAt = null;
@@ -1573,6 +1831,7 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1573
1831
  autoYes: sessionAutoYes,
1574
1832
  commandCursor: 0,
1575
1833
  currentModelId: session.modelId,
1834
+ reasoningEffort: projectModelEffort(readProjectModelEfforts(session.rootDir, authConfig.serverUrl, session.env), session.modelId),
1576
1835
  sessionId: session.sessionId,
1577
1836
  modelPickerIndex: current.modelPickerOpen
1578
1837
  ? getDefaultModelPickerIndex(session.modelId, current.serverModels)
@@ -1596,6 +1855,9 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1596
1855
  setAgentMode(nextAgentMode(session.agentMode));
1597
1856
  scheduleLiveFrameRemount();
1598
1857
  };
1858
+ const reportAgentModeLocked = () => {
1859
+ showTransientStatus(AGENT_MODE_LOCKED_STATUS);
1860
+ };
1599
1861
  const clearLiveFrameRemountTimer = () => {
1600
1862
  if (!liveFrameRemountTimer)
1601
1863
  return;
@@ -1644,6 +1906,7 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1644
1906
  }
1645
1907
  dismissPendingApproval();
1646
1908
  dismissPendingSudoPassword();
1909
+ dismissPendingUserInput();
1647
1910
  exiting = true;
1648
1911
  killAllBackgroundJobs();
1649
1912
  store.update((current) => ({
@@ -1661,7 +1924,9 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1661
1924
  if (!isAuthenticationError(error))
1662
1925
  return false;
1663
1926
  clearCliAuthConfig(session.env);
1664
- saveSessionState(session);
1927
+ if (sessionHasUserMessage(session)) {
1928
+ saveSessionState(session);
1929
+ }
1665
1930
  fatalError = new Error(authenticationErrorMessage(error));
1666
1931
  requestExit();
1667
1932
  return true;
@@ -1707,7 +1972,7 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1707
1972
  cleanupSudoPasswordPrompt = null;
1708
1973
  }
1709
1974
  store.update((current) => ({
1710
- ...current,
1975
+ ...pauseBusyClock(current, Date.now()),
1711
1976
  sudoPrompt: {
1712
1977
  command,
1713
1978
  passwordLength: 0,
@@ -1727,7 +1992,7 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1727
1992
  cleanupSudoPasswordPrompt = null;
1728
1993
  sudoPasswordBuffer = '';
1729
1994
  store.update((current) => ({
1730
- ...current,
1995
+ ...resumeBusyClock(current, Date.now()),
1731
1996
  sudoPrompt: null,
1732
1997
  status: current.sudoPrompt?.returnStatus ?? current.status,
1733
1998
  }));
@@ -1741,7 +2006,7 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1741
2006
  cleanupSudoPasswordPrompt = null;
1742
2007
  sudoPasswordBuffer = '';
1743
2008
  store.update((current) => ({
1744
- ...current,
2009
+ ...resumeBusyClock(current, Date.now()),
1745
2010
  sudoPrompt: null,
1746
2011
  status: current.sudoPrompt?.returnStatus ?? current.status,
1747
2012
  }));
@@ -1761,38 +2026,95 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1761
2026
  : null,
1762
2027
  }));
1763
2028
  };
1764
- const openApprovalPrompt = (title, body, options = {}) => new Promise((resolve) => {
1765
- if (exiting) {
1766
- resolve('n');
2029
+ const openUserInputPrompt = (questions, signal) => new Promise((resolve, reject) => {
2030
+ if (exiting || signal?.aborted) {
2031
+ const error = new Error('Turn cancelled.');
2032
+ error.name = 'AbortError';
2033
+ reject(error);
2034
+ return;
2035
+ }
2036
+ const onAbort = () => dismissPendingUserInput();
2037
+ pendingUserInput = {
2038
+ questions,
2039
+ resolve,
2040
+ reject,
2041
+ signal,
2042
+ onAbort,
2043
+ };
2044
+ signal?.addEventListener('abort', onAbort, { once: true });
2045
+ store.update((current) => ({
2046
+ ...pauseBusyClock(current, Date.now()),
2047
+ ...closedJobsPickerFields(current),
2048
+ status: 'Waiting for your input',
2049
+ userInputPrompt: createUserInputPromptState(questions, statusBehindJobsPicker(current)),
2050
+ }));
2051
+ scheduleLiveFrameRemount();
2052
+ });
2053
+ const handleInlineUserInput = async (result) => {
2054
+ const pending = pendingUserInput;
2055
+ const prompt = store.getState().userInputPrompt;
2056
+ if (!pending || !prompt)
2057
+ return;
2058
+ pendingUserInput = null;
2059
+ pending.signal?.removeEventListener('abort', pending.onAbort);
2060
+ store.update((current) => ({
2061
+ ...resumeBusyClock(current, Date.now()),
2062
+ status: prompt.returnStatus,
2063
+ userInputPrompt: null,
2064
+ }));
2065
+ appendTurnAwareEntry({
2066
+ body: formatUserInputTranscript(pending.questions, result),
2067
+ kind: result.status === 'submitted' ? 'user' : 'system',
2068
+ title: result.status === 'submitted' ? 'Your answers' : 'Question',
2069
+ });
2070
+ pending.resolve(result);
2071
+ scheduleLiveFrameRemount();
2072
+ };
2073
+ const openApprovalPrompt = (request, signal) => new Promise((resolve) => {
2074
+ const deny = { kind: 'deny' };
2075
+ if (exiting || signal?.aborted) {
2076
+ resolve(deny);
1767
2077
  return;
1768
2078
  }
1769
- resolveApprovalChoice = resolve;
2079
+ const onAbort = () => dismissPendingApproval();
2080
+ signal?.addEventListener('abort', onAbort, { once: true });
2081
+ resolvePermissionDecision = (decision) => {
2082
+ signal?.removeEventListener('abort', onAbort);
2083
+ resolve(decision);
2084
+ };
1770
2085
  store.update((current) => ({
1771
- ...current,
1772
- approvalCursor: getDefaultApprovalCursor(),
2086
+ ...pauseBusyClock(current, Date.now()),
2087
+ ...closedJobsPickerFields(current),
2088
+ approvalCursor: getDefaultApprovalCursor(request.options.length),
2089
+ approvalOpenedAt: Date.now(),
2090
+ approvalScrollOffset: 0,
1773
2091
  approvalPrompt: {
1774
- title,
1775
- body,
1776
- diffPreview: options.diff && options.filePath
1777
- ? parseDiffPreview(options.diff)
2092
+ title: request.title,
2093
+ body: request.body,
2094
+ diffPreview: request.diff && request.filePath
2095
+ ? parseDiffPreview(request.diff)
1778
2096
  : undefined,
1779
- filePath: options.filePath,
1780
- returnStatus: current.status,
2097
+ filePath: request.filePath,
2098
+ options: request.options,
2099
+ returnStatus: statusBehindJobsPicker(current),
1781
2100
  },
1782
- status: title,
2101
+ status: request.title,
1783
2102
  }));
1784
2103
  });
1785
- const handleInlineApprovalChoice = async (choice) => {
2104
+ const handleInlineApprovalChoice = async (index) => {
1786
2105
  const current = store.getState();
1787
- const pendingResolve = resolveApprovalChoice;
1788
- resolveApprovalChoice = null;
2106
+ const options = current.approvalPrompt?.options ?? [];
2107
+ const chosen = options[index]?.decision ?? { kind: 'deny' };
2108
+ const pendingResolve = resolvePermissionDecision;
2109
+ resolvePermissionDecision = null;
1789
2110
  store.update((next) => ({
1790
- ...next,
1791
- approvalCursor: getDefaultApprovalCursor(),
2111
+ ...resumeBusyClock(next, Date.now()),
2112
+ approvalCursor: getDefaultApprovalCursor(options.length),
1792
2113
  approvalPrompt: null,
2114
+ approvalScrollOffset: 0,
1793
2115
  status: current.approvalPrompt?.returnStatus ?? next.status,
1794
2116
  }));
1795
- pendingResolve?.(choice);
2117
+ pendingResolve?.(chosen);
1796
2118
  };
1797
2119
  const refreshServerModels = async () => {
1798
2120
  currentServerModels = await models.fetchServerModels({ config: authConfig });
@@ -1811,15 +2133,19 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1811
2133
  input: '',
1812
2134
  modelPickerIndex: getDefaultModelPickerIndex(current.currentModelId, fresh.models),
1813
2135
  modelPickerOpen: true,
2136
+ modelPickerEfforts: readProjectModelEfforts(session.rootDir, authConfig.serverUrl, session.env),
1814
2137
  status: 'Select a model',
1815
2138
  }));
1816
2139
  };
1817
- const switchToModel = async (modelId) => {
1818
- const requested = Number(modelId);
1819
- const fresh = currentServerModels.models.some((model) => model.id === requested)
1820
- ? currentServerModels
1821
- : await refreshServerModels();
2140
+ const switchToModel = async (modelId, effort) => {
2141
+ const fresh = await modelsForSwitch(Number(modelId), currentServerModels, refreshServerModels);
1822
2142
  const selected = models.validateServerModel(modelId, fresh);
2143
+ const lockedModel = fresh.models.find((model) => model.id === selected && model.locked);
2144
+ if (lockedModel)
2145
+ throw new Error(modelLockMessage(lockedModel));
2146
+ if (effort !== undefined) {
2147
+ saveProjectModelEffort(session.rootDir, selected, effort, authConfig.serverUrl, session.env);
2148
+ }
1823
2149
  session.modelId = selected;
1824
2150
  models.updateSelectedModelCache({
1825
2151
  config: authConfig,
@@ -1830,29 +2156,42 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1830
2156
  return;
1831
2157
  syncShellStateFromSession();
1832
2158
  appendStaticEntry({
1833
- body: `Switched to ${formatModelLabel(selected, fresh.models)}. Conversation history preserved.`,
2159
+ body: fresh.models.some((model) => model.id === selected && model.auto)
2160
+ ? formatModelLabel(selected, fresh.models)
2161
+ : `${formatModelLabel(selected, fresh.models)} · ${REASONING_EFFORT_LABELS[store.getState().reasoningEffort]} effort${effort === undefined ? '' : '\nSaved for this model in this project.'}`,
1834
2162
  kind: 'system',
1835
2163
  title: 'Model',
1836
2164
  });
1837
2165
  };
2166
+ const toggleNotifications = () => {
2167
+ const enabled = !store.getState().notificationsEnabled;
2168
+ store.update((current) => ({ ...current, notificationsEnabled: enabled }));
2169
+ try {
2170
+ writePreferences({ ...readPreferences(session.env), notifications: enabled }, session.env);
2171
+ }
2172
+ catch {
2173
+ }
2174
+ showTransientStatus(enabled ? 'Notifications on' : 'Notifications off');
2175
+ };
1838
2176
  const openJobsPicker = () => {
2177
+ if (store.getState().jobsPickerOpen)
2178
+ return;
1839
2179
  syncBackgroundJobsState();
1840
2180
  store.update((current) => ({
1841
2181
  ...current,
1842
2182
  commandCursor: 0,
1843
- cursor: 0,
1844
- input: '',
1845
2183
  jobsPickerExpandedId: null,
1846
2184
  jobsPickerIndex: 0,
1847
2185
  jobsPickerOpen: true,
2186
+ jobsPickerReturnStatus: current.status,
1848
2187
  status: 'Background jobs',
1849
2188
  }));
2189
+ scheduleLiveFrameRemount();
1850
2190
  };
1851
2191
  const appendJobOutputEntry = async (jobId) => {
1852
2192
  const id = jobId.trim();
1853
2193
  await collectBackgroundJobUiOutputMutations({
1854
2194
  session,
1855
- projectIndex,
1856
2195
  jobId: id,
1857
2196
  });
1858
2197
  const job = listBackgroundJobs().find((candidate) => candidate.id === id);
@@ -1868,7 +2207,7 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1868
2207
  body: `${dropped}${buffered.output || '(no output captured)'}`,
1869
2208
  kind: 'system',
1870
2209
  preformatted: true,
1871
- title: `${job.id} output — ${truncate(job.command, 80)}`,
2210
+ title: `${job.id} output - ${truncate(job.command, 80)}`,
1872
2211
  });
1873
2212
  };
1874
2213
  const selectedJobsPickerId = () => {
@@ -1878,32 +2217,51 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1878
2217
  const index = Math.min(Math.max(current.jobsPickerIndex, 0), current.backgroundJobs.length - 1);
1879
2218
  return current.backgroundJobs[index]?.id ?? null;
1880
2219
  };
2220
+ const deferredJobMutationIds = new Set();
2221
+ const drainDeferredJobMutations = async () => {
2222
+ if (deferredJobMutationIds.size === 0)
2223
+ return;
2224
+ const pending = [...deferredJobMutationIds];
2225
+ deferredJobMutationIds.clear();
2226
+ for (const jobId of pending) {
2227
+ await collectBackgroundJobUiOutputMutations({ session, jobId });
2228
+ }
2229
+ syncBackgroundJobsState();
2230
+ };
1881
2231
  const handleJobsPickerOutput = async () => {
1882
2232
  const jobId = selectedJobsPickerId();
1883
2233
  if (!jobId)
1884
2234
  return;
1885
- await collectBackgroundJobUiOutputMutations({
1886
- session,
1887
- projectIndex,
1888
- jobId,
1889
- });
1890
- syncBackgroundJobsState();
2235
+ if (store.getState().busy) {
2236
+ deferredJobMutationIds.add(jobId);
2237
+ }
2238
+ else {
2239
+ await collectBackgroundJobUiOutputMutations({
2240
+ session,
2241
+ jobId,
2242
+ });
2243
+ }
1891
2244
  store.update((current) => ({
1892
2245
  ...current,
1893
2246
  jobsPickerExpandedId: current.jobsPickerExpandedId === jobId ? null : jobId,
1894
2247
  }));
2248
+ syncBackgroundJobsState();
1895
2249
  };
1896
2250
  const handleJobsPickerKill = async () => {
1897
2251
  const jobId = selectedJobsPickerId();
1898
2252
  if (!jobId)
1899
2253
  return;
1900
2254
  const killed = await killBackgroundJob(jobId);
1901
- await collectBackgroundJobUiKillMutations({
1902
- session,
1903
- projectIndex,
1904
- jobId,
1905
- result: killed,
1906
- });
2255
+ if (store.getState().busy) {
2256
+ deferredJobMutationIds.add(jobId);
2257
+ }
2258
+ else {
2259
+ await collectBackgroundJobUiKillMutations({
2260
+ session,
2261
+ jobId,
2262
+ result: killed,
2263
+ });
2264
+ }
1907
2265
  syncBackgroundJobsState();
1908
2266
  if (!killed.ok) {
1909
2267
  appendError(killed.error ?? 'Background job kill failed.');
@@ -1921,6 +2279,13 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1921
2279
  const options = buildModelPickerOptions(current.currentModelId, current.serverModels);
1922
2280
  const selectedIndex = Math.min(current.modelPickerIndex, Math.max(options.length - 1, 0));
1923
2281
  const selected = options[selectedIndex];
2282
+ const lockedModel = selected?.disabled
2283
+ ? current.serverModels.find((model) => model.id === selected.id)
2284
+ : undefined;
2285
+ if (lockedModel) {
2286
+ showTransientStatus(modelLockMessage(lockedModel));
2287
+ return;
2288
+ }
1924
2289
  store.update((next) => ({
1925
2290
  ...next,
1926
2291
  modelPickerOpen: false,
@@ -1934,16 +2299,8 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1934
2299
  });
1935
2300
  return;
1936
2301
  }
1937
- if (selected.id === current.currentModelId) {
1938
- appendStaticEntry({
1939
- body: `Already using ${formatModelLabel(selected.id, current.serverModels)}.`,
1940
- kind: 'system',
1941
- title: 'Model',
1942
- });
1943
- return;
1944
- }
1945
2302
  try {
1946
- await switchToModel(selected.id);
2303
+ await switchToModel(selected.id, projectModelEffort(current.modelPickerEfforts ?? {}, selected.id));
1947
2304
  }
1948
2305
  catch (error) {
1949
2306
  if (exitForAuthenticationError(error))
@@ -1997,15 +2354,24 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1997
2354
  store.update((next) => ({
1998
2355
  ...next,
1999
2356
  busy: true,
2357
+ busyPausedAt: null,
2000
2358
  busySince: resumeStartedAt,
2001
2359
  clockNow: resumeStartedAt,
2002
2360
  status: 'Loading session...',
2003
2361
  }));
2004
2362
  try {
2005
2363
  const snapshot = await loadInteractiveSession(selected.id);
2006
- applySessionSnapshot(session, snapshot);
2364
+ const requestedModelId = Number(snapshot.modelId);
2365
+ const knownModels = currentServerModels.models.some((model) => model.id === requestedModelId)
2366
+ ? currentServerModels
2367
+ : await refreshServerModels();
2368
+ const { modelId: resolvedModelId, fellBack } = models.resolveResumedSessionModel(requestedModelId, knownModels);
2369
+ applySessionSnapshot(session, snapshot, {
2370
+ modelOverride: fellBack ? resolvedModelId : undefined,
2371
+ });
2007
2372
  setBackgroundJobSession(session.sessionId);
2008
2373
  setScratchSession(session.sessionId);
2374
+ setImageStoreSession(session.sessionId);
2009
2375
  syncBackgroundJobsState();
2010
2376
  setTodoSession(session.sessionId);
2011
2377
  syncTodosState();
@@ -2013,6 +2379,7 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2013
2379
  store.update((next) => ({
2014
2380
  ...next,
2015
2381
  busy: false,
2382
+ busyPausedAt: null,
2016
2383
  busySince: null,
2017
2384
  resumePickerFilter: '',
2018
2385
  resumePickerIndex: 0,
@@ -2026,6 +2393,15 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2026
2393
  kind: 'system',
2027
2394
  title: 'Session',
2028
2395
  },
2396
+ ...(fellBack
2397
+ ? [
2398
+ {
2399
+ body: `This session's model is no longer available - switched to ${formatModelLabel(resolvedModelId, knownModels.models)}. Conversation history preserved.`,
2400
+ kind: 'system',
2401
+ title: 'Model',
2402
+ },
2403
+ ]
2404
+ : []),
2029
2405
  ...buildTranscriptFromSessionHistory(session.history),
2030
2406
  ]);
2031
2407
  await remountTui();
@@ -2036,6 +2412,7 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2036
2412
  store.update((next) => ({
2037
2413
  ...next,
2038
2414
  busy: false,
2415
+ busyPausedAt: null,
2039
2416
  busySince: null,
2040
2417
  resumePickerFilter: '',
2041
2418
  resumePickerIndex: 0,
@@ -2059,28 +2436,284 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2059
2436
  }));
2060
2437
  await handleSubmit(queued.body);
2061
2438
  };
2062
- const handleSubmit = async (rawInput) => {
2063
- const chunks = store.getState().pastedChunks;
2439
+ let turnMessageCounter = 0;
2440
+ const upsertTurnMessage = (id, patch) => {
2441
+ store.update((current) => ({
2442
+ ...current,
2443
+ turnMessages: current.turnMessages.map((message) => message.id === id ? { ...message, ...patch } : message),
2444
+ }));
2445
+ };
2446
+ const recoverUnacknowledgedMessages = (autoSubmits = true) => {
2447
+ if (unacknowledged.size === 0)
2448
+ return;
2449
+ const stranded = [...unacknowledged.values()];
2450
+ unacknowledged = new Map();
2451
+ for (const { row } of stranded) {
2452
+ upsertTurnMessage(row, {
2453
+ state: 'queued',
2454
+ note: autoSubmits
2455
+ ? 'not read - sending as the next prompt'
2456
+ : 'not read - left in the composer',
2457
+ });
2458
+ }
2459
+ const existing = store.getState().queuedMessage;
2460
+ const combined = [
2461
+ ...stranded.map((entry) => entry.queued),
2462
+ ...(existing ? [existing] : []),
2463
+ ];
2464
+ const body = combined
2465
+ .map((entry) => entry.body)
2466
+ .filter((entry) => entry.trim())
2467
+ .join('\n\n');
2468
+ if (!body.trim())
2469
+ return;
2470
+ scheduleLiveFrameRemount();
2471
+ store.update((current) => ({
2472
+ ...current,
2473
+ queuedMessage: {
2474
+ body,
2475
+ imageAttachments: combined.flatMap((entry) => entry.imageAttachments),
2476
+ pastedChunks: combined.flatMap((entry) => entry.pastedChunks),
2477
+ },
2478
+ }));
2479
+ };
2480
+ const fireQueuedMessage = async () => {
2481
+ const state = store.getState();
2482
+ const queued = state.queuedMessage;
2483
+ if (!queued || !state.busy || exiting)
2484
+ return;
2485
+ const text = (queued.pastedChunks.length
2486
+ ? expandPastedChunks(queued.body, queued.pastedChunks)
2487
+ : queued.body).trim();
2488
+ const images = queued.imageAttachments.filter((attachment) => queued.body.includes(`[Image #${attachment.index}]`));
2489
+ if (!text && images.length === 0)
2490
+ return;
2491
+ const turnId = activeServerTurnId;
2492
+ const blockedReason = !turnId ? 'waiting for the turn to end' : null;
2493
+ const existingRow = blockedRows.get(queued);
2494
+ if (existingRow !== undefined) {
2495
+ upsertTurnMessage(existingRow, {
2496
+ state: 'queued',
2497
+ ...(blockedReason ? { note: blockedReason } : {}),
2498
+ });
2499
+ if (blockedReason || !turnId)
2500
+ return;
2501
+ }
2502
+ const id = existingRow ?? ++turnMessageCounter;
2503
+ const messageId = `m${id}_${Date.now().toString(36)}`;
2504
+ if (existingRow === undefined) {
2505
+ scheduleLiveFrameRemount();
2506
+ store.update((current) => ({
2507
+ ...current,
2508
+ turnMessages: [
2509
+ ...current.turnMessages,
2510
+ {
2511
+ id,
2512
+ text,
2513
+ state: blockedReason ? 'queued' : 'sending',
2514
+ ...(blockedReason ? { note: blockedReason } : {}),
2515
+ },
2516
+ ],
2517
+ }));
2518
+ }
2519
+ if (blockedReason || !turnId) {
2520
+ blockedRows.set(queued, id);
2521
+ return;
2522
+ }
2523
+ blockedRows.delete(queued);
2524
+ unacknowledged.set(messageId, { row: id, queued });
2525
+ scheduleLiveFrameRemount();
2526
+ store.update((current) => current.queuedMessage === queued
2527
+ ? { ...current, queuedMessage: null }
2528
+ : current);
2529
+ queueTurnEntry({
2530
+ body: text,
2531
+ kind: 'user',
2532
+ preformatted: queued.pastedChunks.length > 0,
2533
+ title: 'You · sent mid-turn',
2534
+ });
2535
+ const rollback = (note) => {
2536
+ if (!unacknowledged.delete(messageId))
2537
+ return;
2538
+ upsertTurnMessage(id, { state: 'queued', note });
2539
+ scheduleLiveFrameRemount();
2540
+ store.update((current) => current.queuedMessage ? current : { ...current, queuedMessage: queued });
2541
+ };
2542
+ let outcome;
2543
+ try {
2544
+ outcome = await chat.postInterjection({
2545
+ config: authConfig,
2546
+ turnId,
2547
+ text,
2548
+ messageId,
2549
+ imageAttachments: images,
2550
+ });
2551
+ }
2552
+ catch (error) {
2553
+ rollback(`not sent - ${error?.message ?? 'request failed'}`);
2554
+ return;
2555
+ }
2556
+ if (outcome === 'stale') {
2557
+ rollback('turn ended - sending as the next prompt');
2558
+ }
2559
+ };
2560
+ const jobWait = createJobWaitTracker(() => session.sessionId);
2561
+ const refreshSkillCommands = () => {
2562
+ try {
2563
+ const local = skillCatalogue(discoverSkills(session.rootDir, session.env));
2564
+ const names = new Set(local.map((skill) => skill.name));
2565
+ setSkillSlashCommands([
2566
+ ...local,
2567
+ ...BUNDLED_SKILLS.filter((skill) => !names.has(skill.name)),
2568
+ ]);
2569
+ }
2570
+ catch {
2571
+ setSkillSlashCommands([]);
2572
+ }
2573
+ };
2574
+ const runSkillsCommand = async (args) => {
2575
+ const builtinCommands = SLASH_COMMANDS.flatMap((option) => [
2576
+ option.command,
2577
+ ...(option.aliases ?? []),
2578
+ ]);
2579
+ if (!args || args === 'list') {
2580
+ refreshSkillCommands();
2581
+ store.update((current) => ({
2582
+ ...current,
2583
+ commandCursor: 0,
2584
+ skillsPickerIndex: 0,
2585
+ skillsPickerItems: buildSkillsPickerItems(session.rootDir, session.env, builtinCommands),
2586
+ skillsPickerOpen: true,
2587
+ }));
2588
+ scheduleLiveFrameRemount();
2589
+ return;
2590
+ }
2591
+ const addMatch = args.match(/^add(?:\s+([\s\S]*))?$/);
2592
+ const project = /(^|\s)--project(\s|$)/.test(args);
2593
+ const sourceText = String(addMatch?.[1] ?? '')
2594
+ .replace(/(^|\s)--project(?=\s|$)/g, ' ')
2595
+ .trim();
2596
+ const source = addMatch && sourceText ? parseSkillSource(sourceText, session.rootDir) : null;
2597
+ if (!source) {
2598
+ appendStaticEntry({
2599
+ body: `Usage: /skills to list skills, or ${SKILLS_ADD_USAGE}`,
2600
+ kind: 'system',
2601
+ title: 'Skills',
2602
+ });
2603
+ return;
2604
+ }
2605
+ const controller = new AbortController();
2606
+ activeTurnAbort = controller;
2607
+ store.update((current) => ({
2608
+ ...current,
2609
+ busy: true,
2610
+ status: 'Fetching skill...',
2611
+ activeTurnInput: `/skills add ${sourceText}`,
2612
+ }));
2613
+ try {
2614
+ const prepared = await prepareSkillInstall(source, session.env, globalThis.fetch, controller.signal);
2615
+ if (!prepared.ok) {
2616
+ appendStaticEntry({
2617
+ body: controller.signal.aborted ? 'Skill install cancelled.' : prepared.error,
2618
+ kind: 'system',
2619
+ title: 'Skills',
2620
+ });
2621
+ return;
2622
+ }
2623
+ const skill = prepared.skill;
2624
+ const targetRoot = project
2625
+ ? projectSkillsRoot(session.rootDir)
2626
+ : personalSkillsRoot(session.env);
2627
+ const destination = joinPath(targetRoot, skill.name);
2628
+ const files = skill.files.map((file) => file.relPath);
2629
+ const shownFiles = files.slice(0, 12).join(', ') + (files.length > 12 ? `, and ${files.length - 12} more` : '');
2630
+ const decision = await openApprovalPrompt({
2631
+ bucket: 'create',
2632
+ title: `Install skill /${skill.name}?`,
2633
+ body: [
2634
+ skill.description,
2635
+ '',
2636
+ `From: ${skill.origin}`,
2637
+ `To: ${destination}`,
2638
+ `Files (${files.length}): ${shownFiles}`,
2639
+ ...(preparedSkillHasScripts(skill)
2640
+ ? ['', 'It includes scripts. Nothing runs now, and the agent still asks before running any command.']
2641
+ : []),
2642
+ ].join('\n'),
2643
+ options: [
2644
+ { label: 'Install', decision: { kind: 'once' } },
2645
+ { label: 'Cancel', decision: { kind: 'deny' } },
2646
+ ],
2647
+ }, controller.signal);
2648
+ if (decision.kind === 'deny') {
2649
+ appendStaticEntry({ body: 'Skill not installed.', kind: 'system', title: 'Skills' });
2650
+ return;
2651
+ }
2652
+ const installed = installPreparedSkill(skill, targetRoot);
2653
+ if (!installed.ok) {
2654
+ appendStaticEntry({ body: installed.error, kind: 'system', title: 'Skills' });
2655
+ return;
2656
+ }
2657
+ refreshSkillCommands();
2658
+ appendStaticEntry({
2659
+ body: `Installed /${skill.name} in ${installed.dir}.\nThe agent can use it from your next message, or run it yourself with /${skill.name}.`,
2660
+ kind: 'system',
2661
+ title: 'Skills',
2662
+ });
2663
+ }
2664
+ finally {
2665
+ if (activeTurnAbort === controller)
2666
+ activeTurnAbort = null;
2667
+ store.update((current) => ({ ...current, busy: false, activeTurnInput: '', status: '' }));
2668
+ await remountTui();
2669
+ await flushQueuedMessage();
2670
+ }
2671
+ };
2672
+ const handleSubmit = async (rawInput, { jobFollowUp = false } = {}) => {
2673
+ const chunks = jobFollowUp ? [] : store.getState().pastedChunks;
2064
2674
  const expanded = chunks.length
2065
2675
  ? expandPastedChunks(String(rawInput ?? ''), chunks)
2066
2676
  : String(rawInput ?? '');
2067
2677
  const input = expanded.trim();
2068
2678
  const preformatted = chunks.length > 0;
2679
+ refreshSkillCommands();
2069
2680
  if (store.getState().busy) {
2070
2681
  if (!input || exiting)
2071
2682
  return;
2072
2683
  if (input.startsWith('/')) {
2684
+ if (isJobsPickerCommand(input)) {
2685
+ store.update((current) => ({
2686
+ ...current,
2687
+ cursor: 0,
2688
+ input: '',
2689
+ pastedChunks: [],
2690
+ }));
2691
+ openJobsPicker();
2692
+ return;
2693
+ }
2694
+ if (input === '/notify') {
2695
+ store.update((current) => ({
2696
+ ...current,
2697
+ cursor: 0,
2698
+ input: '',
2699
+ pastedChunks: [],
2700
+ }));
2701
+ toggleNotifications();
2702
+ return;
2703
+ }
2073
2704
  appendTurnAwareEntry({
2074
- body: "Slash commands can't be queued while a turn is running.",
2705
+ body: "Slash commands can't be queued while a turn is running. " +
2706
+ 'Ctrl+B opens background jobs, Ctrl+G toggles notifications.',
2075
2707
  kind: 'system',
2076
2708
  title: 'Queued',
2077
2709
  });
2078
2710
  return;
2079
2711
  }
2080
2712
  const pending = store.getState();
2713
+ const body = String(rawInput ?? '');
2081
2714
  const snapshot = {
2082
- body: String(rawInput ?? ''),
2083
- imageAttachments: pending.imageAttachments,
2715
+ body,
2716
+ imageAttachments: pending.imageAttachments.filter((attachment) => body.includes(`[Image #${attachment.index}]`)),
2084
2717
  pastedChunks: pending.pastedChunks,
2085
2718
  };
2086
2719
  scheduleLiveFrameRemount();
@@ -2095,19 +2728,24 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2095
2728
  }));
2096
2729
  return;
2097
2730
  }
2098
- const imageAttachments = store.getState().imageAttachments;
2099
- scheduleLiveFrameRemount();
2100
- store.update((current) => ({
2101
- ...current,
2102
- cursor: 0,
2103
- input: '',
2104
- pastedChunks: [],
2105
- promptHistory: appendPromptToHistory(current.promptHistory, input),
2106
- promptHistoryCursor: null,
2107
- promptHistoryDraft: '',
2108
- }));
2109
- appendPromptHistory(input);
2110
- if (!input || exiting) {
2731
+ const imageAttachments = store
2732
+ .getState()
2733
+ .imageAttachments.filter((attachment) => input.includes(`[Image #${attachment.index}]`));
2734
+ if (!jobFollowUp) {
2735
+ scheduleLiveFrameRemount();
2736
+ store.update((current) => ({
2737
+ ...current,
2738
+ cursor: 0,
2739
+ imageAttachments: [],
2740
+ input: '',
2741
+ pastedChunks: [],
2742
+ promptHistory: appendPromptToHistory(current.promptHistory, input),
2743
+ promptHistoryCursor: null,
2744
+ promptHistoryDraft: '',
2745
+ }));
2746
+ appendPromptHistory(input);
2747
+ }
2748
+ if ((!input && !jobFollowUp) || exiting) {
2111
2749
  store.update((current) => ({ ...current, imageAttachments: [] }));
2112
2750
  return;
2113
2751
  }
@@ -2115,6 +2753,47 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2115
2753
  requestExit();
2116
2754
  return;
2117
2755
  }
2756
+ if (input === '/logout') {
2757
+ store.update((current) => ({
2758
+ ...current,
2759
+ busy: true,
2760
+ status: 'Signing out...',
2761
+ }));
2762
+ try {
2763
+ await logoutFromServer({ config: authConfig });
2764
+ }
2765
+ catch {
2766
+ }
2767
+ clearCliAuthConfig(session.env);
2768
+ signedOut = true;
2769
+ requestExit();
2770
+ return;
2771
+ }
2772
+ if (input === '/skills' || input.startsWith('/skills ')) {
2773
+ await runSkillsCommand(input.slice('/skills'.length).trim());
2774
+ return;
2775
+ }
2776
+ if (input === '/mcp') {
2777
+ const connections = sessionMcp(session);
2778
+ const controller = new AbortController();
2779
+ activeTurnAbort = controller;
2780
+ store.update((current) => ({ ...current, busy: true, status: 'Checking MCP servers...', activeTurnInput: '/mcp' }));
2781
+ try {
2782
+ await connections.discover(controller.signal, { force: true });
2783
+ appendStaticEntry({ body: connections.status(), kind: 'system', title: 'MCP servers' });
2784
+ }
2785
+ catch (error) {
2786
+ appendStaticEntry({ body: controller.signal.aborted ? 'MCP discovery cancelled.' : String(error.message), kind: 'system', title: 'MCP servers' });
2787
+ }
2788
+ finally {
2789
+ if (activeTurnAbort === controller)
2790
+ activeTurnAbort = null;
2791
+ store.update((current) => ({ ...current, busy: false, activeTurnInput: '', status: '' }));
2792
+ await remountTui();
2793
+ }
2794
+ await flushQueuedMessage();
2795
+ return;
2796
+ }
2118
2797
  if (input === '/help') {
2119
2798
  appendStaticEntry({
2120
2799
  body: formatInteractiveHelpText(),
@@ -2131,6 +2810,15 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2131
2810
  });
2132
2811
  return;
2133
2812
  }
2813
+ if (input === '/report') {
2814
+ const opened = await openUrl(REPORT_ISSUE_URL);
2815
+ appendStaticEntries(buildReportTranscriptEntries(opened));
2816
+ return;
2817
+ }
2818
+ if (input === '/notify') {
2819
+ toggleNotifications();
2820
+ return;
2821
+ }
2134
2822
  if (input === '/jobs' || input.startsWith('/jobs ')) {
2135
2823
  const jobsArgs = input.slice('/jobs'.length).trim();
2136
2824
  if (!jobsArgs) {
@@ -2143,7 +2831,6 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2143
2831
  const killed = await killBackgroundJob(jobId);
2144
2832
  await collectBackgroundJobUiKillMutations({
2145
2833
  session,
2146
- projectIndex,
2147
2834
  jobId,
2148
2835
  result: killed,
2149
2836
  });
@@ -2165,7 +2852,7 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2165
2852
  return;
2166
2853
  }
2167
2854
  appendStaticEntry({
2168
- body: 'Usage: /jobs — open the jobs picker · /jobs output <id> — full output · /jobs kill <id> — kill one',
2855
+ body: 'Usage: /jobs - open the jobs picker · /jobs output <id> - full output · /jobs kill <id> - kill one',
2169
2856
  kind: 'system',
2170
2857
  title: 'Background jobs',
2171
2858
  });
@@ -2261,6 +2948,7 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2261
2948
  store.update((current) => ({
2262
2949
  ...current,
2263
2950
  busy: true,
2951
+ busyPausedAt: null,
2264
2952
  busySince: Date.now(),
2265
2953
  imageAttachments: [],
2266
2954
  queuedMessage: null,
@@ -2271,6 +2959,7 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2271
2959
  store.update((current) => ({
2272
2960
  ...current,
2273
2961
  busy: false,
2962
+ busyPausedAt: null,
2274
2963
  busySince: null,
2275
2964
  status: 'Ready',
2276
2965
  }));
@@ -2280,6 +2969,7 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2280
2969
  startNewConversation(session);
2281
2970
  setBackgroundJobSession(session.sessionId);
2282
2971
  setScratchSession(session.sessionId);
2972
+ setImageStoreSession(session.sessionId);
2283
2973
  setTodoSession(session.sessionId);
2284
2974
  clearTodos();
2285
2975
  syncBackgroundJobsState();
@@ -2298,6 +2988,7 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2298
2988
  store.update((current) => ({
2299
2989
  ...current,
2300
2990
  busy: false,
2991
+ busyPausedAt: null,
2301
2992
  busySince: null,
2302
2993
  status: 'Ready',
2303
2994
  }));
@@ -2305,15 +2996,18 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2305
2996
  await flushQueuedMessage();
2306
2997
  return;
2307
2998
  }
2999
+ jobWait.turnStarted(jobFollowUp);
2308
3000
  latestUsageSummary = null;
2309
3001
  disarmExitConfirm();
3002
+ unacknowledged = new Map();
2310
3003
  const turnStartedAt = Date.now();
2311
3004
  const turnGeneration = ++activeTurnGeneration;
2312
3005
  const turnAbort = new AbortController();
2313
3006
  activeTurnAbort = turnAbort;
2314
3007
  lastTurnStartedAt = turnStartedAt;
2315
3008
  todosTouchedThisTurn = false;
2316
- clearTodos();
3009
+ if (!jobFollowUp)
3010
+ clearTodos();
2317
3011
  syncTodosState();
2318
3012
  const userEntry = {
2319
3013
  body: input,
@@ -2322,30 +3016,58 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2322
3016
  title: 'You',
2323
3017
  };
2324
3018
  pendingTurnEntries = [];
2325
- queueTurnEntry(userEntry);
3019
+ if (!jobFollowUp)
3020
+ queueTurnEntry(userEntry);
3021
+ resetThinkingPacer();
3022
+ activeTurnImageAttachments = imageAttachments;
2326
3023
  store.update((current) => ({
2327
3024
  ...current,
2328
3025
  activeTurnInput: input,
2329
3026
  activeTurnInputPreformatted: preformatted,
3027
+ analyzingImages: 0,
3028
+ generatingImage: false,
2330
3029
  busy: true,
3030
+ busyPausedAt: null,
2331
3031
  busySince: turnStartedAt,
2332
3032
  clockNow: turnStartedAt,
3033
+ recoveryStatus: '',
2333
3034
  status: 'Running turn...',
3035
+ usageNotice: null,
2334
3036
  thinkingTitle: '',
2335
3037
  thinkingNotes: [],
2336
3038
  transcriptScrollOffset: 0,
2337
3039
  tokenUsage: formatClientTokenUsage(0, latestUsageSummary),
2338
3040
  turnCounter: current.turnCounter + 1,
3041
+ turnMessages: [],
2339
3042
  workingTools: [],
2340
3043
  }));
2341
3044
  try {
2342
3045
  const result = await chat.sendServerUserMessage({
2343
3046
  config: authConfig,
2344
- projectIndex,
2345
3047
  session,
2346
3048
  input,
3049
+ jobFollowUp,
2347
3050
  imageAttachments,
2348
3051
  signal: turnAbort.signal,
3052
+ onTurnStart: (serverTurnId) => {
3053
+ if (turnGeneration !== activeTurnGeneration)
3054
+ return;
3055
+ activeServerTurnId = serverTurnId;
3056
+ },
3057
+ onInterjectionDelivered: (event) => {
3058
+ if (turnGeneration !== activeTurnGeneration)
3059
+ return;
3060
+ for (const messageId of event.messageIds ?? []) {
3061
+ const pending = unacknowledged.get(messageId);
3062
+ if (!pending)
3063
+ continue;
3064
+ unacknowledged.delete(messageId);
3065
+ upsertTurnMessage(pending.row, {
3066
+ state: 'delivered',
3067
+ note: undefined,
3068
+ });
3069
+ }
3070
+ },
2349
3071
  });
2350
3072
  if (turnGeneration !== activeTurnGeneration)
2351
3073
  return;
@@ -2354,6 +3076,7 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2354
3076
  if (!(await saveActiveSession()))
2355
3077
  return;
2356
3078
  syncShellStateFromSession();
3079
+ activeTurnImageAttachments = [];
2357
3080
  store.update((current) => ({
2358
3081
  ...current,
2359
3082
  activeTurnInput: '',
@@ -2362,6 +3085,7 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2362
3085
  commandLog: [],
2363
3086
  imageAttachments: [],
2364
3087
  status: result.waitingForApproval ? 'Awaiting approval' : 'Finishing response...',
3088
+ usageNotice: null,
2365
3089
  thinkingTitle: '',
2366
3090
  thinkingNotes: [],
2367
3091
  tokenUsage: formatClientTokenUsage(Date.now() - turnStartedAt, latestUsageSummary),
@@ -2389,10 +3113,14 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2389
3113
  store.update((current) => ({
2390
3114
  ...current,
2391
3115
  busy: false,
3116
+ busyPausedAt: null,
2392
3117
  busySince: null,
3118
+ recoveryStatus: '',
2393
3119
  status: result.waitingForApproval ? 'Awaiting approval' : 'Ready',
2394
3120
  tokenUsage: formatClientTokenUsage(Date.now() - turnStartedAt, latestUsageSummary),
2395
3121
  }));
3122
+ jobWait.turnEnded(result.waitingForJobs);
3123
+ recoverUnacknowledgedMessages();
2396
3124
  await flushQueuedMessage();
2397
3125
  }
2398
3126
  catch (error) {
@@ -2405,15 +3133,31 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2405
3133
  const cancelled = isTurnCancelledError(error);
2406
3134
  if (exitForAuthenticationError(error))
2407
3135
  return;
3136
+ dismissPendingApproval();
3137
+ dismissPendingSudoPassword();
3138
+ dismissPendingUserInput();
3139
+ const failedTurnAttachments = activeTurnImageAttachments;
3140
+ activeTurnImageAttachments = [];
3141
+ const quotaNotice = cancelled ? null : buildRefusalNotice(error);
3142
+ const restoresPrompt = quotaNotice !== null && !jobFollowUp && !store.getState().input && !store.getState().queuedMessage;
2408
3143
  store.update((current) => ({
2409
3144
  ...current,
3145
+ ...(restoresPrompt
3146
+ ? { cursor: String(rawInput ?? '').length, input: String(rawInput ?? ''), pastedChunks: chunks }
3147
+ : {}),
2410
3148
  activeTurnInput: '',
2411
3149
  activeTurnInputPreformatted: false,
2412
3150
  busy: false,
3151
+ busyPausedAt: null,
2413
3152
  busySince: null,
2414
3153
  commandLog: [],
2415
- imageAttachments: [],
2416
- status: cancelled ? 'Ready' : 'Turn failed',
3154
+ imageAttachments: failedTurnAttachments,
3155
+ recoveryStatus: '',
3156
+ status: cancelled
3157
+ ? 'Ready'
3158
+ : quotaNotice
3159
+ ? quotaNotice.title
3160
+ : 'Turn failed',
2417
3161
  thinkingTitle: '',
2418
3162
  thinkingNotes: [],
2419
3163
  tokenUsage: formatClientTokenUsage(Date.now() - turnStartedAt, latestUsageSummary),
@@ -2432,12 +3176,25 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2432
3176
  if (!(await saveActiveSession()))
2433
3177
  return;
2434
3178
  }
3179
+ else if (quotaNotice) {
3180
+ appendStaticEntries([
3181
+ ...turnEntries,
3182
+ {
3183
+ body: quotaNotice.body,
3184
+ kind: 'system',
3185
+ title: quotaNotice.title,
3186
+ },
3187
+ ]);
3188
+ }
2435
3189
  else {
2436
3190
  appendStaticEntries(turnEntries);
2437
3191
  appendError(error.message);
3192
+ appendStaticEntries(buildTurnFailureHintEntries(cancelled));
2438
3193
  }
2439
3194
  await remountTui();
2440
- if (!cancelled && turnGeneration === activeTurnGeneration) {
3195
+ const autoSubmits = !cancelled && isTurnOutcomeKnown(error);
3196
+ recoverUnacknowledgedMessages(autoSubmits);
3197
+ if (autoSubmits && turnGeneration === activeTurnGeneration) {
2441
3198
  await flushQueuedMessage();
2442
3199
  }
2443
3200
  }
@@ -2447,24 +3204,75 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2447
3204
  }
2448
3205
  if (turnGeneration === activeTurnGeneration) {
2449
3206
  lastTurnStartedAt = null;
3207
+ activeServerTurnId = null;
2450
3208
  }
3209
+ recoverUnacknowledgedMessages();
3210
+ await drainDeferredJobMutations();
3211
+ if (turnGeneration === activeTurnGeneration)
3212
+ scheduleJobFollowUp();
2451
3213
  }
2452
3214
  };
3215
+ session.onAccountUsage = (usage) => {
3216
+ if (usage?.plan && usage.plan !== store.getState().plan) {
3217
+ store.update((current) => ({ ...current, plan: usage.plan }));
3218
+ }
3219
+ const notice = usageNotice(usage);
3220
+ if (!notice)
3221
+ return;
3222
+ const entry = { ...notice, kind: 'system' };
3223
+ appendTurnAwareEntry(entry);
3224
+ if (store.getState().busy) {
3225
+ store.update((current) => ({ ...current, usageNotice: entry }));
3226
+ }
3227
+ };
3228
+ session.onImageAnalysis = (activeImageCount) => {
3229
+ store.update((current) => ({
3230
+ ...current,
3231
+ analyzingImages: Math.max(0, activeImageCount),
3232
+ generatingImage: activeImageCount > 0 ? false : current.generatingImage,
3233
+ }));
3234
+ };
3235
+ session.onRecovery = (status) => {
3236
+ if (status.phase === 'restored' || status.phase === 'continued') {
3237
+ store.update((current) => ({ ...current, recoveryStatus: '' }));
3238
+ appendTurnAwareEntry(status.phase === 'restored'
3239
+ ? { body: 'Continued the same turn.', kind: 'system', title: 'Connection restored' }
3240
+ : {
3241
+ body: 'Continued from the steps that had finished.',
3242
+ kind: 'system',
3243
+ title: 'Server restarted',
3244
+ });
3245
+ return;
3246
+ }
3247
+ store.update((current) => ({
3248
+ ...current,
3249
+ recoveryStatus: status.phase === 'reconnected' ? '' : formatTurnRecoveryStatus(status),
3250
+ }));
3251
+ };
3252
+ session.onImageGeneration = (active) => {
3253
+ store.update((current) => ({
3254
+ ...current,
3255
+ generatingImage: Boolean(active),
3256
+ analyzingImages: active ? 0 : current.analyzingImages,
3257
+ }));
3258
+ };
2453
3259
  session.onStatus = (message) => {
2454
3260
  const panel = thinkingPanelFromStatus(message);
2455
3261
  store.update((current) => ({
2456
3262
  ...current,
2457
3263
  status: message,
2458
- thinkingTitle: panel?.title ?? current.thinkingTitle,
2459
- thinkingNotes: panel?.notes ?? current.thinkingNotes,
2460
- tokenUsage: formatClientTokenUsage(current.busySince == null ? null : Date.now() - current.busySince, latestUsageSummary),
3264
+ tokenUsage: formatClientTokenUsage(busyElapsedMs(current, Date.now()), latestUsageSummary),
2461
3265
  }));
3266
+ queueThinkingUpdate({
3267
+ title: panel ? panel.title : liveStatusPanelTitle(message),
3268
+ notes: panel ? panel.notes : [],
3269
+ });
2462
3270
  };
2463
3271
  session.onContextLog = (message) => {
2464
3272
  store.update((current) => ({
2465
3273
  ...current,
2466
3274
  contextStatus: message,
2467
- tokenUsage: formatClientTokenUsage(current.busySince == null ? null : Date.now() - current.busySince, latestUsageSummary),
3275
+ tokenUsage: formatClientTokenUsage(busyElapsedMs(current, Date.now()), latestUsageSummary),
2468
3276
  }));
2469
3277
  };
2470
3278
  session.onToolEvent = (event) => {
@@ -2479,31 +3287,27 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2479
3287
  if (isFileChangeTool(event.call.name)) {
2480
3288
  const entry = buildFileChangeEntry(event);
2481
3289
  store.appendWorkingTool(entry);
2482
- appendTurnAwareEntry(entry);
3290
+ const result = event.result;
3291
+ if (result?.ok === true || result?.skipped === true)
3292
+ appendTurnAwareEntry(entry);
2483
3293
  return;
2484
3294
  }
2485
- store.appendWorkingTool(buildWorkingToolEntry(event));
2486
- };
2487
- const jobDetailLines = (jobId) => {
2488
- const buffered = getJobBufferedOutput(jobId);
2489
- if (!buffered)
2490
- return [];
2491
- const lines = buffered.output
2492
- .replace(/\r\n/g, '\n')
2493
- .replace(/\r/g, '\n')
2494
- .split('\n')
2495
- .filter((line) => line.trim().length > 0);
2496
- const visible = lines.slice(-20);
2497
- return buffered.droppedChars > 0
2498
- ? [
2499
- `... (${buffered.droppedChars} chars of older output dropped) ...`,
2500
- ...visible,
2501
- ]
2502
- : visible;
3295
+ store.appendWorkingTool(buildWorkingToolEntry(event, session.mcp?.label(event.call.name)));
2503
3296
  };
2504
3297
  const syncBackgroundJobsState = () => {
3298
+ const expandedId = store.getState().jobsPickerExpandedId;
2505
3299
  const jobsForDisplay = listBackgroundJobs().map((job) => {
2506
- const preview = getJobOutputPreview(job.id, 3);
3300
+ const expanded = job.id === expandedId;
3301
+ const preview = getJobOutputPreview(job.id, expanded ? 20 : 3);
3302
+ const dropped = preview?.droppedChars ?? 0;
3303
+ const detailLines = !expanded
3304
+ ? []
3305
+ : dropped > 0
3306
+ ? [
3307
+ `... (${dropped} chars of older output dropped) ...`,
3308
+ ...(preview?.tailLines ?? []),
3309
+ ]
3310
+ : (preview?.tailLines ?? []);
2507
3311
  return {
2508
3312
  id: job.id,
2509
3313
  command: job.command,
@@ -2512,8 +3316,8 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2512
3316
  startedAt: job.startedAt,
2513
3317
  endedAt: job.endedAt,
2514
3318
  firstOutputLine: preview?.firstLine ?? '',
2515
- tailLines: preview?.tailLines ?? [],
2516
- detailLines: jobDetailLines(job.id),
3319
+ tailLines: (preview?.tailLines ?? []).slice(-3),
3320
+ detailLines,
2517
3321
  };
2518
3322
  });
2519
3323
  store.update((current) => ({
@@ -2524,82 +3328,123 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2524
3328
  : null,
2525
3329
  }));
2526
3330
  };
3331
+ const scheduleJobFollowUp = () => {
3332
+ if (jobWait.waiting.length === 0)
3333
+ return;
3334
+ setTimeout(async () => {
3335
+ const state = store.getState();
3336
+ if (exiting || state.busy || state.modelPickerOpen || state.resumePickerOpen)
3337
+ return;
3338
+ const decision = jobWait.takeDecision();
3339
+ if (decision === 'wait')
3340
+ return;
3341
+ if (decision === 'stop') {
3342
+ appendStaticEntry({
3343
+ body: 'A background job finished. Send a message to continue.',
3344
+ kind: 'system',
3345
+ title: 'Background job',
3346
+ });
3347
+ return;
3348
+ }
3349
+ await drainDeferredJobMutations();
3350
+ if (exiting || store.getState().busy)
3351
+ return;
3352
+ void handleSubmit('', { jobFollowUp: true });
3353
+ }, 0);
3354
+ };
2527
3355
  setBackgroundJobUpdateHook((snapshot) => {
2528
3356
  syncBackgroundJobsState();
2529
3357
  if (snapshot.status !== 'running') {
2530
3358
  appendTurnAwareEntry(buildBackgroundJobNoticeEntry(snapshot));
3359
+ scheduleJobFollowUp();
2531
3360
  }
2532
3361
  });
2533
- projectIndex.onStatus = session.onStatus;
2534
- projectIndex.onContextLog = session.onContextLog;
3362
+ refreshSkillCommands();
2535
3363
  session.requestSudoPassword = async ({ command, prompt, signal }) => openSudoPasswordPrompt(command, prompt, signal);
2536
- session.confirmCommand = async (command) => {
3364
+ session.requestUserInput = async (request, signal) => openUserInputPrompt(request.questions, signal);
3365
+ session.requestPermission = async (request) => {
3366
+ const deny = { kind: 'deny' };
2537
3367
  if (exiting)
2538
- return false;
3368
+ return deny;
2539
3369
  if (sessionAutoYes)
2540
- return true;
2541
- const choice = await openApprovalPrompt('Approve command?', command);
2542
- if (choice === 'a') {
2543
- setAgentMode('auto-accept');
2544
- syncShellStateFromSession();
3370
+ return { kind: 'once' };
3371
+ const decision = await openApprovalPrompt(request, session.turnAbortSignal);
3372
+ if (decision.kind === 'always-bucket') {
2545
3373
  appendTurnAwareEntry({
2546
- body: 'Auto-approve enabled for the rest of this session.',
3374
+ body: `Allowed for the rest of this session: ${bucketActionLabel(request.bucket)}.`,
2547
3375
  kind: 'system',
2548
3376
  title: 'Approvals',
2549
3377
  });
2550
- return true;
2551
3378
  }
2552
- return choice === 'y';
2553
- };
2554
- session.confirmPatch = async (filePath, patch) => {
2555
- if (exiting)
2556
- return false;
2557
- if (sessionAutoYes)
2558
- return true;
2559
- const choice = await openApprovalPrompt('Approve patch?', 'Review changes before applying.', {
2560
- diff: patch,
2561
- filePath,
2562
- });
2563
- if (choice === 'a') {
2564
- setAgentMode('auto-accept');
2565
- syncShellStateFromSession();
3379
+ else if (decision.kind === 'always-prefix') {
2566
3380
  appendTurnAwareEntry({
2567
- body: 'Auto-approve enabled for the rest of this session.',
3381
+ body: `Allowed for the rest of this session: commands starting with \`${decision.prefix}\`.`,
3382
+ kind: 'system',
3383
+ title: 'Approvals',
3384
+ });
3385
+ }
3386
+ else if (decision.kind === 'always-mcp-tool') {
3387
+ appendTurnAwareEntry({
3388
+ body: `Allowed for the rest of this session: ${request.mcpLabel ?? request.title}.`,
3389
+ kind: 'system',
3390
+ title: 'Approvals',
3391
+ });
3392
+ }
3393
+ else if (decision.kind === 'always-origin') {
3394
+ appendTurnAwareEntry({
3395
+ body: `Allowed for the rest of this session: browser actions on ${decision.origin}.`,
2568
3396
  kind: 'system',
2569
3397
  title: 'Approvals',
2570
3398
  });
2571
- return true;
2572
3399
  }
2573
- return choice === 'y';
3400
+ return decision;
2574
3401
  };
2575
3402
  const shellInputHandlers = {
3403
+ getApprovalScrollLimit: () => {
3404
+ const contentWidth = frameContentWidth(terminalCols);
3405
+ return approvalScrollLimit(store.getState().approvalPrompt, contentWidth, terminalRows);
3406
+ },
3407
+ getComposerInputWidth: () => composerInputWidth(terminalCols, store.getState()),
2576
3408
  getTranscriptScrollLimit: () => {
2577
- const contentWidth = Math.max(20, Math.floor(terminalCols * 0.95) - 2);
3409
+ const contentWidth = frameContentWidth(terminalCols);
2578
3410
  const blocks = store.getState().transcript.map((entry) => renderTranscriptEntryLines(entry, contentWidth));
2579
3411
  return blocks.reduce((total, block, index) => total + block.length + (index > 0 ? 1 : 0), 0);
2580
3412
  },
3413
+ getUserInputViewport: () => {
3414
+ const nowMs = Date.now();
3415
+ const state = store.getState();
3416
+ return userInputViewportForFrame(state, terminalCols, terminalRows, spinnerFrame, busyElapsedSeconds(state, nowMs), nowMs);
3417
+ },
2581
3418
  onCancelTurn: cancelActiveTurn,
2582
3419
  onCycleAgentMode: cycleAgentMode,
3420
+ onAgentModeChangeBlocked: reportAgentModeLocked,
2583
3421
  onCtrlC: handleCtrlC,
2584
3422
  onLinkCopy: handleLinkCopy,
2585
3423
  onLinkOpen: handleLinkOpen,
2586
3424
  onLiveFrameShapeChange: scheduleLiveFrameRemount,
2587
3425
  onRequestExit: requestExit,
2588
3426
  onResolveApproval: handleInlineApprovalChoice,
3427
+ onResolveUserInput: handleInlineUserInput,
2589
3428
  onResumeSession: handleInlineResumeSelection,
2590
3429
  onSelectionCopy: handleAppSelectionCopy,
2591
3430
  onSelectModel: handleInlineModelSelection,
3431
+ onOpenJobsPicker: openJobsPicker,
3432
+ onToggleNotifications: toggleNotifications,
2592
3433
  onJobsPickerOutput: handleJobsPickerOutput,
2593
3434
  onJobsPickerKill: handleJobsPickerKill,
2594
3435
  onSudoPasswordInput: handleSudoPasswordInput,
2595
3436
  onSubmit: handleSubmit,
3437
+ onFireQueuedMessage: fireQueuedMessage,
2596
3438
  };
2597
3439
  const unsubscribe = store.subscribe(() => {
2598
3440
  renderCurrentFrame();
3441
+ if (jobWait.waiting.length > 0 && !store.getState().busy)
3442
+ scheduleJobFollowUp();
2599
3443
  });
2600
3444
  const spinnerTimer = setInterval(() => {
2601
3445
  spinnerFrame = (spinnerFrame + 1) % 6;
2602
3446
  if (store.getState().busy) {
3447
+ flushPendingThinking();
2603
3448
  renderCurrentFrame();
2604
3449
  }
2605
3450
  }, 120);
@@ -2630,6 +3475,13 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2630
3475
  return;
2631
3476
  }
2632
3477
  if (message.op === 'event') {
3478
+ if (message.kind === 'focus') {
3479
+ store.update((current) => current.terminalFocused === message.focused
3480
+ ? current
3481
+ : { ...current, terminalFocused: message.focused });
3482
+ renderCurrentFrame();
3483
+ return;
3484
+ }
2633
3485
  if (message.kind === 'resize') {
2634
3486
  terminalCols = message.cols;
2635
3487
  terminalRows = message.rows;
@@ -2655,6 +3507,7 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2655
3507
  killAllBackgroundJobs();
2656
3508
  setBackgroundJobSession(null);
2657
3509
  setScratchSession(null);
3510
+ setImageStoreSession(null);
2658
3511
  setTodoSession(null);
2659
3512
  setBackgroundJobUpdateHook(null);
2660
3513
  await bridge.close();
@@ -2664,4 +3517,5 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2664
3517
  });
2665
3518
  if (fatalError)
2666
3519
  throw fatalError;
3520
+ return { signedOut };
2667
3521
  }