@denizokcu/haze 0.9.0 → 0.11.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.
- package/CHANGELOG.md +133 -17
- package/README.md +164 -68
- package/SECURITY.md +22 -0
- package/bin/haze.js +102 -1
- package/dist/buildInfo.json +7 -0
- package/dist/cli/chat/TaskBar.d.ts +2 -1
- package/dist/cli/chat/TaskBar.js +7 -4
- package/dist/cli/chat/chatMetrics.d.ts +17 -1
- package/dist/cli/chat/chatMetrics.js +22 -5
- package/dist/cli/chat/contextReport.d.ts +11 -0
- package/dist/cli/chat/contextReport.js +46 -0
- package/dist/cli/chat/fileMentionSuggestions.d.ts +29 -0
- package/dist/cli/chat/fileMentionSuggestions.js +92 -0
- package/dist/cli/chat/inputSuggestions.d.ts +5 -0
- package/dist/cli/chat/inputSuggestions.js +17 -3
- package/dist/cli/chat/liveRegion.d.ts +25 -0
- package/dist/cli/chat/liveRegion.js +48 -0
- package/dist/cli/chat/messages.d.ts +33 -2
- package/dist/cli/chat/messages.js +216 -33
- package/dist/cli/chat/sessionLifecycle.d.ts +67 -0
- package/dist/cli/chat/sessionLifecycle.js +205 -0
- package/dist/cli/chat/sessionRecorder.js +80 -14
- package/dist/cli/chat/startupInfo.js +11 -4
- package/dist/cli/chat/tips.d.ts +21 -0
- package/dist/cli/chat/tips.js +43 -0
- package/dist/cli/chat/wizardDispatch.d.ts +64 -0
- package/dist/cli/chat/wizardDispatch.js +744 -0
- package/dist/cli/commands/chat.d.ts +6 -0
- package/dist/cli/commands/chat.js +373 -790
- package/dist/cli/commands/chatModes.d.ts +1 -1
- package/dist/cli/commands/chatModes.js +7 -2
- package/dist/cli/commands/commandHelp.js +5 -3
- package/dist/cli/commands/commands.d.ts +5 -2
- package/dist/cli/commands/commands.js +22 -18
- package/dist/cli/commands/doctor.d.ts +19 -0
- package/dist/cli/commands/doctor.js +76 -0
- package/dist/cli/commands/fleetCommand.d.ts +14 -0
- package/dist/cli/commands/fleetCommand.js +46 -0
- package/dist/cli/commands/formatters.d.ts +5 -0
- package/dist/cli/commands/formatters.js +35 -6
- package/dist/cli/commands/logsCommand.js +1 -7
- package/dist/cli/commands/modelCommand.js +1 -1
- package/dist/cli/commands/ndjsonSink.d.ts +23 -0
- package/dist/cli/commands/ndjsonSink.js +38 -0
- package/dist/cli/commands/providerWizard.d.ts +10 -2
- package/dist/cli/commands/providerWizard.js +50 -4
- package/dist/cli/commands/runCommand.d.ts +4 -0
- package/dist/cli/commands/runCommand.js +142 -16
- package/dist/cli/commands/sessionPicker.d.ts +9 -0
- package/dist/cli/commands/sessionPicker.js +29 -0
- package/dist/cli/commands/settingsSummary.js +6 -4
- package/dist/cli/commands/skillConfirmRemove.js +4 -3
- package/dist/cli/commands/skillWizard.d.ts +2 -0
- package/dist/cli/commands/skillWizard.js +16 -6
- package/dist/cli/commands/streaming/abortCause.d.ts +24 -0
- package/dist/cli/commands/streaming/abortCause.js +16 -0
- package/dist/cli/commands/streaming/assistantText.js +9 -2
- package/dist/cli/commands/streaming/goalCheckpoint.d.ts +65 -0
- package/dist/cli/commands/streaming/goalCheckpoint.js +23 -0
- package/dist/cli/commands/streaming/goalSupervisor.d.ts +64 -0
- package/dist/cli/commands/streaming/goalSupervisor.js +127 -0
- package/dist/cli/commands/streaming/idleTimer.d.ts +26 -0
- package/dist/cli/commands/streaming/idleTimer.js +24 -0
- package/dist/cli/commands/streaming/toolCallRecovery.d.ts +2 -0
- package/dist/cli/commands/streaming/toolCallRecovery.js +24 -0
- package/dist/cli/commands/streaming/toolGroupRenderer.d.ts +31 -0
- package/dist/cli/commands/streaming/toolGroupRenderer.js +50 -2
- package/dist/cli/commands/streaming/toolResultState.d.ts +6 -1
- package/dist/cli/commands/streaming/toolResultState.js +29 -7
- package/dist/cli/commands/streaming/turnOutcome.d.ts +17 -0
- package/dist/cli/commands/streaming/turnOutcome.js +27 -11
- package/dist/cli/commands/streaming/turnRuntime.js +6 -4
- package/dist/cli/commands/streaming.d.ts +82 -3
- package/dist/cli/commands/streaming.js +528 -91
- package/dist/cli/commands/wizardActions.d.ts +7 -0
- package/dist/cli/commands/wizardActions.js +7 -0
- package/dist/cli/commands/wizardPrompts.js +7 -1
- package/dist/cli/commands/wizardSuggestions.d.ts +8 -0
- package/dist/cli/commands/wizardSuggestions.js +64 -14
- package/dist/cli/commands/wizardTransition.d.ts +4 -0
- package/dist/cli/commands/wizardTransition.js +1 -2
- package/dist/cli/index.js +82 -22
- package/dist/cli/terminalTitle.d.ts +6 -0
- package/dist/cli/terminalTitle.js +36 -0
- package/dist/config/inputHistory.d.ts +3 -3
- package/dist/config/inputHistory.js +12 -18
- package/dist/config/modelDiscovery.d.ts +71 -0
- package/dist/config/modelDiscovery.js +214 -0
- package/dist/config/privateStorage.js +28 -2
- package/dist/config/providerAuth.d.ts +14 -0
- package/dist/config/providerAuth.js +49 -0
- package/dist/config/providerPresets.d.ts +49 -5
- package/dist/config/providerPresets.js +573 -73
- package/dist/config/providers.d.ts +2 -0
- package/dist/config/providers.js +9 -0
- package/dist/config/settings.d.ts +58 -0
- package/dist/config/settings.js +38 -1
- package/dist/config/skillSettings.d.ts +6 -13
- package/dist/config/skillSettings.js +20 -19
- package/dist/core/agent/budgets.d.ts +36 -0
- package/dist/core/agent/budgets.js +44 -0
- package/dist/core/agent/compaction.d.ts +38 -0
- package/dist/core/agent/compaction.js +108 -19
- package/dist/core/agent/completionController.d.ts +230 -0
- package/dist/core/agent/completionController.js +287 -0
- package/dist/core/agent/contextBudget.d.ts +46 -0
- package/dist/core/agent/contextBudget.js +89 -7
- package/dist/core/agent/errors.js +6 -2
- package/dist/core/agent/events.d.ts +86 -0
- package/dist/core/agent/reasoningPolicy.d.ts +31 -0
- package/dist/core/agent/reasoningPolicy.js +27 -0
- package/dist/core/agent/toolCapabilities.d.ts +27 -0
- package/dist/core/agent/toolCapabilities.js +58 -0
- package/dist/core/agent/toolExecutionBudget.d.ts +35 -0
- package/dist/core/agent/toolExecutionBudget.js +49 -0
- package/dist/core/agent/toolOutputStore.d.ts +13 -0
- package/dist/core/agent/toolOutputStore.js +27 -10
- package/dist/core/agent/toolResults.d.ts +12 -0
- package/dist/core/agent/toolResults.js +38 -0
- package/dist/core/agent/turnBudget.d.ts +35 -0
- package/dist/core/agent/turnBudget.js +27 -0
- package/dist/core/agent/turnPolicy.d.ts +11 -0
- package/dist/core/agent/turnPolicy.js +19 -0
- package/dist/core/agent/workState.d.ts +76 -1
- package/dist/core/agent/workState.js +120 -13
- package/dist/core/attachments/imageAttachments.d.ts +90 -0
- package/dist/core/attachments/imageAttachments.js +245 -0
- package/dist/core/attachments/readBlessings.d.ts +37 -0
- package/dist/core/attachments/readBlessings.js +79 -0
- package/dist/core/deadline.d.ts +33 -0
- package/dist/core/deadline.js +74 -0
- package/dist/core/goal/completionPolicy.d.ts +27 -0
- package/dist/core/goal/completionPolicy.js +37 -1
- package/dist/core/goal/requestClassifier.d.ts +0 -3
- package/dist/core/goal/requestClassifier.js +0 -13
- package/dist/core/io/boundedRead.js +76 -29
- package/dist/core/limits/byteBudgets.d.ts +7 -0
- package/dist/core/limits/byteBudgets.js +7 -0
- package/dist/core/limits/textBudgets.d.ts +25 -0
- package/dist/core/limits/textBudgets.js +25 -0
- package/dist/core/log/llmLog.js +7 -0
- package/dist/core/persistence/orderedFileWriter.d.ts +10 -0
- package/dist/core/persistence/orderedFileWriter.js +16 -2
- package/dist/core/process/backgroundRegistry.d.ts +35 -0
- package/dist/core/process/backgroundRegistry.js +195 -0
- package/dist/core/process/runBoundedProcess.d.ts +9 -0
- package/dist/core/process/runBoundedProcess.js +74 -29
- package/dist/core/safety/missingExecutable.d.ts +42 -0
- package/dist/core/safety/missingExecutable.js +77 -0
- package/dist/core/safety/urlGuard.d.ts +2 -1
- package/dist/core/safety/urlGuard.js +3 -2
- package/dist/core/session/sessionSlimming.js +47 -4
- package/dist/core/session/sessionStore.d.ts +74 -0
- package/dist/core/session/sessionStore.js +268 -18
- package/dist/core/subagent/contracts.d.ts +120 -0
- package/dist/core/subagent/contracts.js +55 -0
- package/dist/core/subagent/executionProfiles.d.ts +28 -0
- package/dist/core/subagent/executionProfiles.js +45 -0
- package/dist/core/subagent/subagentCoordinator.d.ts +78 -0
- package/dist/core/subagent/subagentCoordinator.js +164 -0
- package/dist/core/subagent/subagentRunner.d.ts +211 -145
- package/dist/core/subagent/subagentRunner.js +208 -98
- package/dist/core/subagent/workspaceMutationPolicy.d.ts +11 -0
- package/dist/core/subagent/workspaceMutationPolicy.js +52 -0
- package/dist/core/tasks/taskStorage.js +12 -1
- package/dist/llm/client.d.ts +36 -29
- package/dist/llm/client.js +102 -33
- package/dist/llm/hazeTools.d.ts +2559 -150
- package/dist/llm/hazeTools.js +119 -31
- package/dist/llm/lsp.d.ts +26 -4
- package/dist/llm/lsp.js +90 -14
- package/dist/llm/lspTools.d.ts +2366 -0
- package/dist/llm/lspTools.js +87 -79
- package/dist/llm/openaiCodex.d.ts +3 -0
- package/dist/llm/openaiCodex.js +47 -0
- package/dist/llm/openaiCodexOAuth.d.ts +54 -0
- package/dist/llm/openaiCodexOAuth.js +214 -0
- package/dist/llm/requestContext.d.ts +25 -1
- package/dist/llm/requestContext.js +51 -8
- package/dist/llm/systemPrompt.d.ts +15 -1
- package/dist/llm/systemPrompt.js +24 -8
- package/dist/llm/toolResultTypes.d.ts +8 -1
- package/dist/llm/tools/bashTool.d.ts +906 -32
- package/dist/llm/tools/bashTool.js +30 -4
- package/dist/llm/tools/editMatch.d.ts +14 -0
- package/dist/llm/tools/editMatch.js +72 -0
- package/dist/llm/tools/failures.d.ts +2 -0
- package/dist/llm/tools/failures.js +1 -0
- package/dist/llm/tools/fetchTool.d.ts +42 -26
- package/dist/llm/tools/fetchTool.js +1 -1
- package/dist/llm/tools/fileToolShared.d.ts +6 -4
- package/dist/llm/tools/fileToolShared.js +18 -23
- package/dist/llm/tools/gitIgnore.d.ts +49 -0
- package/dist/llm/tools/gitIgnore.js +129 -0
- package/dist/llm/tools/grepRunner.d.ts +5 -0
- package/dist/llm/tools/grepRunner.js +52 -71
- package/dist/llm/tools/outputCap.d.ts +2 -6
- package/dist/llm/tools/outputCap.js +2 -6
- package/dist/llm/tools/processTool.d.ts +1077 -0
- package/dist/llm/tools/processTool.js +41 -0
- package/dist/llm/tools/readRecovery.d.ts +10 -0
- package/dist/llm/tools/readRecovery.js +135 -0
- package/dist/llm/tools/toolContext.d.ts +9 -1
- package/dist/llm/tools/toolContext.js +83 -43
- package/dist/llm/tools/workspaceFile.d.ts +9 -1
- package/dist/llm/tools/workspaceFile.js +33 -4
- package/dist/llm/webFetch.d.ts +17 -0
- package/dist/llm/webFetch.js +66 -86
- package/dist/llm/workerContext.d.ts +18 -0
- package/dist/llm/workerContext.js +55 -0
- package/dist/skills/SkillLoader.d.ts +2 -2
- package/dist/skills/SkillRegistry.d.ts +3 -2
- package/dist/skills/SkillRegistry.js +43 -13
- package/dist/skills/builder/SkillBuilder.d.ts +3 -0
- package/dist/skills/builder/SkillBuilder.js +23 -5
- package/dist/skills/skillTools.js +11 -4
- package/dist/skills/types.d.ts +6 -1
- package/dist/ui/codeHighlight.d.ts +4 -0
- package/dist/ui/codeHighlight.js +31 -0
- package/dist/ui/components/Header.d.ts +1 -1
- package/dist/ui/components/MarkdownText.d.ts +16 -2
- package/dist/ui/components/MarkdownText.js +244 -34
- package/dist/ui/components/TextInput.d.ts +12 -2
- package/dist/ui/components/TextInput.js +80 -8
- package/dist/ui/theme.d.ts +4 -3
- package/dist/ui/theme.js +5 -4
- package/dist/utils/buildInfo.d.ts +104 -0
- package/dist/utils/buildInfo.js +253 -0
- package/dist/utils/format.d.ts +2 -0
- package/dist/utils/format.js +8 -0
- package/dist/utils/fs.d.ts +9 -1
- package/dist/utils/fs.js +87 -29
- package/dist/utils/openPath.d.ts +2 -0
- package/dist/utils/openPath.js +22 -0
- package/dist/utils/path.d.ts +2 -0
- package/dist/utils/path.js +5 -1
- package/dist/utils/utf8.d.ts +22 -0
- package/dist/utils/utf8.js +54 -0
- package/dist/utils/version.d.ts +9 -3
- package/dist/utils/version.js +28 -2
- package/package.json +24 -19
|
@@ -2,55 +2,45 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
|
2
2
|
import { useEffect, useRef, useState } from 'react';
|
|
3
3
|
import { execFile as execFileCallback } from 'node:child_process';
|
|
4
4
|
import { promisify } from 'node:util';
|
|
5
|
-
import
|
|
6
|
-
import { Box, render, Static, Text, useApp, useStdout } from 'ink';
|
|
5
|
+
import { Box, render, Static, Text, useApp, useWindowSize } from 'ink';
|
|
7
6
|
import Spinner from 'ink-spinner';
|
|
8
7
|
import { readContextFiles } from '../../config/contextFiles.js';
|
|
9
8
|
import { checkForUpdate } from '../../config/updateCheck.js';
|
|
10
9
|
import { addInputHistoryItem, readInputHistory } from '../../config/inputHistory.js';
|
|
11
10
|
import { loadTasks as loadTasksFromStore, clearTasks as clearTasksFromStore } from '../../core/tasks/taskStorage.js';
|
|
12
11
|
import { readSettings, updateSettings } from '../../config/settings.js';
|
|
13
|
-
import { activeModel,
|
|
14
|
-
import { removeLspServer } from '../../config/lspSettings.js';
|
|
15
|
-
import { removeMcpServer } from '../../config/mcpSettings.js';
|
|
12
|
+
import { activeModel, activeProvider } from '../../config/providers.js';
|
|
16
13
|
import { isSkillEnabled } from '../../config/skillSettings.js';
|
|
17
14
|
import { Header } from '../../ui/components/Header.js';
|
|
18
15
|
import { TextInput } from '../../ui/components/TextInput.js';
|
|
19
16
|
import { theme } from '../../ui/theme.js';
|
|
20
17
|
import { handleSlashCommand } from './commands.js';
|
|
21
|
-
import {
|
|
22
|
-
import {
|
|
23
|
-
import {
|
|
18
|
+
import { runAgentGoal } from './streaming/goalSupervisor.js';
|
|
19
|
+
import { formatElapsedTimeWhole, imageAttachmentLine } from './formatters.js';
|
|
20
|
+
import { imageCapabilityError, IMAGE_ONLY_PROMPT_TEXT, resolveImageAttachments } from '../../core/attachments/imageAttachments.js';
|
|
21
|
+
import { resolveReadBlessings } from '../../core/attachments/readBlessings.js';
|
|
22
|
+
import { endLog as endLlmLog } from '../../core/log/llmLog.js';
|
|
24
23
|
import { loadSkillRegistry } from '../../skills/SkillRegistry.js';
|
|
25
|
-
import {
|
|
26
|
-
import { findPreset } from '../../config/providerPresets.js';
|
|
27
|
-
import { createSession, formatSession, latestSession, restoreConversation, restoreWorkState } from '../../core/session/sessionStore.js';
|
|
28
|
-
import { compactModelMessages } from '../../core/agent/compaction.js';
|
|
29
|
-
import { contextBreakdown } from '../../core/agent/contextBudget.js';
|
|
30
|
-
import { stripSyntheticControls } from '../../core/agent/requestAssembly.js';
|
|
31
|
-
import { modelWithConfig } from '../../llm/client.js';
|
|
32
|
-
import { assembleRequestContext } from '../../llm/requestContext.js';
|
|
33
|
-
import { closeMcpClients } from '../../llm/mcp.js';
|
|
24
|
+
import { formatSession, listSessions } from '../../core/session/sessionStore.js';
|
|
34
25
|
import { MAX_VISIBLE_TASKS, TaskBar } from '../chat/TaskBar.js';
|
|
35
|
-
import {
|
|
36
|
-
import { MessageView, messageKey, orderedDisplayMessages } from '../chat/messages.js';
|
|
26
|
+
import { AssistantMarkdownChunkView, MessageView, partitionDisplayMessages } from '../chat/messages.js';
|
|
37
27
|
import { createSessionRecorder } from '../chat/sessionRecorder.js';
|
|
28
|
+
import { createSessionLifecycle } from '../chat/sessionLifecycle.js';
|
|
29
|
+
import { createWizardDispatch } from '../chat/wizardDispatch.js';
|
|
30
|
+
import { buildContextReport } from '../chat/contextReport.js';
|
|
38
31
|
import { startupContextInfo, startupProviderInfo } from '../chat/startupInfo.js';
|
|
39
|
-
import {
|
|
32
|
+
import { TIPS, randomTipIndex, tipsEnabled } from '../chat/tips.js';
|
|
33
|
+
import { fileMentionSuggestions } from '../chat/fileMentionSuggestions.js';
|
|
34
|
+
import { compactHomePath, formatTokenCount, statusBarMetrics } from '../chat/chatMetrics.js';
|
|
40
35
|
import { accumulateTokenUsage, EMPTY_TOKEN_USAGE, shouldClearCompletedTasks } from '../chat/turnState.js';
|
|
41
36
|
import { MASKED_MODES, PICKER_MODES, SUBMIT_EMPTY_MODES, placeholderForMode } from './chatModes.js';
|
|
42
37
|
import { inputSuggestionsForState } from '../chat/inputSuggestions.js';
|
|
43
38
|
import { modelThinkingLabel } from '../../utils/modelName.js';
|
|
44
|
-
import {
|
|
45
|
-
import { captureLspName } from './wizardPrompts.js';
|
|
39
|
+
import { detectCheckoutMismatch, formatMismatchWarning, runtimeCapabilities } from '../../utils/buildInfo.js';
|
|
46
40
|
import { transitionMcpField, transitionProviderField } from './wizardTransition.js';
|
|
47
|
-
import {
|
|
48
|
-
import {
|
|
49
|
-
import {
|
|
50
|
-
import { selectSkillActionResult, selectSkillResult } from './skillWizard.js';
|
|
51
|
-
import { captureSkillDescription as captureSkillDescriptionResult, skillCreationFailure, skillCreationMessage } from './skillCreation.js';
|
|
52
|
-
import { skillConfirmRemoveResult as skillConfirmRemove } from './skillConfirmRemove.js';
|
|
53
|
-
import { commandParts, isYesConfirmation } from './wizardInput.js';
|
|
41
|
+
import { commandParts } from './wizardInput.js';
|
|
42
|
+
import { backgroundProcessCount, subscribeBackgroundProcesses, teardownBackgroundProcesses } from '../../core/process/backgroundRegistry.js';
|
|
43
|
+
import { MAX_SESSION_PICKER_RESULTS } from './sessionPicker.js';
|
|
54
44
|
const execFile = promisify(execFileCallback);
|
|
55
45
|
async function currentBranchName() {
|
|
56
46
|
try {
|
|
@@ -71,10 +61,19 @@ function busyElapsedLabel(startedAt) {
|
|
|
71
61
|
function thinkingLabelForSettings(settings) {
|
|
72
62
|
return modelThinkingLabel(activeModel(settings)?.model);
|
|
73
63
|
}
|
|
74
|
-
|
|
64
|
+
/**
|
|
65
|
+
* Busy indicator isolated in its own component. The Spinner animates on its own
|
|
66
|
+
* internal state (~10 fps) which triggers re-renders inside this subtree; keeping
|
|
67
|
+
* the spinner out of ChatScreen's render scope means those ticks don't propagate
|
|
68
|
+
* to the transcript tree above (where React.memo on MessageView already prevents
|
|
69
|
+
* deep re-renders, but avoiding the reconciliation walk entirely is still cheaper).
|
|
70
|
+
*/
|
|
71
|
+
function BusyBar({ label, elapsed, tip }) {
|
|
72
|
+
return _jsxs(Box, { flexDirection: "column", flexShrink: 0, children: [_jsx(Box, { children: _jsxs(Text, { children: [_jsxs(Text, { color: theme.command, bold: true, children: [_jsx(Spinner, { type: "dots" }), " ", label, elapsed ? _jsxs(Text, { color: theme.muted, children: [" \u00B7 ", elapsed] }) : null] }), _jsx(Text, { color: theme.muted, children: " \u00B7 type to queue follow-up \u00B7 esc to interrupt" })] }) }), tip && (_jsx(Box, { children: _jsxs(Text, { color: theme.muted, children: [_jsx(Text, { bold: true, children: "Tip:" }), " ", tip] }) }))] });
|
|
73
|
+
}
|
|
74
|
+
function ChatScreen({ debug = false, version, build, continueSession = false, resumeSessionId, noSession = false }) {
|
|
75
75
|
const { exit } = useApp();
|
|
76
|
-
const {
|
|
77
|
-
const width = stdout.columns ?? process.stdout.columns ?? 80;
|
|
76
|
+
const { columns: width, rows: terminalRows } = useWindowSize();
|
|
78
77
|
const nextDisplayOrderRef = useRef(1);
|
|
79
78
|
const withDisplayOrder = (message) => {
|
|
80
79
|
if (message.displayOrder != null)
|
|
@@ -82,9 +81,7 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
|
|
|
82
81
|
return { ...message, displayOrder: nextDisplayOrderRef.current++ };
|
|
83
82
|
};
|
|
84
83
|
const withDisplayOrders = (next) => next.map(withDisplayOrder);
|
|
85
|
-
const [messages, setMessagesRaw] = useState([
|
|
86
|
-
{ role: 'system', text: 'Welcome to haze. Use /help for commands.', displayOrder: 0 }
|
|
87
|
-
]);
|
|
84
|
+
const [messages, setMessagesRaw] = useState([]);
|
|
88
85
|
const setMessages = (updater) => {
|
|
89
86
|
setMessagesRaw(previous => withDisplayOrders(typeof updater === 'function' ? updater(previous) : updater));
|
|
90
87
|
};
|
|
@@ -107,17 +104,26 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
|
|
|
107
104
|
if (!sessionRecorderRef.current)
|
|
108
105
|
sessionRecorderRef.current = createSessionRecorder(() => sessionRef.current);
|
|
109
106
|
const sessionStartRef = useRef(new Date());
|
|
107
|
+
// Stable PromptSession object across turns so per-session flags (the
|
|
108
|
+
// context-fallback warning key) persist; rebuilt when a new session starts,
|
|
109
|
+
// detected by sessionStartRef identity (the lifecycle controller replaces
|
|
110
|
+
// the Date on new/resume/continue).
|
|
111
|
+
const promptSessionRef = useRef({ identity: undefined, value: { cwd: process.cwd() } });
|
|
110
112
|
const workStateRef = useRef(undefined);
|
|
111
113
|
const llmLogRef = useRef(undefined);
|
|
112
114
|
const persistenceWarningShownRef = useRef(false);
|
|
113
115
|
const skillErrorSignatureRef = useRef('');
|
|
116
|
+
const projectSkillSignatureRef = useRef('');
|
|
114
117
|
const contextFileSignaturesRef = useRef(new Map());
|
|
115
118
|
const followUpQueueRef = useRef([]);
|
|
116
119
|
const [inputHistory, setInputHistory] = useState([]);
|
|
117
120
|
const [debugLogs, setDebugLogs] = useState([]);
|
|
118
121
|
const [contextFiles, setContextFiles] = useState([]);
|
|
119
122
|
const [mode, setMode] = useState('chat');
|
|
123
|
+
const [sessions, setSessions] = useState([]);
|
|
124
|
+
const [selectedSessionId, setSelectedSessionId] = useState();
|
|
120
125
|
const [busy, setBusy] = useState(false);
|
|
126
|
+
const [backgroundCount, setBackgroundCount] = useState(backgroundProcessCount);
|
|
121
127
|
const [busyLabel, setBusyLabel] = useState(() => thinkingLabelForSettings(settings));
|
|
122
128
|
// Heartbeat for the busy indicator: ticks every second while haze is working
|
|
123
129
|
// so the developer always sees rolling activity (elapsed turn time) even when
|
|
@@ -129,9 +135,16 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
|
|
|
129
135
|
const [taskBarPadding, setTaskBarPadding] = useState(0);
|
|
130
136
|
const [tokenUsage, setTokenUsage] = useState({ ...EMPTY_TOKEN_USAGE });
|
|
131
137
|
const [queuedFollowUps, setQueuedFollowUps] = useState([]);
|
|
138
|
+
// A genuinely paused goal (no measurable progress, deadline, or a stalled
|
|
139
|
+
// model stream) — automatic continuation has already been attempted by the
|
|
140
|
+
// goal supervisor. Carries what a one-key resume needs; any new submission
|
|
141
|
+
// clears it.
|
|
142
|
+
const [pausedResume, setPausedResume] = useState(undefined);
|
|
132
143
|
const [skills, setSkills] = useState([]);
|
|
133
144
|
const [branchName, setBranchName] = useState();
|
|
134
145
|
const [modelProviderFilter, setModelProviderFilter] = useState();
|
|
146
|
+
const [discoveredModels, setDiscoveredModels] = useState([]);
|
|
147
|
+
const [suggestedModels, setSuggestedModels] = useState([]);
|
|
135
148
|
const [selectedProviderName, setSelectedProviderName] = useState();
|
|
136
149
|
const [providerDraft, setProviderDraft] = useState({});
|
|
137
150
|
const [skillDraft, setSkillDraft] = useState({});
|
|
@@ -151,18 +164,39 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
|
|
|
151
164
|
turnStartedAtRef.current = undefined;
|
|
152
165
|
setBusy(nextBusy);
|
|
153
166
|
};
|
|
167
|
+
useEffect(() => subscribeBackgroundProcesses(() => setBackgroundCount(backgroundProcessCount())), []);
|
|
154
168
|
useEffect(() => {
|
|
155
169
|
if (!busy)
|
|
156
170
|
return;
|
|
157
171
|
const heartbeat = setInterval(() => setBusyTick(tick => tick + 1), 1000);
|
|
158
172
|
return () => clearInterval(heartbeat);
|
|
159
173
|
}, [busy]);
|
|
174
|
+
// One tip per thinking section, shown under the busy label while the model
|
|
175
|
+
// is purely thinking (no tool running) and the user has not disabled tips.
|
|
176
|
+
// A fresh tip is picked each time the model enters thinking mode; no
|
|
177
|
+
// rotation during a single thinking section.
|
|
178
|
+
const [tipIndex, setTipIndex] = useState(() => randomTipIndex());
|
|
179
|
+
const thinkingLabel = thinkingLabelForSettings(settings);
|
|
180
|
+
const showingTip = busy && busyLabel === thinkingLabel && tipsEnabled(settings);
|
|
181
|
+
useEffect(() => {
|
|
182
|
+
if (!showingTip)
|
|
183
|
+
return;
|
|
184
|
+
setTipIndex(current => randomTipIndex(current));
|
|
185
|
+
}, [showingTip]);
|
|
186
|
+
// Refresh the branch at turn boundaries so switching branches during a turn
|
|
187
|
+
// shows up promptly without tight idle polling (CR-026).
|
|
188
|
+
useEffect(() => {
|
|
189
|
+
if (busy)
|
|
190
|
+
return;
|
|
191
|
+
currentBranchName().then(setBranchName).catch(() => setBranchName(undefined));
|
|
192
|
+
}, [busy]);
|
|
160
193
|
useEffect(() => {
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
194
|
+
void (async () => {
|
|
195
|
+
const [settingsResult, branch, files] = await Promise.all([
|
|
196
|
+
readSettings().then(value => ({ value, error: undefined })).catch(error => ({ value: {}, error: error instanceof Error ? error.message : String(error) })),
|
|
197
|
+
currentBranchName().catch(() => undefined),
|
|
198
|
+
readContextFiles().catch(() => []),
|
|
199
|
+
]);
|
|
166
200
|
const next = settingsResult.value;
|
|
167
201
|
setSettings(next);
|
|
168
202
|
setSettingsError(settingsResult.error);
|
|
@@ -170,26 +204,32 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
|
|
|
170
204
|
setContextFiles(files);
|
|
171
205
|
contextFileSignaturesRef.current = new Map(files.flatMap(file => file.signature ? [[file.path, file.signature]] : []));
|
|
172
206
|
setMessages(m => [...m, { role: 'system', text: settingsResult.error ? settingsResult.error : `${startupProviderInfo(next)}\n\n${startupContextInfo(files)}` }]);
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
loadTasksFromStore().then(setVisibleTasks).catch(() => undefined);
|
|
181
|
-
if (version) {
|
|
182
|
-
checkForUpdate({ currentVersion: version, packageName: '@denizokcu/haze' })
|
|
183
|
-
.then(result => {
|
|
207
|
+
await sessionLifecycle.initializeSession().catch(error => {
|
|
208
|
+
const text = error instanceof Error ? error.message : String(error);
|
|
209
|
+
setMessages(m => [...m, { role: 'system', text: `Session disabled: ${text}` }]);
|
|
210
|
+
});
|
|
211
|
+
await refreshSkills().catch(() => undefined);
|
|
212
|
+
if (version) {
|
|
213
|
+
const result = await checkForUpdate({ currentVersion: version, packageName: '@denizokcu/haze' }).catch(() => undefined);
|
|
184
214
|
if (result?.isOutdated) {
|
|
185
215
|
setMessages(m => [...m, { role: 'system', text: `A new version of haze is available: ${result.latestVersion} (you have ${version}). Update with: npm i -g @denizokcu/haze` }]);
|
|
186
216
|
}
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
|
|
217
|
+
}
|
|
218
|
+
// Runtime/installation diagnostics: never switch runtimes silently, but
|
|
219
|
+
// make a stale binary serving a workspace with a newer checkout unmistakable.
|
|
220
|
+
const mismatch = detectCheckoutMismatch();
|
|
221
|
+
if (mismatch) {
|
|
222
|
+
setMessages(m => [...m, { role: 'system', text: formatMismatchWarning(mismatch) }]);
|
|
223
|
+
}
|
|
224
|
+
else if (!runtimeCapabilities().logicalGoalSupervisor) {
|
|
225
|
+
setMessages(m => [...m, { role: 'system', text: 'Warning: this haze build lacks the goal supervisor module; exhausting a turn step/tool budget may pause the goal instead of continuing automatically. Reinstall or relink haze (npm run dev:link in the checkout).' }]);
|
|
226
|
+
}
|
|
227
|
+
})().catch(() => undefined);
|
|
228
|
+
readInputHistory().then(setInputHistory).catch(() => undefined);
|
|
229
|
+
loadTasksFromStore().then(setVisibleTasks).catch(() => undefined);
|
|
190
230
|
const branchTimer = setInterval(() => {
|
|
191
231
|
currentBranchName().then(setBranchName).catch(() => setBranchName(undefined));
|
|
192
|
-
},
|
|
232
|
+
}, 15_000);
|
|
193
233
|
return () => clearInterval(branchTimer);
|
|
194
234
|
}, []);
|
|
195
235
|
function persistInputHistory(value) {
|
|
@@ -197,9 +237,15 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
|
|
|
197
237
|
}
|
|
198
238
|
async function refreshSkills() {
|
|
199
239
|
const registry = await loadSkillRegistry();
|
|
200
|
-
const nextSkills = [...registry.skills.values()];
|
|
240
|
+
const nextSkills = registry.candidates ?? [...registry.skills.values()];
|
|
201
241
|
setSkills(nextSkills);
|
|
202
|
-
const
|
|
242
|
+
const projectSkills = nextSkills.filter(skill => skill.source === 'project');
|
|
243
|
+
const projectSignature = projectSkills.map(skill => `${skill.name}:${skill.path}`).join('\n');
|
|
244
|
+
if (projectSignature && projectSignature !== projectSkillSignatureRef.current) {
|
|
245
|
+
setMessages(messages => [...messages, { role: 'system', text: `Project skills discovered (repository-provided, untrusted content): ${projectSkills.map(skill => skill.name).join(', ')}` }]);
|
|
246
|
+
}
|
|
247
|
+
projectSkillSignatureRef.current = projectSignature;
|
|
248
|
+
const errorSignature = registry.errors.map(error => `${error.source ? `${error.source}/` : ''}${error.directory}: ${error.message}`).join('\n');
|
|
203
249
|
if (errorSignature && errorSignature !== skillErrorSignatureRef.current) {
|
|
204
250
|
setMessages(messages => [...messages, { role: 'system', text: `Invalid skills were isolated:\n${errorSignature}` }]);
|
|
205
251
|
}
|
|
@@ -212,10 +258,10 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
|
|
|
212
258
|
const [name, ...args] = commandParts(value.slice(1));
|
|
213
259
|
if (!name)
|
|
214
260
|
return undefined;
|
|
215
|
-
const skill = skills.find(candidate => candidate.name === name);
|
|
216
|
-
//
|
|
217
|
-
//
|
|
218
|
-
return skill
|
|
261
|
+
const skill = skills.find(candidate => candidate.name === name && isSkillEnabled(settings, candidate.name, candidate.source));
|
|
262
|
+
// Candidates are ordered project-first, so disabling a project collision
|
|
263
|
+
// automatically re-surfaces the enabled global skill.
|
|
264
|
+
return skill ? { skill, args: args.join(' ') } : undefined;
|
|
219
265
|
}
|
|
220
266
|
function debugLog(line) {
|
|
221
267
|
if (!debug)
|
|
@@ -229,135 +275,45 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
|
|
|
229
275
|
const text = error instanceof Error ? error.message : String(error);
|
|
230
276
|
setMessages(messages => [...messages, { role: 'system', text: `Persistence warning: ${text}` }]);
|
|
231
277
|
}
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
workStateRef
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
}
|
|
258
|
-
async function
|
|
259
|
-
if (noSession) {
|
|
260
|
-
return;
|
|
261
|
-
}
|
|
262
|
-
if (continueSession) {
|
|
263
|
-
const session = await latestSession();
|
|
264
|
-
if (session) {
|
|
265
|
-
const { messages: conversation, parseErrors: conversationErrors } = await restoreConversation(session);
|
|
266
|
-
sessionRef.current = session;
|
|
267
|
-
sessionStartRef.current = new Date();
|
|
268
|
-
conversationRef.current = conversation;
|
|
269
|
-
setLiveMessagesState(() => []);
|
|
270
|
-
const restoredMessages = displayMessagesFromConversation(conversation);
|
|
271
|
-
setTokenUsage({ ...EMPTY_TOKEN_USAGE, messages: estimateConversationTokens(restoredMessages).input, outputEstimate: estimateConversationTokens(restoredMessages).output });
|
|
272
|
-
const { state: workState, parseErrors: workStateErrors } = await restoreWorkState(session);
|
|
273
|
-
workStateRef.current = workState;
|
|
274
|
-
for (const error of [...conversationErrors, ...workStateErrors]) {
|
|
275
|
-
debugLog(`Session parse error: ${error}`);
|
|
276
|
-
}
|
|
277
|
-
setMessages(m => [...m, { role: 'system', text: `Resumed session: ${formatSession(session)}` }, ...restoredMessages]);
|
|
278
|
-
await startNewLog();
|
|
279
|
-
return;
|
|
280
|
-
}
|
|
281
|
-
}
|
|
282
|
-
await startNewSession(continueSession ? 'No previous session found. Started a new session.' : 'Started a new session.');
|
|
283
|
-
}
|
|
284
|
-
async function clearConversation() {
|
|
285
|
-
clearToolOutputs();
|
|
286
|
-
conversationRef.current = [];
|
|
287
|
-
lastAssistantTextRef.current = '';
|
|
288
|
-
setTokenUsage({ ...EMPTY_TOKEN_USAGE });
|
|
289
|
-
workStateRef.current = undefined;
|
|
290
|
-
setLiveMessagesState(() => []);
|
|
291
|
-
setMessages([{ role: 'system', text: 'Cleared. The void is productive.' }]);
|
|
292
|
-
sessionRecorderRef.current?.recordNamedEvent('clear', 'Conversation cleared');
|
|
293
|
-
await sessionRecorderRef.current?.flush().catch(showPersistenceWarning);
|
|
294
|
-
await startNewLog().catch(showPersistenceWarning);
|
|
295
|
-
}
|
|
296
|
-
function compactConversation(instructions) {
|
|
297
|
-
const result = compactModelMessages(conversationRef.current, { instructions, tokenBudget: 40_000, workState: workStateRef.current });
|
|
298
|
-
if (!result.compacted) {
|
|
299
|
-
setMessages(m => [...m, { role: 'system', text: `Compaction skipped: only ${result.keptCount} model messages in context.` }]);
|
|
300
|
-
return false;
|
|
301
|
-
}
|
|
302
|
-
conversationRef.current = result.messages;
|
|
303
|
-
sessionRecorderRef.current?.recordNamedEvent('compact', `Compacted ${result.olderCount} messages; kept ${result.keptCount}.`);
|
|
304
|
-
sessionRecorderRef.current?.recordConversation(result.messages);
|
|
305
|
-
setMessages(m => [...m, { role: 'system', text: `Compacted context: summarized ${result.olderCount} older model messages and kept the last ${result.keptCount}.` }]);
|
|
306
|
-
return true;
|
|
307
|
-
}
|
|
308
|
-
async function resumeLatestSession() {
|
|
278
|
+
// Session lifecycle (init/continue/resume/new/clear/compact) lives in a
|
|
279
|
+
// dedicated controller so this component stays orchestration glue (CR-006).
|
|
280
|
+
const sessionLifecycle = createSessionLifecycle({
|
|
281
|
+
version,
|
|
282
|
+
build,
|
|
283
|
+
continueSession,
|
|
284
|
+
resumeSessionId,
|
|
285
|
+
noSession,
|
|
286
|
+
debug,
|
|
287
|
+
contextFiles: () => contextFiles,
|
|
288
|
+
sessionRef,
|
|
289
|
+
sessionRecorder: () => sessionRecorderRef.current,
|
|
290
|
+
sessionStartRef,
|
|
291
|
+
conversationRef,
|
|
292
|
+
workStateRef,
|
|
293
|
+
lastAssistantTextRef,
|
|
294
|
+
llmLogRef,
|
|
295
|
+
contextFileSignaturesRef,
|
|
296
|
+
setMessages,
|
|
297
|
+
setLiveMessagesState,
|
|
298
|
+
setTokenUsage,
|
|
299
|
+
manualCompaction: () => settings.manualCompaction ?? 'llm-summary',
|
|
300
|
+
debugLog,
|
|
301
|
+
showPersistenceWarning,
|
|
302
|
+
});
|
|
303
|
+
const { clearConversation, compactConversation, compactConversationWithModel } = sessionLifecycle;
|
|
304
|
+
async function openSessionPicker() {
|
|
309
305
|
await sessionRecorderRef.current?.flush().catch(showPersistenceWarning);
|
|
310
|
-
const
|
|
311
|
-
|
|
312
|
-
|
|
306
|
+
const next = await listSessions();
|
|
307
|
+
setSessions(next);
|
|
308
|
+
setSelectedSessionId(undefined);
|
|
309
|
+
if (next.length === 0) {
|
|
310
|
+
setMessages(m => [...m, { role: 'system', text: 'No saved sessions found for this workspace.' }]);
|
|
311
|
+
setMode('chat');
|
|
313
312
|
return;
|
|
314
313
|
}
|
|
315
|
-
|
|
316
|
-
const
|
|
317
|
-
|
|
318
|
-
debugLog(`Session parse error: ${error}`);
|
|
319
|
-
}
|
|
320
|
-
clearToolOutputs();
|
|
321
|
-
sessionRef.current = session;
|
|
322
|
-
conversationRef.current = conversation;
|
|
323
|
-
workStateRef.current = workState;
|
|
324
|
-
setTokenUsage({ ...EMPTY_TOKEN_USAGE });
|
|
325
|
-
setLiveMessagesState(() => []);
|
|
326
|
-
setMessages([{ role: 'system', text: `Resumed session: ${formatSession(session)}` }, ...displayMessagesFromConversation(conversation)]);
|
|
327
|
-
}
|
|
328
|
-
async function buildContextReport() {
|
|
329
|
-
const runtime = await modelWithConfig({ cwd: process.cwd() });
|
|
330
|
-
if (!runtime?.model) {
|
|
331
|
-
return 'No model provider configured. Run /provider to choose or add a provider before /context can estimate tokens.';
|
|
332
|
-
}
|
|
333
|
-
const session = { start: sessionStartRef.current, cwd: process.cwd() };
|
|
334
|
-
const assembled = await assembleRequestContext({ contextFiles, session, model: runtime.model });
|
|
335
|
-
try {
|
|
336
|
-
const messages = stripSyntheticControls(conversationRef.current);
|
|
337
|
-
const breakdown = contextBreakdown({ system: assembled.systemPrompt, contextFiles, messages, tools: assembled.availableTools });
|
|
338
|
-
const tools = breakdown.toolSchemas.map(tool => ({
|
|
339
|
-
name: tool.name,
|
|
340
|
-
tokens: tool.tokens,
|
|
341
|
-
category: assembled.toolCategories.get(tool.name) ?? 'builtin',
|
|
342
|
-
}));
|
|
343
|
-
return formatContextReport({
|
|
344
|
-
modelLabel: `${runtime.config.providerName}:${runtime.config.modelName}`,
|
|
345
|
-
systemTokens: breakdown.system,
|
|
346
|
-
projectContext: breakdown.projectContext,
|
|
347
|
-
tools,
|
|
348
|
-
messagesByRole: breakdown.messagesByRole,
|
|
349
|
-
toolResults: breakdown.toolResults,
|
|
350
|
-
toolInputs: breakdown.toolInputs,
|
|
351
|
-
syntheticControl: breakdown.syntheticControl,
|
|
352
|
-
logicalInputEstimate: breakdown.logicalInputEstimate,
|
|
353
|
-
messageCount: messages.length,
|
|
354
|
-
mcpErrors: assembled.loadedMcp?.errors ?? [],
|
|
355
|
-
});
|
|
356
|
-
}
|
|
357
|
-
finally {
|
|
358
|
-
if (assembled.loadedMcp?.clients.length)
|
|
359
|
-
await closeMcpClients(assembled.loadedMcp.clients);
|
|
360
|
-
}
|
|
314
|
+
setMode('sessions');
|
|
315
|
+
const hidden = Math.max(0, next.length - MAX_SESSION_PICKER_RESULTS);
|
|
316
|
+
setMessages(m => [...m, { role: 'system', text: `Choose a saved session (newest first)${hidden ? `. Showing ${MAX_SESSION_PICKER_RESULTS} of ${next.length}; ${hidden} older sessions are hidden.` : '.'}` }]);
|
|
361
317
|
}
|
|
362
318
|
function cancelThinking() {
|
|
363
319
|
if (!busy)
|
|
@@ -381,7 +337,11 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
|
|
|
381
337
|
function closeInputList() {
|
|
382
338
|
if (mode !== 'chat') {
|
|
383
339
|
setMode('chat');
|
|
340
|
+
setSessions([]);
|
|
341
|
+
setSelectedSessionId(undefined);
|
|
384
342
|
setModelProviderFilter(undefined);
|
|
343
|
+
setDiscoveredModels([]);
|
|
344
|
+
setSuggestedModels([]);
|
|
385
345
|
setSelectedProviderName(undefined);
|
|
386
346
|
setProviderDraft({});
|
|
387
347
|
setSkillDraft({});
|
|
@@ -392,321 +352,26 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
|
|
|
392
352
|
setMcpDraft({});
|
|
393
353
|
}
|
|
394
354
|
}
|
|
395
|
-
async function selectProvider(providerName) {
|
|
396
|
-
if (providerName === PROVIDER_CHOICES.addProvider) {
|
|
397
|
-
setProviderDraft({});
|
|
398
|
-
setMode('providerAddPreset');
|
|
399
|
-
setMessages(m => [...m, { role: 'system', text: 'Choose a provider preset, or select "custom" to enter details manually.' }]);
|
|
400
|
-
return;
|
|
401
|
-
}
|
|
402
|
-
const provider = findProvider(settings, providerName);
|
|
403
|
-
if (!provider) {
|
|
404
|
-
setMessages(m => [...m, { role: 'system', text: `No provider named ${providerName}. Use /provider and choose add provider.` }]);
|
|
405
|
-
setMode('chat');
|
|
406
|
-
return;
|
|
407
|
-
}
|
|
408
|
-
setSelectedProviderName(provider.name);
|
|
409
|
-
setMode('providerAction');
|
|
410
|
-
setMessages(m => [...m, { role: 'system', text: `${provider.name}: choose an action.` }]);
|
|
411
|
-
}
|
|
412
|
-
async function selectPreset(presetId) {
|
|
413
|
-
if (presetId === PROVIDER_CHOICES.custom) {
|
|
414
|
-
setProviderDraft({});
|
|
415
|
-
setMode('providerAddName');
|
|
416
|
-
setMessages(m => [...m, { role: 'system', text: 'Provider name? Example: openrouter, local, lmstudio.' }]);
|
|
417
|
-
return;
|
|
418
|
-
}
|
|
419
|
-
const preset = findPreset(presetId);
|
|
420
|
-
if (!preset) {
|
|
421
|
-
setMessages(m => [...m, { role: 'system', text: `Unknown preset: ${presetId}.` }]);
|
|
422
|
-
return;
|
|
423
|
-
}
|
|
424
|
-
// Check if a provider with this name already exists
|
|
425
|
-
const existingName = settings.providers?.some(p => p.name === preset.name) ? preset.id : preset.name;
|
|
426
|
-
const nameConflict = settings.providers?.some(p => p.name === existingName);
|
|
427
|
-
if (nameConflict) {
|
|
428
|
-
setMessages(m => [...m, { role: 'system', text: `Provider ${existingName} already exists. Use /provider to manage existing providers.` }]);
|
|
429
|
-
setMode('chat');
|
|
430
|
-
setProviderDraft({});
|
|
431
|
-
return;
|
|
432
|
-
}
|
|
433
|
-
setProviderDraft({ name: existingName, url: preset.baseUrl });
|
|
434
|
-
if (preset.needsApiKey) {
|
|
435
|
-
setMode('providerAddKey');
|
|
436
|
-
setMessages(m => [...m, { role: 'system', text: `${preset.name} (${preset.baseUrl})\nAPI key${preset.apiKeyHint ? ` (${preset.apiKeyHint})` : ''}?` }]);
|
|
437
|
-
}
|
|
438
|
-
else {
|
|
439
|
-
// Local/keyless: skip API key, go straight to models
|
|
440
|
-
setMode('providerAddModels');
|
|
441
|
-
const hint = preset.suggestedModels?.length ? ` Example: ${preset.suggestedModels.join(', ')}` : '';
|
|
442
|
-
setMessages(m => [...m, { role: 'system', text: `${preset.name} (${preset.baseUrl}) — no API key needed.\nComma-separated model names?${hint}` }]);
|
|
443
|
-
}
|
|
444
|
-
}
|
|
445
|
-
async function useProvider(providerName) {
|
|
446
|
-
const provider = findProvider(settings, providerName);
|
|
447
|
-
if (!provider) {
|
|
448
|
-
setMessages(m => [...m, { role: 'system', text: `No provider named ${providerName}.` }]);
|
|
449
|
-
setMode('chat');
|
|
450
|
-
setSelectedProviderName(undefined);
|
|
451
|
-
return;
|
|
452
|
-
}
|
|
453
|
-
const next = await updateSettings({ provider: provider.name });
|
|
454
|
-
setSettings(next);
|
|
455
|
-
setSelectedProviderName(undefined);
|
|
456
|
-
setModelProviderFilter(provider.name);
|
|
457
|
-
setMode('model');
|
|
458
|
-
setMessages(m => [...m, { role: 'system', text: `Provider set to ${provider.name}. Choose a model.` }]);
|
|
459
|
-
}
|
|
460
|
-
async function selectProviderAction(action) {
|
|
461
|
-
if (!selectedProviderName) {
|
|
462
|
-
setMode('provider');
|
|
463
|
-
return;
|
|
464
|
-
}
|
|
465
|
-
const provider = findProvider(settings, selectedProviderName);
|
|
466
|
-
if (!provider) {
|
|
467
|
-
setMessages(m => [...m, { role: 'system', text: `Provider ${selectedProviderName} not found.` }]);
|
|
468
|
-
setMode('chat');
|
|
469
|
-
setSelectedProviderName(undefined);
|
|
470
|
-
return;
|
|
471
|
-
}
|
|
472
|
-
if (action === PROVIDER_ACTIONS.useProvider) {
|
|
473
|
-
await useProvider(selectedProviderName);
|
|
474
|
-
return;
|
|
475
|
-
}
|
|
476
|
-
const actionResult = providerActionResult(action, provider);
|
|
477
|
-
if (actionResult.selectedName === undefined)
|
|
478
|
-
setSelectedProviderName(undefined);
|
|
479
|
-
if (actionResult.mode)
|
|
480
|
-
setMode(actionResult.mode);
|
|
481
|
-
showWizardMessage(actionResult.message);
|
|
482
|
-
}
|
|
483
|
-
async function selectModel(selector) {
|
|
484
|
-
const scopedSelector = modelProviderFilter ? `${modelProviderFilter}:${selector}` : selector;
|
|
485
|
-
const resolved = resolveModelSelector(settings, scopedSelector);
|
|
486
|
-
if (resolved.status === 'ambiguous') {
|
|
487
|
-
setMessages(m => [...m, { role: 'system', text: `Model ${resolved.model} exists on multiple providers: ${resolved.providers.map(provider => modelSelector(provider, resolved.model)).join(', ')}` }]);
|
|
488
|
-
return;
|
|
489
|
-
}
|
|
490
|
-
if (resolved.status === 'missing') {
|
|
491
|
-
setMessages(m => [...m, { role: 'system', text: `No configured model named ${selector}. Use /provider, select a provider, then choose add models.` }]);
|
|
492
|
-
return;
|
|
493
|
-
}
|
|
494
|
-
const next = await updateSettings({ provider: resolved.provider.name, model: resolved.model });
|
|
495
|
-
setSettings(next);
|
|
496
|
-
setModelProviderFilter(undefined);
|
|
497
|
-
setMode('chat');
|
|
498
|
-
setMessages(m => [...m, { role: 'system', text: `Model set to ${resolved.model} on ${resolved.provider.name}.\n\n${startupProviderInfo(next)}` }]);
|
|
499
|
-
}
|
|
500
|
-
async function appendModelsToProvider(modelsValue) {
|
|
501
|
-
const result = providerAppendModels(settings, selectedProviderName, modelsValue);
|
|
502
|
-
if (!result.provider) {
|
|
503
|
-
setMessages(m => [...m, { role: 'system', text: result.message }]);
|
|
504
|
-
setMode('chat');
|
|
505
|
-
return;
|
|
506
|
-
}
|
|
507
|
-
if (!result.settingsPatch) {
|
|
508
|
-
setMessages(m => [...m, { role: 'system', text: result.message }]);
|
|
509
|
-
return;
|
|
510
|
-
}
|
|
511
|
-
const next = await updateSettings(result.settingsPatch);
|
|
512
|
-
setSettings(next);
|
|
513
|
-
setSelectedProviderName(undefined);
|
|
514
|
-
setModelProviderFilter(result.provider.name);
|
|
515
|
-
setMode('model');
|
|
516
|
-
setMessages(m => [...m, { role: 'system', text: result.message }]);
|
|
517
|
-
}
|
|
518
|
-
async function finishProviderAdd(modelsValue) {
|
|
519
|
-
const result = providerFinishAdd(settings, providerDraft, modelsValue);
|
|
520
|
-
if (!result.provider || !result.settingsPatch) {
|
|
521
|
-
setMessages(m => [...m, { role: 'system', text: result.message }]);
|
|
522
|
-
setMode('chat');
|
|
523
|
-
setProviderDraft({});
|
|
524
|
-
return;
|
|
525
|
-
}
|
|
526
|
-
const next = await updateSettings(result.settingsPatch);
|
|
527
|
-
setSettings(next);
|
|
528
|
-
setProviderDraft({});
|
|
529
|
-
setModelProviderFilter(result.provider.name);
|
|
530
|
-
setMode('model');
|
|
531
|
-
setMessages(m => [...m, { role: 'system', text: result.message }]);
|
|
532
|
-
}
|
|
533
|
-
// --- LSP wizard handlers (mirror the provider wizard) ---
|
|
534
355
|
function showWizardMessage(message) {
|
|
535
356
|
if (message)
|
|
536
357
|
setMessages(m => [...m, { role: 'system', text: message }]);
|
|
537
358
|
}
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
if (result.settingsPatch)
|
|
555
|
-
setSettings(await updateSettings(result.settingsPatch));
|
|
556
|
-
if (result.mode)
|
|
557
|
-
setMode(result.mode);
|
|
558
|
-
showWizardMessage(result.message);
|
|
559
|
-
}
|
|
560
|
-
async function selectLspAction(action) {
|
|
561
|
-
const result = selectLspActionResult(settings, selectedLspName, action);
|
|
562
|
-
if (result.settingsPatch)
|
|
563
|
-
setSettings(await updateSettings(result.settingsPatch));
|
|
564
|
-
if ('selectedName' in result)
|
|
565
|
-
setSelectedLspName(result.selectedName);
|
|
566
|
-
if (result.mode)
|
|
567
|
-
setMode(result.mode);
|
|
568
|
-
showWizardMessage(result.message);
|
|
569
|
-
}
|
|
570
|
-
async function finishLspCustom(commandLine) {
|
|
571
|
-
const result = finishLspCustomResult(settings, lspDraft.name, commandLine);
|
|
572
|
-
if (result.settingsPatch)
|
|
573
|
-
setSettings(await updateSettings(result.settingsPatch));
|
|
574
|
-
if (result.clearDraft)
|
|
575
|
-
setLspDraft({});
|
|
576
|
-
if (result.mode)
|
|
577
|
-
setMode(result.mode);
|
|
578
|
-
showWizardMessage(result.message);
|
|
579
|
-
}
|
|
580
|
-
// --- MCP wizard handlers (mirror the provider wizard) ---
|
|
581
|
-
async function selectMcpServer(serverName) {
|
|
582
|
-
const result = selectMcpServerResult(settings, serverName);
|
|
583
|
-
if (result.clearDraft)
|
|
584
|
-
setMcpDraft({});
|
|
585
|
-
if (serverName === SERVER_CHOICES.addServer)
|
|
586
|
-
setMode('mcpAddPreset');
|
|
587
|
-
else if (result.mode)
|
|
588
|
-
setMode(result.mode);
|
|
589
|
-
if (result.selectedName !== undefined)
|
|
590
|
-
setSelectedMcpName(result.selectedName);
|
|
591
|
-
showWizardMessage(result.message);
|
|
592
|
-
}
|
|
593
|
-
async function selectMcpPreset(presetId) {
|
|
594
|
-
const result = selectMcpPresetResult(settings, presetId);
|
|
595
|
-
if (result.clearDraft)
|
|
596
|
-
setMcpDraft({});
|
|
597
|
-
if (result.draft)
|
|
598
|
-
setMcpDraft(result.draft);
|
|
599
|
-
if (result.mode)
|
|
600
|
-
setMode(result.mode);
|
|
601
|
-
showWizardMessage(result.message);
|
|
602
|
-
}
|
|
603
|
-
async function selectMcpAction(action) {
|
|
604
|
-
const result = selectMcpActionResult(settings, selectedMcpName, action);
|
|
605
|
-
if (result.settingsPatch)
|
|
606
|
-
setSettings(await updateSettings(result.settingsPatch));
|
|
607
|
-
if ('selectedName' in result)
|
|
608
|
-
setSelectedMcpName(result.selectedName);
|
|
609
|
-
if (result.mode)
|
|
610
|
-
setMode(result.mode);
|
|
611
|
-
showWizardMessage(result.message);
|
|
612
|
-
}
|
|
613
|
-
async function finishMcpCustom(keyValue, draft = mcpDraft) {
|
|
614
|
-
const result = finishMcpCustomResult(settings, draft, keyValue);
|
|
615
|
-
if (result.settingsPatch)
|
|
616
|
-
setSettings(await updateSettings(result.settingsPatch));
|
|
617
|
-
if (result.clearDraft)
|
|
618
|
-
setMcpDraft({});
|
|
619
|
-
if (result.mode)
|
|
620
|
-
setMode(result.mode);
|
|
621
|
-
showWizardMessage(result.message);
|
|
622
|
-
}
|
|
623
|
-
async function setMcpServerKey(keyValue) {
|
|
624
|
-
const result = setMcpServerKeyResult(settings, selectedMcpName, keyValue);
|
|
625
|
-
if (result.settingsPatch)
|
|
626
|
-
setSettings(await updateSettings(result.settingsPatch));
|
|
627
|
-
if ('selectedName' in result)
|
|
628
|
-
setSelectedMcpName(result.selectedName);
|
|
629
|
-
if (result.mode)
|
|
630
|
-
setMode(result.mode);
|
|
631
|
-
showWizardMessage(result.message);
|
|
632
|
-
}
|
|
633
|
-
// --- Skills wizard handlers (mirror the provider/LSP/MCP wizards) ---
|
|
634
|
-
async function selectSkill(name) {
|
|
635
|
-
const result = selectSkillResult(skills, name);
|
|
636
|
-
if (result.clearDraft)
|
|
637
|
-
setSkillDraft({});
|
|
638
|
-
if ('selectedName' in result)
|
|
639
|
-
setSelectedSkillName(result.selectedName);
|
|
640
|
-
if (result.mode)
|
|
641
|
-
setMode(result.mode);
|
|
642
|
-
showWizardMessage(result.message);
|
|
643
|
-
}
|
|
644
|
-
async function selectSkillAction(action) {
|
|
645
|
-
const result = selectSkillActionResult(settings, skills, selectedSkillName, action);
|
|
646
|
-
if (result.settingsPatch)
|
|
647
|
-
setSettings(await updateSettings(result.settingsPatch));
|
|
648
|
-
if ('selectedName' in result)
|
|
649
|
-
setSelectedSkillName(result.selectedName);
|
|
650
|
-
if (result.mode)
|
|
651
|
-
setMode(result.mode);
|
|
652
|
-
if (result.validate && result.skill) {
|
|
653
|
-
const { loadSkill } = await import('../../skills/SkillLoader.js');
|
|
654
|
-
try {
|
|
655
|
-
const loaded = await loadSkill(result.skill.dir, 'global');
|
|
656
|
-
showWizardMessage(loaded ? `Valid: ${loaded.name}` : 'No SKILL.md found');
|
|
657
|
-
}
|
|
658
|
-
catch (error) {
|
|
659
|
-
const text = error instanceof Error ? error.message : String(error);
|
|
660
|
-
showWizardMessage(`Invalid skill: ${text}`);
|
|
661
|
-
}
|
|
662
|
-
return;
|
|
663
|
-
}
|
|
664
|
-
showWizardMessage(result.message);
|
|
665
|
-
}
|
|
666
|
-
async function captureSkillName(value) {
|
|
667
|
-
const dirName = toSkillDirName(value);
|
|
668
|
-
if (!dirName) {
|
|
669
|
-
setMessages(m => [...m, { role: 'system', text: 'Skill name must contain at least one letter or number. Try again, or press ESC to cancel.' }]);
|
|
670
|
-
return;
|
|
671
|
-
}
|
|
672
|
-
const registry = await loadSkillRegistry();
|
|
673
|
-
if (registry.skills.has(dirName)) {
|
|
674
|
-
setMessages(m => [...m, { role: 'system', text: `A skill named "${dirName}" already exists. Pick another name, or press ESC to cancel.` }]);
|
|
675
|
-
return;
|
|
676
|
-
}
|
|
677
|
-
setSkillDraft(d => ({ ...d, name: dirName }));
|
|
678
|
-
setMode('skillsAddDescription');
|
|
679
|
-
setMessages(m => [...m, { role: 'system', text: `Describe what "${dirName}" should do. This is the work the LLM will expand into the skill body.` }]);
|
|
680
|
-
}
|
|
681
|
-
async function captureSkillDescription(value) {
|
|
682
|
-
const result = captureSkillDescriptionResult(value, skillDraft.name);
|
|
683
|
-
if (result.message) {
|
|
684
|
-
const message = result.message;
|
|
685
|
-
setMessages(m => [...m, { role: 'system', text: message }]);
|
|
686
|
-
}
|
|
687
|
-
if (result.mode === 'chat')
|
|
688
|
-
setMode('chat');
|
|
689
|
-
if (result.clearDraft)
|
|
690
|
-
setSkillDraft({});
|
|
691
|
-
if (result.description && result.draftName) {
|
|
692
|
-
const name = result.draftName;
|
|
693
|
-
const description = result.description;
|
|
694
|
-
setBusyLabel(result.busyLabel ?? 'Creating skill');
|
|
695
|
-
setBusyWithHeartbeat(true);
|
|
696
|
-
try {
|
|
697
|
-
const created = await createSkill({ name, description });
|
|
698
|
-
setMessages(m => [...m, { role: 'system', text: skillCreationMessage(created.name, created.file) }]);
|
|
699
|
-
await refreshSkills();
|
|
700
|
-
}
|
|
701
|
-
catch (error) {
|
|
702
|
-
setMessages(m => [...m, { role: 'system', text: skillCreationFailure(error) }]);
|
|
703
|
-
}
|
|
704
|
-
finally {
|
|
705
|
-
setBusyWithHeartbeat(false);
|
|
706
|
-
setBusyLabel(thinkingLabelForSettings(settings));
|
|
707
|
-
}
|
|
708
|
-
}
|
|
709
|
-
}
|
|
359
|
+
// Wizard/picker submit dispatch lives in one table-driven module with a
|
|
360
|
+
// shared settings-patch applier (CR-006). Rebuilt every render so handlers
|
|
361
|
+
// see current state without new React state.
|
|
362
|
+
const wizard = createWizardDispatch({
|
|
363
|
+
settings, skills, modelProviderFilter, selectedProviderName, selectedSkillName, selectedLspName, selectedMcpName,
|
|
364
|
+
sessions, selectedSessionId,
|
|
365
|
+
providerDraft, lspDraft, mcpDraft, skillDraft,
|
|
366
|
+
setMode, setSettings,
|
|
367
|
+
setSelectedProviderName, setSelectedSkillName, setSelectedLspName, setSelectedMcpName, setSelectedSessionId,
|
|
368
|
+
resumeSessionById: sessionLifecycle.resumeSessionById,
|
|
369
|
+
forkSessionById: sessionLifecycle.forkSessionById,
|
|
370
|
+
setModelProviderFilter, setProviderDraft, setSkillDraft, setLspDraft, setMcpDraft, setDiscoveredModels, setSuggestedModels,
|
|
371
|
+
showMessage: showWizardMessage, refreshSkills,
|
|
372
|
+
setBusyLabel, setBusy: setBusyWithHeartbeat,
|
|
373
|
+
idleBusyLabel: thinkingLabelForSettings(settings),
|
|
374
|
+
});
|
|
710
375
|
async function submit(value) {
|
|
711
376
|
if (settingsError) {
|
|
712
377
|
try {
|
|
@@ -728,7 +393,10 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
|
|
|
728
393
|
queueFollowUp(value);
|
|
729
394
|
return;
|
|
730
395
|
}
|
|
731
|
-
|
|
396
|
+
// Any new submission supersedes a paused-task resume affordance.
|
|
397
|
+
if (pausedResume)
|
|
398
|
+
setPausedResume(undefined);
|
|
399
|
+
const providerEffects = transitionProviderField({ mode, value, settings, draft: providerDraft });
|
|
732
400
|
if (providerEffects) {
|
|
733
401
|
for (const effect of providerEffects) {
|
|
734
402
|
if (effect.type === 'message')
|
|
@@ -741,6 +409,11 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
|
|
|
741
409
|
else
|
|
742
410
|
setProviderDraft(draft => ({ ...draft, ...effect.patch }));
|
|
743
411
|
}
|
|
412
|
+
else if (effect.type === 'discover-provider-models') {
|
|
413
|
+
// The draft patch above is still pending React state, so discovery
|
|
414
|
+
// receives the merged draft explicitly (same pattern as MCP stdio).
|
|
415
|
+
await wizard.discoverProviderModelsForDraft(effect.draft);
|
|
416
|
+
}
|
|
744
417
|
}
|
|
745
418
|
return;
|
|
746
419
|
}
|
|
@@ -754,209 +427,12 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
|
|
|
754
427
|
else if (effect.type === 'mcp-draft')
|
|
755
428
|
setMcpDraft(draft => ({ ...draft, ...effect.patch }));
|
|
756
429
|
else if (effect.type === 'finish-mcp-stdio')
|
|
757
|
-
await finishMcpCustom(undefined, effect.draft);
|
|
758
|
-
}
|
|
759
|
-
return;
|
|
760
|
-
}
|
|
761
|
-
if (mode === 'skills') {
|
|
762
|
-
await selectSkill(value);
|
|
763
|
-
return;
|
|
764
|
-
}
|
|
765
|
-
if (mode === 'skillsAction') {
|
|
766
|
-
await selectSkillAction(value);
|
|
767
|
-
return;
|
|
768
|
-
}
|
|
769
|
-
if (mode === 'skillsAddName') {
|
|
770
|
-
await captureSkillName(value);
|
|
771
|
-
return;
|
|
772
|
-
}
|
|
773
|
-
if (mode === 'skillsAddDescription') {
|
|
774
|
-
await captureSkillDescription(value);
|
|
775
|
-
return;
|
|
776
|
-
}
|
|
777
|
-
if (mode === 'skillsConfirmRemove') {
|
|
778
|
-
const result = skillConfirmRemove(settings, skills, selectedSkillName, value);
|
|
779
|
-
if (result.message) {
|
|
780
|
-
const message = result.message;
|
|
781
|
-
setMessages(m => [...m, { role: 'system', text: message }]);
|
|
782
|
-
}
|
|
783
|
-
if (result.selectedName === undefined)
|
|
784
|
-
setSelectedSkillName(undefined);
|
|
785
|
-
if (result.mode === 'chat')
|
|
786
|
-
setMode('chat');
|
|
787
|
-
if (result.removedDir)
|
|
788
|
-
await fs.remove(result.removedDir);
|
|
789
|
-
if (result.settingsPatch)
|
|
790
|
-
setSettings(await updateSettings(result.settingsPatch));
|
|
791
|
-
if (result.removedDir)
|
|
792
|
-
await refreshSkills();
|
|
793
|
-
return;
|
|
794
|
-
}
|
|
795
|
-
if (mode === 'provider') {
|
|
796
|
-
await selectProvider(value);
|
|
797
|
-
return;
|
|
798
|
-
}
|
|
799
|
-
if (mode === 'providerAction') {
|
|
800
|
-
await selectProviderAction(value);
|
|
801
|
-
return;
|
|
802
|
-
}
|
|
803
|
-
if (mode === 'providerAddPreset') {
|
|
804
|
-
await selectPreset(value);
|
|
805
|
-
return;
|
|
806
|
-
}
|
|
807
|
-
if (mode === 'model') {
|
|
808
|
-
await selectModel(value);
|
|
809
|
-
return;
|
|
810
|
-
}
|
|
811
|
-
if (mode === 'providerAddModels') {
|
|
812
|
-
await finishProviderAdd(value);
|
|
813
|
-
return;
|
|
814
|
-
}
|
|
815
|
-
if (mode === 'providerAppendModels') {
|
|
816
|
-
await appendModelsToProvider(value);
|
|
817
|
-
return;
|
|
818
|
-
}
|
|
819
|
-
if (mode === 'providerSetKey') {
|
|
820
|
-
const result = providerSetKey(settings, selectedProviderName, value);
|
|
821
|
-
if (!result.provider) {
|
|
822
|
-
setMessages(m => [...m, { role: 'system', text: result.message }]);
|
|
823
|
-
setMode('chat');
|
|
824
|
-
return;
|
|
825
|
-
}
|
|
826
|
-
if (!result.settingsPatch) {
|
|
827
|
-
setMessages(m => [...m, { role: 'system', text: result.message }]);
|
|
828
|
-
return;
|
|
829
|
-
}
|
|
830
|
-
setSettings(await updateSettings(result.settingsPatch));
|
|
831
|
-
setSelectedProviderName(undefined);
|
|
832
|
-
setMode('chat');
|
|
833
|
-
setMessages(m => [...m, { role: 'system', text: result.message }]);
|
|
834
|
-
return;
|
|
835
|
-
}
|
|
836
|
-
if (mode === 'providerRemoveModels') {
|
|
837
|
-
const result = providerRemoveModels(settings, selectedProviderName, value);
|
|
838
|
-
if (!result.provider) {
|
|
839
|
-
setMessages(m => [...m, { role: 'system', text: result.message }]);
|
|
840
|
-
setMode('chat');
|
|
841
|
-
return;
|
|
842
|
-
}
|
|
843
|
-
if (!result.settingsPatch) {
|
|
844
|
-
setMessages(m => [...m, { role: 'system', text: result.message }]);
|
|
845
|
-
return;
|
|
846
|
-
}
|
|
847
|
-
const next = await updateSettings(result.settingsPatch);
|
|
848
|
-
setSettings(next);
|
|
849
|
-
setSelectedProviderName(undefined);
|
|
850
|
-
setMode('chat');
|
|
851
|
-
setMessages(m => [...m, { role: 'system', text: result.message }]);
|
|
852
|
-
return;
|
|
853
|
-
}
|
|
854
|
-
if (mode === 'providerConfirmRemove') {
|
|
855
|
-
const provider = selectedProviderName ? findProvider(settings, selectedProviderName) : undefined;
|
|
856
|
-
if (!provider) {
|
|
857
|
-
setMessages(m => [...m, { role: 'system', text: 'No provider selected.' }]);
|
|
858
|
-
setMode('chat');
|
|
859
|
-
return;
|
|
860
|
-
}
|
|
861
|
-
if (!isYesConfirmation(value)) {
|
|
862
|
-
setMessages(m => [...m, { role: 'system', text: 'Cancelled. Provider not removed.' }]);
|
|
863
|
-
setSelectedProviderName(undefined);
|
|
864
|
-
setMode('chat');
|
|
865
|
-
return;
|
|
866
|
-
}
|
|
867
|
-
const result = providerRemove(settings, selectedProviderName);
|
|
868
|
-
const next = await updateSettings(result.settingsPatch ?? {});
|
|
869
|
-
setSettings(next);
|
|
870
|
-
setSelectedProviderName(undefined);
|
|
871
|
-
setMode('chat');
|
|
872
|
-
setMessages(m => [...m, { role: 'system', text: result.message }]);
|
|
873
|
-
return;
|
|
874
|
-
}
|
|
875
|
-
if (mode === 'lsp') {
|
|
876
|
-
await selectLspServer(value);
|
|
877
|
-
return;
|
|
878
|
-
}
|
|
879
|
-
if (mode === 'lspAction') {
|
|
880
|
-
await selectLspAction(value);
|
|
881
|
-
return;
|
|
882
|
-
}
|
|
883
|
-
if (mode === 'lspAddPreset') {
|
|
884
|
-
await selectLspPreset(value);
|
|
885
|
-
return;
|
|
886
|
-
}
|
|
887
|
-
if (mode === 'lspAddName') {
|
|
888
|
-
const result = captureLspName(settings, value);
|
|
889
|
-
if (result.message) {
|
|
890
|
-
showWizardMessage(result.message);
|
|
891
|
-
return;
|
|
892
|
-
}
|
|
893
|
-
if (result.draft)
|
|
894
|
-
setLspDraft({ name: result.draft.name });
|
|
895
|
-
if (result.nextMode)
|
|
896
|
-
setMode(result.nextMode);
|
|
897
|
-
showWizardMessage(result.systemMessage);
|
|
898
|
-
return;
|
|
899
|
-
}
|
|
900
|
-
if (mode === 'lspAddCommand') {
|
|
901
|
-
await finishLspCustom(value);
|
|
902
|
-
return;
|
|
903
|
-
}
|
|
904
|
-
if (mode === 'lspConfirmRemove') {
|
|
905
|
-
if (!selectedLspName) {
|
|
906
|
-
setMode('chat');
|
|
907
|
-
return;
|
|
908
|
-
}
|
|
909
|
-
if (!isYesConfirmation(value)) {
|
|
910
|
-
setMessages(m => [...m, { role: 'system', text: 'Cancelled. LSP server not removed.' }]);
|
|
911
|
-
setSelectedLspName(undefined);
|
|
912
|
-
setMode('chat');
|
|
913
|
-
return;
|
|
430
|
+
await wizard.finishMcpCustom(undefined, effect.draft);
|
|
914
431
|
}
|
|
915
|
-
const next = await updateSettings({ lspServers: removeLspServer(settings, selectedLspName) });
|
|
916
|
-
setSettings(next);
|
|
917
|
-
setMessages(m => [...m, { role: 'system', text: `Removed LSP server ${selectedLspName}.` }]);
|
|
918
|
-
setSelectedLspName(undefined);
|
|
919
|
-
setMode('chat');
|
|
920
|
-
return;
|
|
921
|
-
}
|
|
922
|
-
if (mode === 'mcp') {
|
|
923
|
-
await selectMcpServer(value);
|
|
924
|
-
return;
|
|
925
|
-
}
|
|
926
|
-
if (mode === 'mcpAction') {
|
|
927
|
-
await selectMcpAction(value);
|
|
928
|
-
return;
|
|
929
|
-
}
|
|
930
|
-
if (mode === 'mcpAddPreset') {
|
|
931
|
-
await selectMcpPreset(value);
|
|
932
432
|
return;
|
|
933
433
|
}
|
|
934
|
-
if (mode
|
|
935
|
-
await finishMcpCustom(value);
|
|
936
|
-
return;
|
|
937
|
-
}
|
|
938
|
-
if (mode === 'mcpSetKey') {
|
|
939
|
-
await setMcpServerKey(value);
|
|
940
|
-
return;
|
|
941
|
-
}
|
|
942
|
-
if (mode === 'mcpConfirmRemove') {
|
|
943
|
-
if (!selectedMcpName) {
|
|
944
|
-
setMode('chat');
|
|
945
|
-
return;
|
|
946
|
-
}
|
|
947
|
-
if (!isYesConfirmation(value)) {
|
|
948
|
-
setMessages(m => [...m, { role: 'system', text: 'Cancelled. MCP server not removed.' }]);
|
|
949
|
-
setSelectedMcpName(undefined);
|
|
950
|
-
setMode('chat');
|
|
951
|
-
return;
|
|
952
|
-
}
|
|
953
|
-
const next = await updateSettings({ mcpServers: removeMcpServer(settings, selectedMcpName) });
|
|
954
|
-
setSettings(next);
|
|
955
|
-
setMessages(m => [...m, { role: 'system', text: `Removed MCP server ${selectedMcpName}.` }]);
|
|
956
|
-
setSelectedMcpName(undefined);
|
|
957
|
-
setMode('chat');
|
|
434
|
+
if (await wizard.dispatch(mode, value))
|
|
958
435
|
return;
|
|
959
|
-
}
|
|
960
436
|
const invokedSkill = skillInvocation(value);
|
|
961
437
|
if (invokedSkill) {
|
|
962
438
|
const argumentText = invokedSkill.args ? `\nUser-provided skill arguments: ${invokedSkill.args}` : '';
|
|
@@ -975,12 +451,18 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
|
|
|
975
451
|
lastAssistantTextRef.current = '';
|
|
976
452
|
setLiveMessagesState(() => []);
|
|
977
453
|
setMessages([{ role: 'system', text: 'Started fresh. The fog parts.' }]);
|
|
978
|
-
await startNewSession('
|
|
454
|
+
await sessionLifecycle.startNewSession('New session started.');
|
|
455
|
+
},
|
|
456
|
+
resumeSession: noSession ? undefined : async (id) => {
|
|
457
|
+
if (id)
|
|
458
|
+
await sessionLifecycle.resumeSessionById(id);
|
|
459
|
+
else
|
|
460
|
+
await openSessionPicker();
|
|
979
461
|
},
|
|
980
|
-
resumeSession: resumeLatestSession,
|
|
981
462
|
sessionInfo: () => sessionRef.current ? formatSession(sessionRef.current) : 'Session persistence is off.',
|
|
982
463
|
compactConversation,
|
|
983
|
-
|
|
464
|
+
compactConversationLlm: compactConversationWithModel,
|
|
465
|
+
runAgentTurn: (prompt, displayValue, options) => doAgentTurn(prompt, displayValue, options),
|
|
984
466
|
refreshContextFiles: async () => {
|
|
985
467
|
const files = await readContextFiles().catch(() => contextFiles);
|
|
986
468
|
setContextFiles(files);
|
|
@@ -992,7 +474,7 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
|
|
|
992
474
|
setSettings(next);
|
|
993
475
|
return next;
|
|
994
476
|
},
|
|
995
|
-
getContextReport:
|
|
477
|
+
getContextReport: () => buildContextReport({ sessionStart: sessionStartRef.current, contextFiles, conversation: conversationRef.current }),
|
|
996
478
|
};
|
|
997
479
|
let result;
|
|
998
480
|
try {
|
|
@@ -1004,6 +486,7 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
|
|
|
1004
486
|
return;
|
|
1005
487
|
}
|
|
1006
488
|
if (result === 'exit') {
|
|
489
|
+
await teardownBackgroundProcesses().catch(showPersistenceWarning);
|
|
1007
490
|
await sessionRecorderRef.current?.flush().catch(showPersistenceWarning);
|
|
1008
491
|
if (llmLogRef.current)
|
|
1009
492
|
await endLlmLog(llmLogRef.current).catch(showPersistenceWarning);
|
|
@@ -1015,9 +498,43 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
|
|
|
1015
498
|
}
|
|
1016
499
|
return;
|
|
1017
500
|
}
|
|
1018
|
-
await
|
|
501
|
+
const prepared = await prepareUserInput(value);
|
|
502
|
+
if (!prepared)
|
|
503
|
+
return;
|
|
504
|
+
await doAgentTurn(prepared.value, prepared.displayValue, prepared.options);
|
|
505
|
+
}
|
|
506
|
+
// F03: resolve @image mentions in a prompt the user typed into attachments and
|
|
507
|
+
// gate them on the active provider's explicit capability before any model call.
|
|
508
|
+
// Applied only to genuine user input (direct chat and queued follow-ups), never
|
|
509
|
+
// to synthetic control prompts (/init, /fleet, skill invocations). Resolution
|
|
510
|
+
// errors and capability rejections surface an actionable system message and
|
|
511
|
+
// return undefined instead of starting a turn.
|
|
512
|
+
async function prepareUserInput(value) {
|
|
513
|
+
let resolved;
|
|
514
|
+
try {
|
|
515
|
+
resolved = await resolveImageAttachments(value);
|
|
516
|
+
}
|
|
517
|
+
catch (error) {
|
|
518
|
+
const text = error instanceof Error ? error.message : String(error);
|
|
519
|
+
setMessages(m => [...m, { role: 'system', text }]);
|
|
520
|
+
return undefined;
|
|
521
|
+
}
|
|
522
|
+
const blessed = await resolveReadBlessings(resolved.text);
|
|
523
|
+
if (resolved.attachments.length === 0 && blessed.blessedPaths.length === 0)
|
|
524
|
+
return { value, options: {} };
|
|
525
|
+
const gateError = imageCapabilityError(activeProvider(settings));
|
|
526
|
+
if (resolved.attachments.length > 0 && gateError) {
|
|
527
|
+
setMessages(m => [...m, { role: 'system', text: gateError }]);
|
|
528
|
+
return undefined;
|
|
529
|
+
}
|
|
530
|
+
const displayValue = [resolved.text, ...resolved.attachments.map(imageAttachmentLine)].filter(Boolean).join('\n');
|
|
531
|
+
return {
|
|
532
|
+
value: resolved.text || IMAGE_ONLY_PROMPT_TEXT,
|
|
533
|
+
displayValue,
|
|
534
|
+
options: { attachments: resolved.attachments, blessedPaths: blessed.blessedPaths },
|
|
535
|
+
};
|
|
1019
536
|
}
|
|
1020
|
-
async function doAgentTurn(value, displayValue) {
|
|
537
|
+
async function doAgentTurn(value, displayValue, turnOptions = {}) {
|
|
1021
538
|
setDebugLogs([]);
|
|
1022
539
|
// When every task is already completed, start the new turn with a clean
|
|
1023
540
|
// slate: the task bar clears (nothing shown for simple questions) and the
|
|
@@ -1028,16 +545,54 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
|
|
|
1028
545
|
setTaskBarPadding(0);
|
|
1029
546
|
await clearTasksFromStore().catch(() => undefined);
|
|
1030
547
|
}
|
|
1031
|
-
await runSingleAgentTurn(value, displayValue);
|
|
548
|
+
await runSingleAgentTurn(value, displayValue, turnOptions);
|
|
1032
549
|
while (followUpQueueRef.current.length > 0) {
|
|
1033
550
|
const next = followUpQueueRef.current[0];
|
|
1034
551
|
followUpQueueRef.current = followUpQueueRef.current.slice(1);
|
|
1035
552
|
setQueuedFollowUps(followUpQueueRef.current);
|
|
1036
553
|
setMessages(m => [...m, { role: 'system', text: `Running queued follow-up: ${next}` }]);
|
|
1037
|
-
await
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
554
|
+
const preparedFollowUp = await prepareUserInput(next);
|
|
555
|
+
if (!preparedFollowUp)
|
|
556
|
+
continue;
|
|
557
|
+
await runSingleAgentTurn(preparedFollowUp.value, preparedFollowUp.displayValue, preparedFollowUp.options);
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
/**
|
|
561
|
+
* Resume a paused turn against the preserved conversation (no re-added user
|
|
562
|
+
* message). An idle-stall resume continues the same logical turn's bounded
|
|
563
|
+
* retry pool; an incomplete-goal resume starts a fresh logical turn (its
|
|
564
|
+
* budget was exhausted) nudged to pick up the remaining concrete work.
|
|
565
|
+
*/
|
|
566
|
+
/**
|
|
567
|
+
* Explicitly resume a genuinely paused goal (automatic continuation already
|
|
568
|
+
* ran): an idle-stall resume continues the bounded retry pool; an
|
|
569
|
+
* incomplete-goal resume restarts the supervisor from the stored checkpoint.
|
|
570
|
+
* Both ride the preserved conversation — no completed mutations are replayed.
|
|
571
|
+
*/
|
|
572
|
+
async function resumePausedTask() {
|
|
573
|
+
const resume = pausedResume;
|
|
574
|
+
if (!resume || busy)
|
|
575
|
+
return;
|
|
576
|
+
setPausedResume(undefined);
|
|
577
|
+
setMessages(m => [...m, { role: 'system', text: 'Resuming the unfinished goal; completed work is preserved in the conversation.' }]);
|
|
578
|
+
const resumeFrom = resume.kind === 'incomplete-goal' && resume.checkpoint
|
|
579
|
+
? { kind: 'incomplete-goal', checkpoint: resume.checkpoint }
|
|
580
|
+
: { kind: 'model-stream-idle', retryAttempt: resume.retryAttempt };
|
|
581
|
+
await runSingleAgentTurn(resume.request, undefined, {}, resumeFrom);
|
|
582
|
+
}
|
|
583
|
+
/**
|
|
584
|
+
* The PromptSession shared by every turn of the active session. Returning a
|
|
585
|
+
* stable object (not a fresh literal per turn) is what makes once-per-session
|
|
586
|
+
* affordances actually once-per-session; a new session identity yields a
|
|
587
|
+
* fresh object so they fire again at its start.
|
|
588
|
+
*/
|
|
589
|
+
function currentPromptSession() {
|
|
590
|
+
if (promptSessionRef.current.identity !== sessionStartRef.current) {
|
|
591
|
+
promptSessionRef.current = { identity: sessionStartRef.current, value: { start: sessionStartRef.current, cwd: process.cwd() } };
|
|
592
|
+
}
|
|
593
|
+
return promptSessionRef.current.value;
|
|
594
|
+
}
|
|
595
|
+
async function runSingleAgentTurn(value, displayValue, turnOptions = {}, resumeExisting) {
|
|
1041
596
|
const sessionRecorder = sessionRecorderRef.current;
|
|
1042
597
|
const finalizeMessage = (msg) => {
|
|
1043
598
|
if (msg.hidden)
|
|
@@ -1046,100 +601,124 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
|
|
|
1046
601
|
setMessages(m => [...m, ordered]);
|
|
1047
602
|
sessionRecorder.recordUiMessage(ordered);
|
|
1048
603
|
};
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
setLiveMessagesState(m => m.filter(msg => msg.id !== id));
|
|
1064
|
-
finalizeMessage(updated);
|
|
604
|
+
// The logical-goal supervisor owns this submission: recoverable-incomplete
|
|
605
|
+
// physical turns (including step/tool budget boundaries) continue
|
|
606
|
+
// automatically; per-turn limits stay safety boundaries. An explicit
|
|
607
|
+
// resumeFrom restarts a genuinely paused goal from its checkpoint/pool.
|
|
608
|
+
const goalResult = await runAgentGoal({
|
|
609
|
+
request: value,
|
|
610
|
+
displayValue,
|
|
611
|
+
contextFiles,
|
|
612
|
+
session: currentPromptSession(),
|
|
613
|
+
callbacks: {
|
|
614
|
+
addMessage: msg => {
|
|
615
|
+
const ordered = withDisplayOrder(msg);
|
|
616
|
+
if (ordered.streaming) {
|
|
617
|
+
setLiveMessagesState(m => [...m, ordered]);
|
|
1065
618
|
return;
|
|
1066
619
|
}
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
620
|
+
finalizeMessage(ordered);
|
|
621
|
+
},
|
|
622
|
+
updateMessage: (id, update) => {
|
|
623
|
+
const liveMessage = liveMessagesRef.current.find(msg => msg.id === id);
|
|
624
|
+
if (liveMessage) {
|
|
625
|
+
const updated = { ...liveMessage, ...update };
|
|
626
|
+
if (updated.streaming === false) {
|
|
627
|
+
setLiveMessagesState(m => m.filter(msg => msg.id !== id));
|
|
628
|
+
finalizeMessage(updated);
|
|
629
|
+
return;
|
|
630
|
+
}
|
|
631
|
+
setLiveMessagesState(m => m.map(msg => msg.id === id ? { ...msg, ...update } : msg));
|
|
632
|
+
return;
|
|
633
|
+
}
|
|
634
|
+
setMessages(m => m.map(msg => msg.id === id ? { ...msg, ...update } : msg));
|
|
635
|
+
},
|
|
636
|
+
setConversation: msgs => {
|
|
637
|
+
conversationRef.current = msgs;
|
|
638
|
+
sessionRecorder.recordConversation(msgs);
|
|
639
|
+
},
|
|
640
|
+
setBusy: setBusyWithHeartbeat,
|
|
641
|
+
setBusyLabel,
|
|
642
|
+
debugLog,
|
|
643
|
+
getConversation: () => conversationRef.current,
|
|
644
|
+
getLastAssistantText: () => lastAssistantTextRef.current,
|
|
645
|
+
setLastAssistantText: text => { lastAssistantTextRef.current = text; },
|
|
646
|
+
setAbortController: controller => { abortControllerRef.current = controller; },
|
|
647
|
+
setWorkState: state => {
|
|
648
|
+
workStateRef.current = state;
|
|
649
|
+
sessionRecorder.recordWorkState(state);
|
|
650
|
+
},
|
|
651
|
+
compactConversation,
|
|
652
|
+
recordTokenUsage: usage => {
|
|
653
|
+
setTokenUsage(current => accumulateTokenUsage(current, usage));
|
|
654
|
+
},
|
|
655
|
+
onEvent: event => {
|
|
656
|
+
sessionRecorder.recordEvent(event);
|
|
657
|
+
},
|
|
658
|
+
onTasksChanged: () => { loadTasksFromStore().then(t => { setVisibleTasks(t); setTaskBarPadding(0); }).catch(() => undefined); },
|
|
659
|
+
contextFileSignatures: contextFileSignaturesRef.current,
|
|
660
|
+
log: llmLogRef.current,
|
|
1093
661
|
},
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
}, 0, false, false, { start: sessionStartRef.current, cwd: process.cwd() });
|
|
662
|
+
...(resumeExisting ? { resumeFrom: resumeExisting } : {}),
|
|
663
|
+
...(turnOptions.attachments || turnOptions.blessedPaths || turnOptions.ephemeralControl || turnOptions.subagentOverrides ? { turnOptions } : {})
|
|
664
|
+
});
|
|
1098
665
|
await sessionRecorder.flush().catch(showPersistenceWarning);
|
|
1099
666
|
await llmLogRef.current?.writer?.flush().catch(showPersistenceWarning);
|
|
667
|
+
// Only a genuinely paused goal (supervisor already attempted automatic
|
|
668
|
+
// continuation) exposes the one-key resume affordance; it stays until the
|
|
669
|
+
// user submits something else.
|
|
670
|
+
if (goalResult.resume?.kind === 'model-stream-idle')
|
|
671
|
+
setPausedResume({ kind: 'model-stream-idle', request: goalResult.resume.request, retryAttempt: goalResult.resume.retryAttempt });
|
|
672
|
+
else if (goalResult.resume?.kind === 'incomplete-goal')
|
|
673
|
+
setPausedResume({ kind: 'incomplete-goal', request: goalResult.resume.checkpoint.request, retryAttempt: 0, checkpoint: goalResult.resume.checkpoint });
|
|
674
|
+
else
|
|
675
|
+
setPausedResume(undefined);
|
|
676
|
+
return goalResult;
|
|
1100
677
|
}
|
|
1101
678
|
const visible = messages.filter(message => !message.hidden);
|
|
1102
679
|
const activeLiveMessages = liveMessages.filter(message => !message.hidden);
|
|
1103
|
-
const
|
|
1104
|
-
const transcriptItems = orderedVisibleMessages.filter(message => !message.streaming).map((message, index) => ({ key: messageKey(message, index), message }));
|
|
1105
|
-
const streamingItems = orderedVisibleMessages.filter(message => message.streaming);
|
|
680
|
+
const { staticItems: staticTranscriptItems, streamingItems } = partitionDisplayMessages([...visible, ...activeLiveMessages]);
|
|
1106
681
|
const activeSelection = activeModel(settings);
|
|
1107
682
|
const placeholder = placeholderForMode(mode, busy);
|
|
1108
683
|
const activeModelName = activeSelection ? `${activeSelection.provider.name}:${activeSelection.model}` : 'unconfigured';
|
|
1109
|
-
const headerSubtitle = [
|
|
1110
|
-
'A minimal LLM harness for growing your own workflows while you work.',
|
|
1111
|
-
'',
|
|
1112
|
-
'Start with simple chat, then teach haze your habits with skills:',
|
|
1113
|
-
'/skills — add, enable/disable, validate, or remove Markdown skills.',
|
|
1114
|
-
'',
|
|
1115
|
-
'The most adaptive workflow is the one you shape as you go.',
|
|
1116
|
-
'',
|
|
1117
|
-
'Guardrails are light: haze lets the LLM work from the terminal almost like you,',
|
|
1118
|
-
'while trying to stay scoped to this project.',
|
|
1119
|
-
].join('\n');
|
|
684
|
+
const headerSubtitle = (_jsxs(Text, { children: ['A minimal coding agent for your terminal.\n\nStart with chat. Turn repeated work into Markdown skills:\n', _jsx(Text, { color: theme.command, children: "/skills" }), ' — create, enable, disable, validate, or remove skills.\n\nType ', _jsx(Text, { color: theme.command, children: "@" }), ' to browse workspace files. To grant read-only access to a file or directory outside the workspace for this turn, mention a path containing ', _jsx(Text, { color: theme.command, children: "/" }), ' (for example, ', _jsx(Text, { color: theme.command, children: "@../shared/file.ts" }), ' or ', _jsx(Text, { color: theme.command, children: "/tmp/reference.md" }), ').\n\nImage mentions require a vision-capable model. File edits and writes stay inside the workspace.\n\nhaze runs tool calls without confirmation gates. Supervise consequential work as you would any shell session.\n\nShape haze around your workflow as you go.\n\nUse ', _jsx(Text, { color: theme.command, children: "/help" }), ' for commands.'] }));
|
|
1120
685
|
const workspaceLabel = `${compactHomePath(process.cwd())}${branchName ? ` (${branchName})` : ''}`;
|
|
1121
|
-
const
|
|
1122
|
-
const
|
|
1123
|
-
const
|
|
1124
|
-
const fallbackTokens = estimateConversationTokens(allDisplayMessages);
|
|
1125
|
-
const estimatedLogicalInput = tokenUsage.logicalInputEstimate || fallbackTokens.input || 0;
|
|
1126
|
-
const providerInput = tokenUsage.inputTokens;
|
|
1127
|
-
const effectiveInput = providerInput == null ? estimatedLogicalInput : Math.max(providerInput, estimatedLogicalInput);
|
|
1128
|
-
const effectiveOutput = tokenUsage.outputTokens ?? (fallbackTokens.output || 0);
|
|
1129
|
-
const inputEstimated = providerInput == null || effectiveInput !== providerInput;
|
|
1130
|
-
const outputEstimated = tokenUsage.outputTokens == null;
|
|
1131
|
-
const enabledSkills = skills.filter(skill => isSkillEnabled(settings, skill.name));
|
|
1132
|
-
const statusDetailLabel = `${hazeMessages} haze message${hazeMessages === 1 ? '' : 's'} / ${toolsUsed} tool call${toolsUsed === 1 ? '' : 's'} / LLM ${inputEstimated ? '~' : ''}↑${formatTokenCount(effectiveInput)} ${outputEstimated ? '~' : ''}↓${formatTokenCount(effectiveOutput)} / ${enabledSkills.length} skill${enabledSkills.length === 1 ? '' : 's'}`;
|
|
1133
|
-
const hasTokenBreakdown = tokenUsage.systemPrompt > 0 || tokenUsage.messages > 0 || tokenUsage.toolSchemas > 0 || effectiveInput > 0 || effectiveOutput > 0;
|
|
1134
|
-
const inputSuggestions = inputSuggestionsForState({ mode, settings, skills, selectedProviderName, modelProviderFilter, selectedSkillName, selectedLspName, selectedMcpName });
|
|
686
|
+
const enabledSkillCount = new Set(skills.filter(skill => isSkillEnabled(settings, skill.name, skill.source)).map(skill => skill.name)).size;
|
|
687
|
+
const metrics = statusBarMetrics({ messages: [...messages, ...liveMessages], tokenUsage, enabledSkillCount, backgroundProcessCount: backgroundCount });
|
|
688
|
+
const inputSuggestions = inputSuggestionsForState({ mode, settings, skills, sessions, selectedProviderName, modelProviderFilter, providerDraftName: providerDraft.name, discoveredModels, suggestedModels, selectedSkillName, selectedLspName, selectedMcpName });
|
|
1135
689
|
const staticItems = [
|
|
1136
|
-
{ kind: 'header', key:
|
|
1137
|
-
...
|
|
690
|
+
{ kind: 'header', key: 'header', subtitle: headerSubtitle },
|
|
691
|
+
...staticTranscriptItems,
|
|
1138
692
|
];
|
|
1139
693
|
const busyElapsed = busyElapsedLabel(turnStartedAtRef.current);
|
|
1140
|
-
|
|
694
|
+
const contentWidth = Math.max(1, width - 2);
|
|
695
|
+
// Live-region budget: once the dynamic frame exceeds the viewport, Ink falls
|
|
696
|
+
// back to clearTerminal + full transcript replay, which wipes scrollback and
|
|
697
|
+
// jumps to the top on every render. Every dynamic section is therefore
|
|
698
|
+
// clamped so the frame stays under one screen (see chat/liveRegion.ts).
|
|
699
|
+
const busyRows = busy ? (showingTip ? 2 : 1) : 0;
|
|
700
|
+
const queuedRows = queuedFollowUps.length > 0 ? 2 + queuedFollowUps.length : 0;
|
|
701
|
+
const collapsedTaskRows = Math.min(visibleTasks.length, MAX_VISIBLE_TASKS);
|
|
702
|
+
const expandedTaskCap = Math.max(MAX_VISIBLE_TASKS, terminalRows - 18);
|
|
703
|
+
const expandedTaskRows = Math.min(visibleTasks.length, expandedTaskCap) + (visibleTasks.length > expandedTaskCap ? 1 : 0);
|
|
704
|
+
const taskRows = visibleTasks.length > 0 ? 2 + taskBarPadding + (tasksExpanded ? expandedTaskRows : collapsedTaskRows) : 0;
|
|
705
|
+
// Debug-only panels are counted conservatively so debug mode cannot overflow either.
|
|
706
|
+
const debugPanelRows = debug && debugLogs.length > 0 ? 4 + debugLogs.length : 0;
|
|
707
|
+
const tokenPanelRows = debug && metrics.hasTokenBreakdown ? 5 : 0;
|
|
708
|
+
// The input box is border (2) + one row; a user-pasted multiline draft can
|
|
709
|
+
// exceed this estimate (accepted: it is transient, user-driven editing state).
|
|
710
|
+
const fixedLiveRows = busyRows + queuedRows + taskRows + debugPanelRows + tokenPanelRows + 3 /* input */ + 2 /* status */ + 2 /* safety */;
|
|
711
|
+
const streamingRowsBudget = Math.max(1, terminalRows - fixedLiveRows);
|
|
712
|
+
const perStreamingItemRows = streamingItems.length > 0 ? Math.max(2, Math.floor(streamingRowsBudget / streamingItems.length)) : 0;
|
|
713
|
+
return _jsxs(Box, { flexDirection: "column", paddingX: 1, children: [_jsx(Static, { items: staticItems, children: item => item.kind === 'header'
|
|
1141
714
|
? _jsx(Header, { subtitle: item.subtitle, version: version }, item.key)
|
|
1142
|
-
:
|
|
715
|
+
: item.kind === 'assistant-markdown'
|
|
716
|
+
? _jsx(AssistantMarkdownChunkView, { message: item.message, content: item.content, width: contentWidth, first: item.first, final: item.final }, item.key)
|
|
717
|
+
: _jsx(MessageView, { message: item.message, width: contentWidth }, item.key) }), streamingItems.length > 0 && _jsx(Box, { flexDirection: "column", flexShrink: 0, children: streamingItems.map(item => {
|
|
718
|
+
// One row for the optional header plus one for the item's bottom margin.
|
|
719
|
+
const chrome = (item.showHeader === false ? 0 : 1) + 1;
|
|
720
|
+
return _jsx(MessageView, { message: item.message, width: contentWidth, showHeader: item.showHeader, maxVisibleLines: Math.max(1, perStreamingItemRows - chrome) }, item.key);
|
|
721
|
+
}) }), debug && debugLogs.length > 0 && _jsxs(Box, { flexDirection: "column", flexShrink: 0, marginBottom: 1, borderStyle: "round", borderColor: theme.muted, paddingX: 1, children: [_jsx(Text, { color: theme.muted, bold: true, children: "Debug" }), debugLogs.map((line, index) => _jsxs(Text, { color: theme.muted, children: ["\u2022 ", line] }, index))] }), queuedFollowUps.length > 0 && _jsxs(Box, { flexDirection: "column", flexShrink: 0, marginBottom: 1, children: [_jsx(Text, { color: theme.muted, children: "Queued follow-ups:" }), queuedFollowUps.map((item, index) => _jsxs(Text, { color: theme.muted, children: [" ", index + 1, ". ", item] }, `${index}-${item}`))] }), pausedResume && !busy && _jsxs(Box, { flexShrink: 0, marginBottom: 1, children: [_jsxs(Text, { color: theme.muted, children: [pausedResume.kind === 'incomplete-goal' ? 'Unfinished goal paused (no measurable progress)' : 'Unfinished goal paused (model stream stalled)', " \u00B7 "] }), _jsxs(Text, { color: theme.command, bold: true, children: ["Press R to ", pausedResume.kind === 'incomplete-goal' ? 'resume' : 'retry'] }), _jsx(Text, { color: theme.muted, children: " or type a follow-up" })] }), visibleTasks.length > 0 && _jsx(Box, { flexDirection: "column", flexShrink: 0, marginBottom: 1, children: _jsx(TaskBar, { tasks: visibleTasks, width: contentWidth, expanded: tasksExpanded, padding: taskBarPadding, maxRows: expandedTaskCap }) }), busy && _jsx(BusyBar, { label: busyLabel, elapsed: busyElapsed, tip: showingTip ? TIPS[tipIndex] : undefined }), _jsx(Box, { borderStyle: "round", borderColor: theme.deepPurple, paddingX: 1, flexShrink: 0, children: _jsx(Box, { flexGrow: 1, minWidth: 0, children: _jsx(TextInput, { placeholder: placeholder, disabled: busy && mode !== 'chat', mask: MASKED_MODES.has(mode), historyItems: inputHistory, recordHistory: mode === 'chat', suggestions: inputSuggestions, suggestionMode: PICKER_MODES.has(mode) ? 'always' : 'slash', submitOnEmpty: SUBMIT_EMPTY_MODES.has(mode), width: Math.max(20, contentWidth - 4), getMentionSuggestions: fileMentionSuggestions, onHistoryAdd: persistInputHistory, onToggleTasks: () => {
|
|
1143
722
|
if (!tasksExpanded) {
|
|
1144
723
|
setTaskBarPadding(0);
|
|
1145
724
|
setTasksExpanded(true);
|
|
@@ -1150,19 +729,23 @@ function ChatScreen({ debug = false, version, continueSession = false, noSession
|
|
|
1150
729
|
setTaskBarPadding(Math.max(0, expandedRows - collapsedRows));
|
|
1151
730
|
setTasksExpanded(false);
|
|
1152
731
|
}
|
|
1153
|
-
}, onCancel: cancelThinking, onEscape: () => {
|
|
732
|
+
}, onCancel: cancelThinking, onResumeKey: pausedResume != null && !busy ? resumePausedTask : undefined, onEscape: () => {
|
|
1154
733
|
if (busy)
|
|
1155
734
|
cancelThinking();
|
|
1156
735
|
else
|
|
1157
736
|
closeInputList();
|
|
1158
|
-
}, onSubmit: submit }) }) }), debug && hasTokenBreakdown && _jsxs(Box, { flexShrink: 0, flexDirection: "column", paddingX: 1, children: [_jsxs(Text, { color: theme.muted, bold: true, children: ["Token usage ", inputEstimated || outputEstimated ? '(estimated)' : '(precise)'] }), _jsxs(Text, { color: theme.muted, children: [" in=", formatTokenCount(effectiveInput), " out=", formatTokenCount(effectiveOutput), tokenUsage.cacheReadTokens > 0 ? ` cached=${formatTokenCount(tokenUsage.cacheReadTokens)}` : '', tokenUsage.noCacheTokens > 0 ? ` uncached=${formatTokenCount(tokenUsage.noCacheTokens)}` : '', tokenUsage.cacheWriteTokens > 0 ? ` cache_write=${formatTokenCount(tokenUsage.cacheWriteTokens)}` : '', tokenUsage.reasoningTokens > 0 ? ` reasoning=${formatTokenCount(tokenUsage.reasoningTokens)}` : ''] }), _jsxs(Text, { color: theme.muted, children: [" logical=", formatTokenCount(tokenUsage.logicalInputEstimate), tokenUsage.effectiveNonCachedInput != null ? ` effective_non_cached=${formatTokenCount(tokenUsage.effectiveNonCachedInput)}` : ''] }), _jsxs(Text, { color: theme.muted, children: [" system=", formatTokenCount(tokenUsage.systemPrompt), " messages=", formatTokenCount(tokenUsage.messages), " tools=", formatTokenCount(tokenUsage.toolSchemas), " output=", formatTokenCount(tokenUsage.outputEstimate)] })] }), _jsxs(Box, { flexShrink: 0, justifyContent: "space-between", children: [_jsxs(Box, { flexDirection: "column", flexShrink: 1, minWidth: 0, children: [_jsx(Text, { color: theme.muted,
|
|
737
|
+
}, onSubmit: submit }) }) }), debug && metrics.hasTokenBreakdown && _jsxs(Box, { flexShrink: 0, flexDirection: "column", paddingX: 1, children: [_jsxs(Text, { color: theme.muted, bold: true, children: ["Token usage ", metrics.inputEstimated || metrics.outputEstimated ? '(estimated)' : '(precise)'] }), _jsxs(Text, { color: theme.muted, children: [" in=", formatTokenCount(metrics.effectiveInput), " out=", formatTokenCount(metrics.effectiveOutput), tokenUsage.cacheReadTokens > 0 ? ` cached=${formatTokenCount(tokenUsage.cacheReadTokens)}` : '', tokenUsage.noCacheTokens > 0 ? ` uncached=${formatTokenCount(tokenUsage.noCacheTokens)}` : '', tokenUsage.cacheWriteTokens > 0 ? ` cache_write=${formatTokenCount(tokenUsage.cacheWriteTokens)}` : '', tokenUsage.reasoningTokens > 0 ? ` reasoning=${formatTokenCount(tokenUsage.reasoningTokens)}` : ''] }), _jsxs(Text, { color: theme.muted, children: [" logical=", formatTokenCount(tokenUsage.logicalInputEstimate), tokenUsage.effectiveNonCachedInput != null ? ` effective_non_cached=${formatTokenCount(tokenUsage.effectiveNonCachedInput)}` : ''] }), _jsxs(Text, { color: theme.muted, children: [" system=", formatTokenCount(tokenUsage.systemPrompt), " messages=", formatTokenCount(tokenUsage.messages), " tools=", formatTokenCount(tokenUsage.toolSchemas), " output=", formatTokenCount(tokenUsage.outputEstimate)] })] }), _jsxs(Box, { flexShrink: 0, justifyContent: "space-between", children: [_jsxs(Box, { flexDirection: "column", flexShrink: 1, minWidth: 0, children: [_jsx(Text, { color: theme.muted, wrap: "truncate-end", children: workspaceLabel }), _jsx(Text, { color: theme.muted, wrap: "truncate-end", children: metrics.statusDetailLabel })] }), _jsx(Box, { flexShrink: 0, marginLeft: 2, children: _jsx(Text, { color: theme.muted, wrap: "truncate-start", children: activeModelName }) })] })] });
|
|
1159
738
|
}
|
|
1160
739
|
export async function chatCommand(options = {}) {
|
|
1161
740
|
if (process.stdout.isTTY) {
|
|
1162
741
|
process.stdout.write('\u001B[2J\u001B[3J\u001B[H');
|
|
1163
742
|
}
|
|
1164
743
|
await clearTasksFromStore().catch(() => undefined);
|
|
1165
|
-
|
|
744
|
+
// Incremental rendering rewrites only changed lines of the live frame, removing
|
|
745
|
+
// the full-frame erase/rewrite flicker while streaming. The fps cap aligns with
|
|
746
|
+
// the ~80ms spinner cadence; faster renders would only repaint unchanged lines.
|
|
747
|
+
const app = render(_jsx(ChatScreen, { debug: options.debug, version: options.version, build: options.build, continueSession: options.continueSession, resumeSessionId: options.resumeSessionId, noSession: options.noSession }), { incrementalRendering: true, maxFps: 15 });
|
|
1166
748
|
await app.waitUntilExit();
|
|
749
|
+
await teardownBackgroundProcesses().catch(() => undefined);
|
|
1167
750
|
await clearTasksFromStore().catch(() => undefined);
|
|
1168
751
|
}
|