@thegitai/cli 1.0.0-preview.9 → 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 (99) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +301 -15
  3. package/dist/bin/ai.js +139 -111
  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 +77 -34
  8. package/dist/src/api/chat.js +700 -173
  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 +71 -10
  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/repl.js +1141 -299
  72. package/dist/src/ui/slash-commands.js +140 -0
  73. package/dist/src/ui/tui/attention.js +25 -0
  74. package/dist/src/ui/tui/bridge.js +38 -5
  75. package/dist/src/ui/tui/build-frame.js +858 -303
  76. package/dist/src/ui/tui/composer-layout.js +76 -0
  77. package/dist/src/ui/tui/desktop-notification.js +118 -0
  78. package/dist/src/ui/tui/markdown-render.js +21 -11
  79. package/dist/src/ui/tui/model-label.js +13 -0
  80. package/dist/src/ui/tui/shell-input.js +266 -61
  81. package/dist/src/ui/tui/shortcuts.js +61 -0
  82. package/dist/src/ui/tui/terminal-theme.js +28 -0
  83. package/dist/src/ui/tui/text.js +31 -6
  84. package/dist/src/ui/tui/user-input.js +593 -0
  85. package/dist/src/update-check.js +205 -0
  86. package/dist/src/usage-notice.js +52 -0
  87. package/dist/src/usage.js +25 -2
  88. package/dist/src/utils.js +4 -0
  89. package/dist/src/version.js +52 -2
  90. package/dist/vendor/mcp/LICENSES.txt +414 -0
  91. package/dist/vendor/mcp/client.cjs +82 -0
  92. package/package.json +22 -9
  93. package/dist/src/project-index.js +0 -233
  94. package/dist/src/tools/code-intel.js +0 -472
  95. package/dist/src/tools/find-symbol.js +0 -70
  96. package/dist/src/tools/hover-symbol.js +0 -95
  97. package/dist/src/tools/list-symbols.js +0 -55
  98. package/dist/src/tools/search-code.js +0 -37
  99. package/dist/src/tools/signature-help.js +0 -118
@@ -1,18 +1,38 @@
1
+ import { sessionMcp } from '../mcp-client.js';
2
+ import { projectModelEffort, readProjectModelEfforts, saveProjectModelEffort } from '../project-model-preferences.js';
3
+ import { REASONING_EFFORT_LABELS } from '../reasoning-effort.js';
4
+ import { basename, 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';
@@ -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,32 +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
1061
  analyzingImages: 0,
967
- approvalCursor: getDefaultApprovalCursor(),
1062
+ generatingImage: false,
1063
+ approvalCursor: 0,
968
1064
  approvalPrompt: null,
1065
+ approvalScrollOffset: 0,
969
1066
  autoYes: session.autoYes,
970
1067
  backgroundJobs: [],
971
1068
  busy: false,
1069
+ busyPausedAt: null,
972
1070
  busySince: null,
973
1071
  clockNow: Date.now(),
974
1072
  commandCursor: 0,
975
1073
  commandLog: [],
976
1074
  contextStatus: 'Idle',
977
1075
  currentModelId: session.modelId,
1076
+ reasoningEffort: projectModelEffort(readProjectModelEfforts(session.rootDir, serverUrl, session.env), session.modelId),
978
1077
  cursor: 0,
979
1078
  exiting: false,
980
1079
  input: '',
981
1080
  maxToolSteps: session.maxToolSteps,
1081
+ notificationsEnabled: readPreferences(session.env).notifications,
1082
+ terminalFocused: INITIAL_TERMINAL_FOCUS,
982
1083
  jobsPickerExpandedId: null,
983
1084
  jobsPickerIndex: 0,
984
1085
  jobsPickerOpen: false,
985
1086
  modelPickerIndex: getDefaultModelPickerIndex(session.modelId, serverModels.models),
986
1087
  modelPickerOpen: false,
1088
+ shortcutsOpen: false,
1089
+ skillsPickerIndex: 0,
1090
+ skillsPickerItems: [],
1091
+ skillsPickerOpen: false,
1092
+ transientStatus: null,
987
1093
  projectRoot: session.rootDir,
988
1094
  sessionId: session.sessionId,
989
1095
  showSessionId: debugUi.showSessionId,
@@ -996,6 +1102,7 @@ function createInitialShellState(session, serverModels, debugUi) {
996
1102
  resumePickerSessions: [],
997
1103
  transcriptScrollOffset: 0,
998
1104
  queuedMessage: null,
1105
+ turnMessages: [],
999
1106
  serverModels: serverModels.models,
1000
1107
  sudoPrompt: null,
1001
1108
  status: 'Ready',
@@ -1006,6 +1113,7 @@ function createInitialShellState(session, serverModels, debugUi) {
1006
1113
  tokenUsage: formatClientTokenUsage(null),
1007
1114
  transcript: [],
1008
1115
  turnCounter: Math.max(0, session.history.filter((entry) => entry.role === 'user').length),
1116
+ userInputPrompt: null,
1009
1117
  pastedChunks: [],
1010
1118
  imageAttachments: [],
1011
1119
  workingTools: [],
@@ -1022,7 +1130,6 @@ export function formatClientTokenUsage(_responseTimeMs, usageSummary = null) {
1022
1130
  const reasoningTokens = usageSummary?.reasoningTokens ?? 0;
1023
1131
  const cacheTokens = usageSummary?.cacheTokens ?? 0;
1024
1132
  const cacheWriteTokens = usageSummary?.cacheWriteTokens ?? 0;
1025
- const indexTokens = usageSummary?.indexTokens ?? 0;
1026
1133
  return [
1027
1134
  'Session tokens',
1028
1135
  `in ${formatTokenCount(inputTokens)}`,
@@ -1030,7 +1137,6 @@ export function formatClientTokenUsage(_responseTimeMs, usageSummary = null) {
1030
1137
  ...(reasoningTokens > 0 ? [`think ${formatTokenCount(reasoningTokens)}`] : []),
1031
1138
  `cache ${formatTokenCount(cacheTokens)}`,
1032
1139
  `write ${formatTokenCount(cacheWriteTokens)}`,
1033
- `index ${formatTokenCount(indexTokens)}`,
1034
1140
  ].join(' • ');
1035
1141
  }
1036
1142
  export function formatPromptDirectoryLabel(projectRoot, homeDir = process.env.HOME ?? '') {
@@ -1073,6 +1179,24 @@ function splitThinkingLines(text) {
1073
1179
  .map((part) => part.trim())
1074
1180
  .filter(Boolean));
1075
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
+ }
1076
1200
  function thinkingPanelFromStatus(status) {
1077
1201
  const rawText = thinkingNoteFromStatus(status);
1078
1202
  if (!rawText)
@@ -1096,7 +1220,7 @@ function thinkingPanelFromStatus(status) {
1096
1220
  const bodyLines = rawLines.length > 1 && rawLines[0].length <= 72 ? rawLines.slice(1) : rawLines;
1097
1221
  return {
1098
1222
  title,
1099
- notes: splitThinkingLines(bodyLines.join('\n')).slice(-3),
1223
+ notes: splitThinkingLines(bodyLines.join('\n')).slice(0, 3),
1100
1224
  };
1101
1225
  }
1102
1226
  export const EXIT_CTRL_C_CONFIRM_MESSAGE = 'Press Ctrl+C again to quit.';
@@ -1104,16 +1228,6 @@ export const EXIT_CTRL_C_CONFIRM_MS = 3000;
1104
1228
  export function isExitConfirmActive(exitConfirmUntil, now = Date.now()) {
1105
1229
  return exitConfirmUntil != null && now < exitConfirmUntil;
1106
1230
  }
1107
- export function getInputCommandToken(input) {
1108
- const trimmed = String(input ?? '').trim();
1109
- if (!trimmed.startsWith('/'))
1110
- return '';
1111
- const firstSpaceIndex = trimmed.indexOf(' ');
1112
- const token = firstSpaceIndex === -1 ? trimmed : trimmed.slice(0, firstSpaceIndex);
1113
- if (token.indexOf('/', 1) !== -1)
1114
- return '';
1115
- return token;
1116
- }
1117
1231
  function shouldShowCommandPalette(state) {
1118
1232
  const trimmed = String(state.input ?? '').trim();
1119
1233
  return (!state.busy &&
@@ -1121,8 +1235,9 @@ function shouldShowCommandPalette(state) {
1121
1235
  !state.modelPickerOpen &&
1122
1236
  !state.resumePickerOpen &&
1123
1237
  trimmed.startsWith('/') &&
1124
- !trimmed.includes(' ') &&
1125
- getInputCommandToken(trimmed) !== '');
1238
+ !String(state.input ?? '').includes(' ') &&
1239
+ getInputCommandToken(trimmed) !== '' &&
1240
+ getSlashCommandSuggestions(trimmed).length > 0);
1126
1241
  }
1127
1242
  export function shouldRemountLiveFrameForComposerInputChange(current, nextInput) {
1128
1243
  const currentShowsCommands = shouldShowCommandPalette(current);
@@ -1134,20 +1249,19 @@ export function shouldRemountLiveFrameForComposerInputChange(current, nextInput)
1134
1249
  }
1135
1250
  export function applySlashCommandSuggestion(currentInput, suggestion) {
1136
1251
  const token = getInputCommandToken(currentInput);
1252
+ const command = isSkillSlashCommand(suggestion) ? `${suggestion.command} ` : suggestion.command;
1137
1253
  if (!token) {
1138
- return { cursor: suggestion.command.length, input: suggestion.command };
1254
+ return { cursor: command.length, input: command };
1139
1255
  }
1140
1256
  const tokenStart = currentInput.indexOf(token);
1141
1257
  const before = currentInput.slice(0, tokenStart);
1142
1258
  const after = currentInput.slice(tokenStart + token.length);
1259
+ const inserted = after.startsWith(' ') ? suggestion.command : command;
1143
1260
  return {
1144
- cursor: before.length + suggestion.command.length,
1145
- input: `${before}${suggestion.command}${after}`,
1261
+ cursor: before.length + inserted.length,
1262
+ input: `${before}${inserted}${after}`,
1146
1263
  };
1147
1264
  }
1148
- export function isExactSlashCommandToken(token) {
1149
- return SLASH_COMMANDS.some((command) => command.command === token);
1150
- }
1151
1265
  export function insertAtCursor(state, text) {
1152
1266
  const before = state.input.slice(0, state.cursor);
1153
1267
  const after = state.input.slice(state.cursor);
@@ -1226,38 +1340,84 @@ export function navigatePromptHistory(state, direction) {
1226
1340
  promptHistoryCursor: nextCursor,
1227
1341
  };
1228
1342
  }
1229
- function getDefaultApprovalCursor() {
1230
- const denyIndex = APPROVAL_OPTIONS.findIndex((option) => option.value === 'n');
1231
- return denyIndex === -1 ? 0 : denyIndex;
1232
- }
1233
- export function getNextApprovalCursor(currentIndex, direction) {
1234
- return (currentIndex + direction + APPROVAL_OPTIONS.length) % APPROVAL_OPTIONS.length;
1235
- }
1236
- export function getApprovalChoiceForCursor(cursor) {
1237
- return (APPROVAL_OPTIONS[Math.min(Math.max(cursor, 0), APPROVAL_OPTIONS.length - 1)]
1238
- ?.value ?? 'n');
1239
- }
1240
- export function resolveApprovalChoiceFromInput(input) {
1241
- const normalizedInput = String(input ?? '').trim().toLowerCase();
1242
- if (normalizedInput === 'y')
1243
- return 'y';
1244
- if (normalizedInput === 'a')
1245
- return 'a';
1246
- if (normalizedInput === 'n')
1247
- return 'n';
1248
- 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);
1249
1374
  }
1250
1375
  export function buildModelPickerOptions(currentModelId, serverModels) {
1251
- 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) => ({
1252
1381
  id: model.id,
1253
- label: model.label,
1382
+ label: model.auto ? autoOptionLabel(model.label) : model.label,
1254
1383
  publicId: model.id,
1255
1384
  costRating: model.costRating,
1256
1385
  current: model.id === currentModelId,
1257
- disabled: false,
1258
- 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,
1259
1389
  }));
1260
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
+ }
1261
1421
  function getDefaultModelPickerIndex(currentModelId, serverModels) {
1262
1422
  const options = buildModelPickerOptions(currentModelId, serverModels);
1263
1423
  const currentIndex = options.findIndex((option) => option.id === currentModelId);
@@ -1288,7 +1448,7 @@ async function saveSessionBoth({ serverSessionClient, session, }) {
1288
1448
  saveSessionState(session);
1289
1449
  await serverSessionClient.save(session);
1290
1450
  }
1291
- 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, }) {
1292
1452
  if (process.stdin.isTTY !== true) {
1293
1453
  throw new Error('stdin is not a terminal');
1294
1454
  }
@@ -1296,17 +1456,23 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1296
1456
  throw new Error('stdout is not a terminal');
1297
1457
  }
1298
1458
  let fatalError = null;
1459
+ let signedOut = false;
1299
1460
  await withTuiMode(async () => {
1300
1461
  setBackgroundJobSession(session.sessionId);
1301
1462
  setScratchSession(session.sessionId);
1463
+ setImageStoreSession(session.sessionId);
1302
1464
  setTodoSession(session.sessionId);
1303
- const store = createShellStore(createInitialShellState(session, serverModels, debugUi));
1465
+ const store = createShellStore({
1466
+ ...createInitialShellState(session, serverModels, debugUi, authConfig.serverUrl),
1467
+ plan,
1468
+ });
1304
1469
  store.replaceTranscript(createSessionTranscript(session));
1305
1470
  let currentServerModels = serverModels;
1306
1471
  let sessionAutoYes = session.autoYes;
1307
1472
  let resolveDone = null;
1308
- let resolveApprovalChoice = null;
1473
+ let resolvePermissionDecision = null;
1309
1474
  let resolveSudoPassword = null;
1475
+ let pendingUserInput = null;
1310
1476
  let cleanupSudoPasswordPrompt = null;
1311
1477
  let sudoPasswordBuffer = '';
1312
1478
  const bridge = createRatatuiBridge();
@@ -1321,8 +1487,13 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1321
1487
  let tuiReady = false;
1322
1488
  let lastTurnStartedAt = null;
1323
1489
  let latestUsageSummary = null;
1490
+ const usageNotice = createUsageNoticeTracker();
1324
1491
  let pendingTurnEntries = [];
1325
1492
  let activeTurnAbort = null;
1493
+ let activeTurnImageAttachments = [];
1494
+ let activeServerTurnId = null;
1495
+ let unacknowledged = new Map();
1496
+ const blockedRows = new WeakMap();
1326
1497
  let newConversationInFlight = false;
1327
1498
  let todosTouchedThisTurn = false;
1328
1499
  const syncTodosState = () => {
@@ -1332,6 +1503,36 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1332
1503
  let exitCtrlCArmed = false;
1333
1504
  let exitCtrlCTimer = null;
1334
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
+ };
1335
1536
  const done = new Promise((resolve) => {
1336
1537
  resolveDone = resolve;
1337
1538
  });
@@ -1345,15 +1546,17 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1345
1546
  void remountTui();
1346
1547
  }, 0);
1347
1548
  };
1348
- const showTransientStatus = (status) => {
1549
+ const showTransientStatus = (transientStatus) => {
1349
1550
  if (transientStatusTimer) {
1350
1551
  clearTimeout(transientStatusTimer);
1351
1552
  transientStatusTimer = null;
1352
1553
  }
1353
- store.update((current) => ({ ...current, status }));
1554
+ store.update((current) => ({ ...current, transientStatus }));
1354
1555
  transientStatusTimer = setTimeout(() => {
1355
1556
  transientStatusTimer = null;
1356
- store.update((current) => current.status === status ? { ...current, status: 'Ready' } : current);
1557
+ store.update((current) => current.transientStatus === transientStatus
1558
+ ? { ...current, transientStatus: null }
1559
+ : current);
1357
1560
  }, 2500);
1358
1561
  };
1359
1562
  const terminalTitle = createTerminalTitleController({
@@ -1366,14 +1569,43 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1366
1569
  busy: state.busy,
1367
1570
  });
1368
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
+ };
1369
1602
  const renderCurrentFrame = () => {
1370
1603
  if (!tuiReady)
1371
1604
  return;
1372
1605
  const state = store.getState();
1373
1606
  syncTerminalTitle();
1374
- const elapsedSeconds = state.busySince
1375
- ? Math.max(0, Math.floor((Date.now() - state.busySince) / 1000))
1376
- : 0;
1607
+ syncAttention();
1608
+ const elapsedSeconds = busyElapsedSeconds(state, Date.now());
1377
1609
  bridge.render(buildTuiFrame(state, terminalCols, terminalRows, spinnerFrame, elapsedSeconds, Date.now()));
1378
1610
  };
1379
1611
  const remountTui = async () => {
@@ -1499,15 +1731,16 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1499
1731
  }
1500
1732
  };
1501
1733
  const dismissPendingApproval = () => {
1502
- if (!resolveApprovalChoice)
1734
+ if (!resolvePermissionDecision)
1503
1735
  return;
1504
- const pendingResolve = resolveApprovalChoice;
1505
- resolveApprovalChoice = null;
1506
- pendingResolve('n');
1736
+ const pendingResolve = resolvePermissionDecision;
1737
+ resolvePermissionDecision = null;
1738
+ pendingResolve({ kind: 'deny' });
1507
1739
  store.update((current) => ({
1508
- ...current,
1509
- approvalCursor: getDefaultApprovalCursor(),
1740
+ ...resumeBusyClock(current, Date.now()),
1741
+ approvalCursor: 0,
1510
1742
  approvalPrompt: null,
1743
+ approvalScrollOffset: 0,
1511
1744
  }));
1512
1745
  };
1513
1746
  const dismissPendingSudoPassword = () => {
@@ -1520,21 +1753,40 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1520
1753
  sudoPasswordBuffer = '';
1521
1754
  pendingResolve(null);
1522
1755
  store.update((current) => ({
1523
- ...current,
1756
+ ...resumeBusyClock(current, Date.now()),
1524
1757
  sudoPrompt: null,
1525
1758
  }));
1526
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
+ };
1527
1775
  const cancelActiveTurn = () => {
1528
1776
  if (!store.getState().busy || newConversationInFlight)
1529
1777
  return;
1530
1778
  disarmExitConfirm();
1531
1779
  dismissPendingApproval();
1532
1780
  dismissPendingSudoPassword();
1781
+ dismissPendingUserInput();
1533
1782
  activeTurnGeneration += 1;
1783
+ resetThinkingPacer();
1534
1784
  activeTurnAbort?.abort();
1535
1785
  activeTurnAbort = null;
1536
1786
  cancelActiveCommand();
1537
1787
  const queued = store.getState().queuedMessage;
1788
+ const restoredAttachments = composerAttachmentsAfterCancel(queued ? queued.imageAttachments : [], activeTurnImageAttachments);
1789
+ activeTurnImageAttachments = [];
1538
1790
  const cancelledEntries = [
1539
1791
  ...takePendingTurnEntries(),
1540
1792
  {
@@ -1548,20 +1800,23 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1548
1800
  activeTurnInput: '',
1549
1801
  activeTurnInputPreformatted: false,
1550
1802
  busy: false,
1803
+ busyPausedAt: null,
1551
1804
  busySince: null,
1552
1805
  commandLog: [],
1553
1806
  cursor: queued ? queued.body.length : current.cursor,
1554
- imageAttachments: queued ? queued.imageAttachments : [],
1807
+ imageAttachments: restoredAttachments,
1555
1808
  input: queued ? queued.body : current.input,
1556
1809
  pastedChunks: queued ? queued.pastedChunks : current.pastedChunks,
1557
1810
  promptHistoryCursor: queued ? null : current.promptHistoryCursor,
1558
1811
  promptHistoryDraft: queued ? '' : current.promptHistoryDraft,
1559
1812
  queuedMessage: null,
1813
+ recoveryStatus: '',
1560
1814
  status: 'Ready',
1561
1815
  thinkingTitle: '',
1562
1816
  thinkingNotes: [],
1817
+ turnMessages: [],
1563
1818
  workingTools: [],
1564
- tokenUsage: formatClientTokenUsage(current.busySince == null ? null : Date.now() - current.busySince, latestUsageSummary),
1819
+ tokenUsage: formatClientTokenUsage(busyElapsedMs(current, Date.now()), latestUsageSummary),
1565
1820
  }));
1566
1821
  appendStaticEntries(cancelledEntries);
1567
1822
  lastTurnStartedAt = null;
@@ -1576,6 +1831,7 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1576
1831
  autoYes: sessionAutoYes,
1577
1832
  commandCursor: 0,
1578
1833
  currentModelId: session.modelId,
1834
+ reasoningEffort: projectModelEffort(readProjectModelEfforts(session.rootDir, authConfig.serverUrl, session.env), session.modelId),
1579
1835
  sessionId: session.sessionId,
1580
1836
  modelPickerIndex: current.modelPickerOpen
1581
1837
  ? getDefaultModelPickerIndex(session.modelId, current.serverModels)
@@ -1599,6 +1855,9 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1599
1855
  setAgentMode(nextAgentMode(session.agentMode));
1600
1856
  scheduleLiveFrameRemount();
1601
1857
  };
1858
+ const reportAgentModeLocked = () => {
1859
+ showTransientStatus(AGENT_MODE_LOCKED_STATUS);
1860
+ };
1602
1861
  const clearLiveFrameRemountTimer = () => {
1603
1862
  if (!liveFrameRemountTimer)
1604
1863
  return;
@@ -1647,6 +1906,7 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1647
1906
  }
1648
1907
  dismissPendingApproval();
1649
1908
  dismissPendingSudoPassword();
1909
+ dismissPendingUserInput();
1650
1910
  exiting = true;
1651
1911
  killAllBackgroundJobs();
1652
1912
  store.update((current) => ({
@@ -1712,7 +1972,7 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1712
1972
  cleanupSudoPasswordPrompt = null;
1713
1973
  }
1714
1974
  store.update((current) => ({
1715
- ...current,
1975
+ ...pauseBusyClock(current, Date.now()),
1716
1976
  sudoPrompt: {
1717
1977
  command,
1718
1978
  passwordLength: 0,
@@ -1732,7 +1992,7 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1732
1992
  cleanupSudoPasswordPrompt = null;
1733
1993
  sudoPasswordBuffer = '';
1734
1994
  store.update((current) => ({
1735
- ...current,
1995
+ ...resumeBusyClock(current, Date.now()),
1736
1996
  sudoPrompt: null,
1737
1997
  status: current.sudoPrompt?.returnStatus ?? current.status,
1738
1998
  }));
@@ -1746,7 +2006,7 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1746
2006
  cleanupSudoPasswordPrompt = null;
1747
2007
  sudoPasswordBuffer = '';
1748
2008
  store.update((current) => ({
1749
- ...current,
2009
+ ...resumeBusyClock(current, Date.now()),
1750
2010
  sudoPrompt: null,
1751
2011
  status: current.sudoPrompt?.returnStatus ?? current.status,
1752
2012
  }));
@@ -1766,38 +2026,95 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1766
2026
  : null,
1767
2027
  }));
1768
2028
  };
1769
- const openApprovalPrompt = (title, body, options = {}) => new Promise((resolve) => {
1770
- if (exiting) {
1771
- 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);
1772
2034
  return;
1773
2035
  }
1774
- resolveApprovalChoice = resolve;
2036
+ const onAbort = () => dismissPendingUserInput();
2037
+ pendingUserInput = {
2038
+ questions,
2039
+ resolve,
2040
+ reject,
2041
+ signal,
2042
+ onAbort,
2043
+ };
2044
+ signal?.addEventListener('abort', onAbort, { once: true });
1775
2045
  store.update((current) => ({
1776
- ...current,
1777
- approvalCursor: getDefaultApprovalCursor(),
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);
2077
+ return;
2078
+ }
2079
+ const onAbort = () => dismissPendingApproval();
2080
+ signal?.addEventListener('abort', onAbort, { once: true });
2081
+ resolvePermissionDecision = (decision) => {
2082
+ signal?.removeEventListener('abort', onAbort);
2083
+ resolve(decision);
2084
+ };
2085
+ store.update((current) => ({
2086
+ ...pauseBusyClock(current, Date.now()),
2087
+ ...closedJobsPickerFields(current),
2088
+ approvalCursor: getDefaultApprovalCursor(request.options.length),
2089
+ approvalOpenedAt: Date.now(),
2090
+ approvalScrollOffset: 0,
1778
2091
  approvalPrompt: {
1779
- title,
1780
- body,
1781
- diffPreview: options.diff && options.filePath
1782
- ? parseDiffPreview(options.diff)
2092
+ title: request.title,
2093
+ body: request.body,
2094
+ diffPreview: request.diff && request.filePath
2095
+ ? parseDiffPreview(request.diff)
1783
2096
  : undefined,
1784
- filePath: options.filePath,
1785
- returnStatus: current.status,
2097
+ filePath: request.filePath,
2098
+ options: request.options,
2099
+ returnStatus: statusBehindJobsPicker(current),
1786
2100
  },
1787
- status: title,
2101
+ status: request.title,
1788
2102
  }));
1789
2103
  });
1790
- const handleInlineApprovalChoice = async (choice) => {
2104
+ const handleInlineApprovalChoice = async (index) => {
1791
2105
  const current = store.getState();
1792
- const pendingResolve = resolveApprovalChoice;
1793
- resolveApprovalChoice = null;
2106
+ const options = current.approvalPrompt?.options ?? [];
2107
+ const chosen = options[index]?.decision ?? { kind: 'deny' };
2108
+ const pendingResolve = resolvePermissionDecision;
2109
+ resolvePermissionDecision = null;
1794
2110
  store.update((next) => ({
1795
- ...next,
1796
- approvalCursor: getDefaultApprovalCursor(),
2111
+ ...resumeBusyClock(next, Date.now()),
2112
+ approvalCursor: getDefaultApprovalCursor(options.length),
1797
2113
  approvalPrompt: null,
2114
+ approvalScrollOffset: 0,
1798
2115
  status: current.approvalPrompt?.returnStatus ?? next.status,
1799
2116
  }));
1800
- pendingResolve?.(choice);
2117
+ pendingResolve?.(chosen);
1801
2118
  };
1802
2119
  const refreshServerModels = async () => {
1803
2120
  currentServerModels = await models.fetchServerModels({ config: authConfig });
@@ -1816,15 +2133,19 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1816
2133
  input: '',
1817
2134
  modelPickerIndex: getDefaultModelPickerIndex(current.currentModelId, fresh.models),
1818
2135
  modelPickerOpen: true,
2136
+ modelPickerEfforts: readProjectModelEfforts(session.rootDir, authConfig.serverUrl, session.env),
1819
2137
  status: 'Select a model',
1820
2138
  }));
1821
2139
  };
1822
- const switchToModel = async (modelId) => {
1823
- const requested = Number(modelId);
1824
- const fresh = currentServerModels.models.some((model) => model.id === requested)
1825
- ? currentServerModels
1826
- : await refreshServerModels();
2140
+ const switchToModel = async (modelId, effort) => {
2141
+ const fresh = await modelsForSwitch(Number(modelId), currentServerModels, refreshServerModels);
1827
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
+ }
1828
2149
  session.modelId = selected;
1829
2150
  models.updateSelectedModelCache({
1830
2151
  config: authConfig,
@@ -1835,29 +2156,42 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1835
2156
  return;
1836
2157
  syncShellStateFromSession();
1837
2158
  appendStaticEntry({
1838
- 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.'}`,
1839
2162
  kind: 'system',
1840
2163
  title: 'Model',
1841
2164
  });
1842
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
+ };
1843
2176
  const openJobsPicker = () => {
2177
+ if (store.getState().jobsPickerOpen)
2178
+ return;
1844
2179
  syncBackgroundJobsState();
1845
2180
  store.update((current) => ({
1846
2181
  ...current,
1847
2182
  commandCursor: 0,
1848
- cursor: 0,
1849
- input: '',
1850
2183
  jobsPickerExpandedId: null,
1851
2184
  jobsPickerIndex: 0,
1852
2185
  jobsPickerOpen: true,
2186
+ jobsPickerReturnStatus: current.status,
1853
2187
  status: 'Background jobs',
1854
2188
  }));
2189
+ scheduleLiveFrameRemount();
1855
2190
  };
1856
2191
  const appendJobOutputEntry = async (jobId) => {
1857
2192
  const id = jobId.trim();
1858
2193
  await collectBackgroundJobUiOutputMutations({
1859
2194
  session,
1860
- projectIndex,
1861
2195
  jobId: id,
1862
2196
  });
1863
2197
  const job = listBackgroundJobs().find((candidate) => candidate.id === id);
@@ -1873,7 +2207,7 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1873
2207
  body: `${dropped}${buffered.output || '(no output captured)'}`,
1874
2208
  kind: 'system',
1875
2209
  preformatted: true,
1876
- title: `${job.id} output — ${truncate(job.command, 80)}`,
2210
+ title: `${job.id} output - ${truncate(job.command, 80)}`,
1877
2211
  });
1878
2212
  };
1879
2213
  const selectedJobsPickerId = () => {
@@ -1883,32 +2217,51 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1883
2217
  const index = Math.min(Math.max(current.jobsPickerIndex, 0), current.backgroundJobs.length - 1);
1884
2218
  return current.backgroundJobs[index]?.id ?? null;
1885
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
+ };
1886
2231
  const handleJobsPickerOutput = async () => {
1887
2232
  const jobId = selectedJobsPickerId();
1888
2233
  if (!jobId)
1889
2234
  return;
1890
- await collectBackgroundJobUiOutputMutations({
1891
- session,
1892
- projectIndex,
1893
- jobId,
1894
- });
1895
- syncBackgroundJobsState();
2235
+ if (store.getState().busy) {
2236
+ deferredJobMutationIds.add(jobId);
2237
+ }
2238
+ else {
2239
+ await collectBackgroundJobUiOutputMutations({
2240
+ session,
2241
+ jobId,
2242
+ });
2243
+ }
1896
2244
  store.update((current) => ({
1897
2245
  ...current,
1898
2246
  jobsPickerExpandedId: current.jobsPickerExpandedId === jobId ? null : jobId,
1899
2247
  }));
2248
+ syncBackgroundJobsState();
1900
2249
  };
1901
2250
  const handleJobsPickerKill = async () => {
1902
2251
  const jobId = selectedJobsPickerId();
1903
2252
  if (!jobId)
1904
2253
  return;
1905
2254
  const killed = await killBackgroundJob(jobId);
1906
- await collectBackgroundJobUiKillMutations({
1907
- session,
1908
- projectIndex,
1909
- jobId,
1910
- result: killed,
1911
- });
2255
+ if (store.getState().busy) {
2256
+ deferredJobMutationIds.add(jobId);
2257
+ }
2258
+ else {
2259
+ await collectBackgroundJobUiKillMutations({
2260
+ session,
2261
+ jobId,
2262
+ result: killed,
2263
+ });
2264
+ }
1912
2265
  syncBackgroundJobsState();
1913
2266
  if (!killed.ok) {
1914
2267
  appendError(killed.error ?? 'Background job kill failed.');
@@ -1926,6 +2279,13 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1926
2279
  const options = buildModelPickerOptions(current.currentModelId, current.serverModels);
1927
2280
  const selectedIndex = Math.min(current.modelPickerIndex, Math.max(options.length - 1, 0));
1928
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
+ }
1929
2289
  store.update((next) => ({
1930
2290
  ...next,
1931
2291
  modelPickerOpen: false,
@@ -1939,16 +2299,8 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1939
2299
  });
1940
2300
  return;
1941
2301
  }
1942
- if (selected.id === current.currentModelId) {
1943
- appendStaticEntry({
1944
- body: `Already using ${formatModelLabel(selected.id, current.serverModels)}.`,
1945
- kind: 'system',
1946
- title: 'Model',
1947
- });
1948
- return;
1949
- }
1950
2302
  try {
1951
- await switchToModel(selected.id);
2303
+ await switchToModel(selected.id, projectModelEffort(current.modelPickerEfforts ?? {}, selected.id));
1952
2304
  }
1953
2305
  catch (error) {
1954
2306
  if (exitForAuthenticationError(error))
@@ -2002,15 +2354,24 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2002
2354
  store.update((next) => ({
2003
2355
  ...next,
2004
2356
  busy: true,
2357
+ busyPausedAt: null,
2005
2358
  busySince: resumeStartedAt,
2006
2359
  clockNow: resumeStartedAt,
2007
2360
  status: 'Loading session...',
2008
2361
  }));
2009
2362
  try {
2010
2363
  const snapshot = await loadInteractiveSession(selected.id);
2011
- 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
+ });
2012
2372
  setBackgroundJobSession(session.sessionId);
2013
2373
  setScratchSession(session.sessionId);
2374
+ setImageStoreSession(session.sessionId);
2014
2375
  syncBackgroundJobsState();
2015
2376
  setTodoSession(session.sessionId);
2016
2377
  syncTodosState();
@@ -2018,6 +2379,7 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2018
2379
  store.update((next) => ({
2019
2380
  ...next,
2020
2381
  busy: false,
2382
+ busyPausedAt: null,
2021
2383
  busySince: null,
2022
2384
  resumePickerFilter: '',
2023
2385
  resumePickerIndex: 0,
@@ -2031,6 +2393,15 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2031
2393
  kind: 'system',
2032
2394
  title: 'Session',
2033
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
+ : []),
2034
2405
  ...buildTranscriptFromSessionHistory(session.history),
2035
2406
  ]);
2036
2407
  await remountTui();
@@ -2041,6 +2412,7 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2041
2412
  store.update((next) => ({
2042
2413
  ...next,
2043
2414
  busy: false,
2415
+ busyPausedAt: null,
2044
2416
  busySince: null,
2045
2417
  resumePickerFilter: '',
2046
2418
  resumePickerIndex: 0,
@@ -2064,28 +2436,284 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2064
2436
  }));
2065
2437
  await handleSubmit(queued.body);
2066
2438
  };
2067
- const handleSubmit = async (rawInput) => {
2068
- 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;
2069
2674
  const expanded = chunks.length
2070
2675
  ? expandPastedChunks(String(rawInput ?? ''), chunks)
2071
2676
  : String(rawInput ?? '');
2072
2677
  const input = expanded.trim();
2073
2678
  const preformatted = chunks.length > 0;
2679
+ refreshSkillCommands();
2074
2680
  if (store.getState().busy) {
2075
2681
  if (!input || exiting)
2076
2682
  return;
2077
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
+ }
2078
2704
  appendTurnAwareEntry({
2079
- 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.',
2080
2707
  kind: 'system',
2081
2708
  title: 'Queued',
2082
2709
  });
2083
2710
  return;
2084
2711
  }
2085
2712
  const pending = store.getState();
2713
+ const body = String(rawInput ?? '');
2086
2714
  const snapshot = {
2087
- body: String(rawInput ?? ''),
2088
- imageAttachments: pending.imageAttachments,
2715
+ body,
2716
+ imageAttachments: pending.imageAttachments.filter((attachment) => body.includes(`[Image #${attachment.index}]`)),
2089
2717
  pastedChunks: pending.pastedChunks,
2090
2718
  };
2091
2719
  scheduleLiveFrameRemount();
@@ -2100,19 +2728,24 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2100
2728
  }));
2101
2729
  return;
2102
2730
  }
2103
- const imageAttachments = store.getState().imageAttachments;
2104
- scheduleLiveFrameRemount();
2105
- store.update((current) => ({
2106
- ...current,
2107
- cursor: 0,
2108
- input: '',
2109
- pastedChunks: [],
2110
- promptHistory: appendPromptToHistory(current.promptHistory, input),
2111
- promptHistoryCursor: null,
2112
- promptHistoryDraft: '',
2113
- }));
2114
- appendPromptHistory(input);
2115
- 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) {
2116
2749
  store.update((current) => ({ ...current, imageAttachments: [] }));
2117
2750
  return;
2118
2751
  }
@@ -2120,6 +2753,47 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2120
2753
  requestExit();
2121
2754
  return;
2122
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
+ }
2123
2797
  if (input === '/help') {
2124
2798
  appendStaticEntry({
2125
2799
  body: formatInteractiveHelpText(),
@@ -2136,6 +2810,15 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2136
2810
  });
2137
2811
  return;
2138
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
+ }
2139
2822
  if (input === '/jobs' || input.startsWith('/jobs ')) {
2140
2823
  const jobsArgs = input.slice('/jobs'.length).trim();
2141
2824
  if (!jobsArgs) {
@@ -2148,7 +2831,6 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2148
2831
  const killed = await killBackgroundJob(jobId);
2149
2832
  await collectBackgroundJobUiKillMutations({
2150
2833
  session,
2151
- projectIndex,
2152
2834
  jobId,
2153
2835
  result: killed,
2154
2836
  });
@@ -2170,7 +2852,7 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2170
2852
  return;
2171
2853
  }
2172
2854
  appendStaticEntry({
2173
- 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',
2174
2856
  kind: 'system',
2175
2857
  title: 'Background jobs',
2176
2858
  });
@@ -2266,6 +2948,7 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2266
2948
  store.update((current) => ({
2267
2949
  ...current,
2268
2950
  busy: true,
2951
+ busyPausedAt: null,
2269
2952
  busySince: Date.now(),
2270
2953
  imageAttachments: [],
2271
2954
  queuedMessage: null,
@@ -2276,6 +2959,7 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2276
2959
  store.update((current) => ({
2277
2960
  ...current,
2278
2961
  busy: false,
2962
+ busyPausedAt: null,
2279
2963
  busySince: null,
2280
2964
  status: 'Ready',
2281
2965
  }));
@@ -2285,6 +2969,7 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2285
2969
  startNewConversation(session);
2286
2970
  setBackgroundJobSession(session.sessionId);
2287
2971
  setScratchSession(session.sessionId);
2972
+ setImageStoreSession(session.sessionId);
2288
2973
  setTodoSession(session.sessionId);
2289
2974
  clearTodos();
2290
2975
  syncBackgroundJobsState();
@@ -2303,6 +2988,7 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2303
2988
  store.update((current) => ({
2304
2989
  ...current,
2305
2990
  busy: false,
2991
+ busyPausedAt: null,
2306
2992
  busySince: null,
2307
2993
  status: 'Ready',
2308
2994
  }));
@@ -2310,15 +2996,18 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2310
2996
  await flushQueuedMessage();
2311
2997
  return;
2312
2998
  }
2999
+ jobWait.turnStarted(jobFollowUp);
2313
3000
  latestUsageSummary = null;
2314
3001
  disarmExitConfirm();
3002
+ unacknowledged = new Map();
2315
3003
  const turnStartedAt = Date.now();
2316
3004
  const turnGeneration = ++activeTurnGeneration;
2317
3005
  const turnAbort = new AbortController();
2318
3006
  activeTurnAbort = turnAbort;
2319
3007
  lastTurnStartedAt = turnStartedAt;
2320
3008
  todosTouchedThisTurn = false;
2321
- clearTodos();
3009
+ if (!jobFollowUp)
3010
+ clearTodos();
2322
3011
  syncTodosState();
2323
3012
  const userEntry = {
2324
3013
  body: input,
@@ -2327,31 +3016,58 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2327
3016
  title: 'You',
2328
3017
  };
2329
3018
  pendingTurnEntries = [];
2330
- queueTurnEntry(userEntry);
3019
+ if (!jobFollowUp)
3020
+ queueTurnEntry(userEntry);
3021
+ resetThinkingPacer();
3022
+ activeTurnImageAttachments = imageAttachments;
2331
3023
  store.update((current) => ({
2332
3024
  ...current,
2333
3025
  activeTurnInput: input,
2334
3026
  activeTurnInputPreformatted: preformatted,
2335
3027
  analyzingImages: 0,
3028
+ generatingImage: false,
2336
3029
  busy: true,
3030
+ busyPausedAt: null,
2337
3031
  busySince: turnStartedAt,
2338
3032
  clockNow: turnStartedAt,
3033
+ recoveryStatus: '',
2339
3034
  status: 'Running turn...',
3035
+ usageNotice: null,
2340
3036
  thinkingTitle: '',
2341
3037
  thinkingNotes: [],
2342
3038
  transcriptScrollOffset: 0,
2343
3039
  tokenUsage: formatClientTokenUsage(0, latestUsageSummary),
2344
3040
  turnCounter: current.turnCounter + 1,
3041
+ turnMessages: [],
2345
3042
  workingTools: [],
2346
3043
  }));
2347
3044
  try {
2348
3045
  const result = await chat.sendServerUserMessage({
2349
3046
  config: authConfig,
2350
- projectIndex,
2351
3047
  session,
2352
3048
  input,
3049
+ jobFollowUp,
2353
3050
  imageAttachments,
2354
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
+ },
2355
3071
  });
2356
3072
  if (turnGeneration !== activeTurnGeneration)
2357
3073
  return;
@@ -2360,6 +3076,7 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2360
3076
  if (!(await saveActiveSession()))
2361
3077
  return;
2362
3078
  syncShellStateFromSession();
3079
+ activeTurnImageAttachments = [];
2363
3080
  store.update((current) => ({
2364
3081
  ...current,
2365
3082
  activeTurnInput: '',
@@ -2368,6 +3085,7 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2368
3085
  commandLog: [],
2369
3086
  imageAttachments: [],
2370
3087
  status: result.waitingForApproval ? 'Awaiting approval' : 'Finishing response...',
3088
+ usageNotice: null,
2371
3089
  thinkingTitle: '',
2372
3090
  thinkingNotes: [],
2373
3091
  tokenUsage: formatClientTokenUsage(Date.now() - turnStartedAt, latestUsageSummary),
@@ -2395,10 +3113,14 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2395
3113
  store.update((current) => ({
2396
3114
  ...current,
2397
3115
  busy: false,
3116
+ busyPausedAt: null,
2398
3117
  busySince: null,
3118
+ recoveryStatus: '',
2399
3119
  status: result.waitingForApproval ? 'Awaiting approval' : 'Ready',
2400
3120
  tokenUsage: formatClientTokenUsage(Date.now() - turnStartedAt, latestUsageSummary),
2401
3121
  }));
3122
+ jobWait.turnEnded(result.waitingForJobs);
3123
+ recoverUnacknowledgedMessages();
2402
3124
  await flushQueuedMessage();
2403
3125
  }
2404
3126
  catch (error) {
@@ -2411,15 +3133,31 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2411
3133
  const cancelled = isTurnCancelledError(error);
2412
3134
  if (exitForAuthenticationError(error))
2413
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;
2414
3143
  store.update((current) => ({
2415
3144
  ...current,
3145
+ ...(restoresPrompt
3146
+ ? { cursor: String(rawInput ?? '').length, input: String(rawInput ?? ''), pastedChunks: chunks }
3147
+ : {}),
2416
3148
  activeTurnInput: '',
2417
3149
  activeTurnInputPreformatted: false,
2418
3150
  busy: false,
3151
+ busyPausedAt: null,
2419
3152
  busySince: null,
2420
3153
  commandLog: [],
2421
- imageAttachments: [],
2422
- status: cancelled ? 'Ready' : 'Turn failed',
3154
+ imageAttachments: failedTurnAttachments,
3155
+ recoveryStatus: '',
3156
+ status: cancelled
3157
+ ? 'Ready'
3158
+ : quotaNotice
3159
+ ? quotaNotice.title
3160
+ : 'Turn failed',
2423
3161
  thinkingTitle: '',
2424
3162
  thinkingNotes: [],
2425
3163
  tokenUsage: formatClientTokenUsage(Date.now() - turnStartedAt, latestUsageSummary),
@@ -2438,12 +3176,25 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2438
3176
  if (!(await saveActiveSession()))
2439
3177
  return;
2440
3178
  }
3179
+ else if (quotaNotice) {
3180
+ appendStaticEntries([
3181
+ ...turnEntries,
3182
+ {
3183
+ body: quotaNotice.body,
3184
+ kind: 'system',
3185
+ title: quotaNotice.title,
3186
+ },
3187
+ ]);
3188
+ }
2441
3189
  else {
2442
3190
  appendStaticEntries(turnEntries);
2443
3191
  appendError(error.message);
3192
+ appendStaticEntries(buildTurnFailureHintEntries(cancelled));
2444
3193
  }
2445
3194
  await remountTui();
2446
- if (!cancelled && turnGeneration === activeTurnGeneration) {
3195
+ const autoSubmits = !cancelled && isTurnOutcomeKnown(error);
3196
+ recoverUnacknowledgedMessages(autoSubmits);
3197
+ if (autoSubmits && turnGeneration === activeTurnGeneration) {
2447
3198
  await flushQueuedMessage();
2448
3199
  }
2449
3200
  }
@@ -2453,13 +3204,56 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2453
3204
  }
2454
3205
  if (turnGeneration === activeTurnGeneration) {
2455
3206
  lastTurnStartedAt = null;
3207
+ activeServerTurnId = null;
2456
3208
  }
3209
+ recoverUnacknowledgedMessages();
3210
+ await drainDeferredJobMutations();
3211
+ if (turnGeneration === activeTurnGeneration)
3212
+ scheduleJobFollowUp();
3213
+ }
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 }));
2457
3226
  }
2458
3227
  };
2459
3228
  session.onImageAnalysis = (activeImageCount) => {
2460
3229
  store.update((current) => ({
2461
3230
  ...current,
2462
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,
2463
3257
  }));
2464
3258
  };
2465
3259
  session.onStatus = (message) => {
@@ -2467,16 +3261,18 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2467
3261
  store.update((current) => ({
2468
3262
  ...current,
2469
3263
  status: message,
2470
- thinkingTitle: panel?.title ?? current.thinkingTitle,
2471
- thinkingNotes: panel?.notes ?? current.thinkingNotes,
2472
- tokenUsage: formatClientTokenUsage(current.busySince == null ? null : Date.now() - current.busySince, latestUsageSummary),
3264
+ tokenUsage: formatClientTokenUsage(busyElapsedMs(current, Date.now()), latestUsageSummary),
2473
3265
  }));
3266
+ queueThinkingUpdate({
3267
+ title: panel ? panel.title : liveStatusPanelTitle(message),
3268
+ notes: panel ? panel.notes : [],
3269
+ });
2474
3270
  };
2475
3271
  session.onContextLog = (message) => {
2476
3272
  store.update((current) => ({
2477
3273
  ...current,
2478
3274
  contextStatus: message,
2479
- tokenUsage: formatClientTokenUsage(current.busySince == null ? null : Date.now() - current.busySince, latestUsageSummary),
3275
+ tokenUsage: formatClientTokenUsage(busyElapsedMs(current, Date.now()), latestUsageSummary),
2480
3276
  }));
2481
3277
  };
2482
3278
  session.onToolEvent = (event) => {
@@ -2491,31 +3287,27 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2491
3287
  if (isFileChangeTool(event.call.name)) {
2492
3288
  const entry = buildFileChangeEntry(event);
2493
3289
  store.appendWorkingTool(entry);
2494
- appendTurnAwareEntry(entry);
3290
+ const result = event.result;
3291
+ if (result?.ok === true || result?.skipped === true)
3292
+ appendTurnAwareEntry(entry);
2495
3293
  return;
2496
3294
  }
2497
- store.appendWorkingTool(buildWorkingToolEntry(event));
2498
- };
2499
- const jobDetailLines = (jobId) => {
2500
- const buffered = getJobBufferedOutput(jobId);
2501
- if (!buffered)
2502
- return [];
2503
- const lines = buffered.output
2504
- .replace(/\r\n/g, '\n')
2505
- .replace(/\r/g, '\n')
2506
- .split('\n')
2507
- .filter((line) => line.trim().length > 0);
2508
- const visible = lines.slice(-20);
2509
- return buffered.droppedChars > 0
2510
- ? [
2511
- `... (${buffered.droppedChars} chars of older output dropped) ...`,
2512
- ...visible,
2513
- ]
2514
- : visible;
3295
+ store.appendWorkingTool(buildWorkingToolEntry(event, session.mcp?.label(event.call.name)));
2515
3296
  };
2516
3297
  const syncBackgroundJobsState = () => {
3298
+ const expandedId = store.getState().jobsPickerExpandedId;
2517
3299
  const jobsForDisplay = listBackgroundJobs().map((job) => {
2518
- 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 ?? []);
2519
3311
  return {
2520
3312
  id: job.id,
2521
3313
  command: job.command,
@@ -2524,8 +3316,8 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2524
3316
  startedAt: job.startedAt,
2525
3317
  endedAt: job.endedAt,
2526
3318
  firstOutputLine: preview?.firstLine ?? '',
2527
- tailLines: preview?.tailLines ?? [],
2528
- detailLines: jobDetailLines(job.id),
3319
+ tailLines: (preview?.tailLines ?? []).slice(-3),
3320
+ detailLines,
2529
3321
  };
2530
3322
  });
2531
3323
  store.update((current) => ({
@@ -2536,82 +3328,123 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2536
3328
  : null,
2537
3329
  }));
2538
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
+ };
2539
3355
  setBackgroundJobUpdateHook((snapshot) => {
2540
3356
  syncBackgroundJobsState();
2541
3357
  if (snapshot.status !== 'running') {
2542
3358
  appendTurnAwareEntry(buildBackgroundJobNoticeEntry(snapshot));
3359
+ scheduleJobFollowUp();
2543
3360
  }
2544
3361
  });
2545
- projectIndex.onStatus = session.onStatus;
2546
- projectIndex.onContextLog = session.onContextLog;
3362
+ refreshSkillCommands();
2547
3363
  session.requestSudoPassword = async ({ command, prompt, signal }) => openSudoPasswordPrompt(command, prompt, signal);
2548
- session.confirmCommand = async (command) => {
3364
+ session.requestUserInput = async (request, signal) => openUserInputPrompt(request.questions, signal);
3365
+ session.requestPermission = async (request) => {
3366
+ const deny = { kind: 'deny' };
2549
3367
  if (exiting)
2550
- return false;
3368
+ return deny;
2551
3369
  if (sessionAutoYes)
2552
- return true;
2553
- const choice = await openApprovalPrompt('Approve command?', command);
2554
- if (choice === 'a') {
2555
- setAgentMode('auto-accept');
2556
- syncShellStateFromSession();
3370
+ return { kind: 'once' };
3371
+ const decision = await openApprovalPrompt(request, session.turnAbortSignal);
3372
+ if (decision.kind === 'always-bucket') {
2557
3373
  appendTurnAwareEntry({
2558
- body: 'Auto-approve enabled for the rest of this session.',
3374
+ body: `Allowed for the rest of this session: ${bucketActionLabel(request.bucket)}.`,
2559
3375
  kind: 'system',
2560
3376
  title: 'Approvals',
2561
3377
  });
2562
- return true;
2563
3378
  }
2564
- return choice === 'y';
2565
- };
2566
- session.confirmPatch = async (filePath, patch) => {
2567
- if (exiting)
2568
- return false;
2569
- if (sessionAutoYes)
2570
- return true;
2571
- const choice = await openApprovalPrompt('Approve patch?', 'Review changes before applying.', {
2572
- diff: patch,
2573
- filePath,
2574
- });
2575
- if (choice === 'a') {
2576
- setAgentMode('auto-accept');
2577
- syncShellStateFromSession();
3379
+ else if (decision.kind === 'always-prefix') {
2578
3380
  appendTurnAwareEntry({
2579
- 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}.`,
2580
3396
  kind: 'system',
2581
3397
  title: 'Approvals',
2582
3398
  });
2583
- return true;
2584
3399
  }
2585
- return choice === 'y';
3400
+ return decision;
2586
3401
  };
2587
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()),
2588
3408
  getTranscriptScrollLimit: () => {
2589
- const contentWidth = Math.max(20, Math.floor(terminalCols * 0.95) - 2);
3409
+ const contentWidth = frameContentWidth(terminalCols);
2590
3410
  const blocks = store.getState().transcript.map((entry) => renderTranscriptEntryLines(entry, contentWidth));
2591
3411
  return blocks.reduce((total, block, index) => total + block.length + (index > 0 ? 1 : 0), 0);
2592
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
+ },
2593
3418
  onCancelTurn: cancelActiveTurn,
2594
3419
  onCycleAgentMode: cycleAgentMode,
3420
+ onAgentModeChangeBlocked: reportAgentModeLocked,
2595
3421
  onCtrlC: handleCtrlC,
2596
3422
  onLinkCopy: handleLinkCopy,
2597
3423
  onLinkOpen: handleLinkOpen,
2598
3424
  onLiveFrameShapeChange: scheduleLiveFrameRemount,
2599
3425
  onRequestExit: requestExit,
2600
3426
  onResolveApproval: handleInlineApprovalChoice,
3427
+ onResolveUserInput: handleInlineUserInput,
2601
3428
  onResumeSession: handleInlineResumeSelection,
2602
3429
  onSelectionCopy: handleAppSelectionCopy,
2603
3430
  onSelectModel: handleInlineModelSelection,
3431
+ onOpenJobsPicker: openJobsPicker,
3432
+ onToggleNotifications: toggleNotifications,
2604
3433
  onJobsPickerOutput: handleJobsPickerOutput,
2605
3434
  onJobsPickerKill: handleJobsPickerKill,
2606
3435
  onSudoPasswordInput: handleSudoPasswordInput,
2607
3436
  onSubmit: handleSubmit,
3437
+ onFireQueuedMessage: fireQueuedMessage,
2608
3438
  };
2609
3439
  const unsubscribe = store.subscribe(() => {
2610
3440
  renderCurrentFrame();
3441
+ if (jobWait.waiting.length > 0 && !store.getState().busy)
3442
+ scheduleJobFollowUp();
2611
3443
  });
2612
3444
  const spinnerTimer = setInterval(() => {
2613
3445
  spinnerFrame = (spinnerFrame + 1) % 6;
2614
3446
  if (store.getState().busy) {
3447
+ flushPendingThinking();
2615
3448
  renderCurrentFrame();
2616
3449
  }
2617
3450
  }, 120);
@@ -2642,6 +3475,13 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2642
3475
  return;
2643
3476
  }
2644
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
+ }
2645
3485
  if (message.kind === 'resize') {
2646
3486
  terminalCols = message.cols;
2647
3487
  terminalRows = message.rows;
@@ -2667,6 +3507,7 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2667
3507
  killAllBackgroundJobs();
2668
3508
  setBackgroundJobSession(null);
2669
3509
  setScratchSession(null);
3510
+ setImageStoreSession(null);
2670
3511
  setTodoSession(null);
2671
3512
  setBackgroundJobUpdateHook(null);
2672
3513
  await bridge.close();
@@ -2676,4 +3517,5 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2676
3517
  });
2677
3518
  if (fatalError)
2678
3519
  throw fatalError;
3520
+ return { signedOut };
2679
3521
  }