zapagent 1.14.17 → 1.14.18
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/package.json +1 -1
- package/src/App.tsx +29 -21
- package/src/agent/wireRunHandlers.ts +0 -6
- package/src/commands/dispatcher.ts +1 -11
- package/src/goal-command.ts +2 -2
- package/src/goal-session.ts +14 -6
- package/src/goal-view-poller.ts +44 -0
- package/src/goal-view.ts +67 -0
- package/src/hooks/useAgentRunner.ts +18 -9
- package/src/hooks/useGoalView.ts +49 -0
- package/src/hooks/useSpinner.ts +4 -1
- package/src/hooks/useUpdateCheck.ts +13 -7
- package/src/ui/UpdateNotice.tsx +5 -5
- package/src/ui/dialog-update.tsx +19 -6
- package/src/ui/goal-status.tsx +36 -0
- package/src/ui/live-activity.tsx +52 -14
- package/src/ui/theme.ts +2 -0
- package/src/ui/todos-panel.tsx +10 -2
- package/src/update-check.ts +27 -1
package/package.json
CHANGED
package/src/App.tsx
CHANGED
|
@@ -452,7 +452,7 @@ export function App() {
|
|
|
452
452
|
|
|
453
453
|
// ── Toasts ──
|
|
454
454
|
const { toasts, addToast } = useToasts()
|
|
455
|
-
const
|
|
455
|
+
const updateCheck = useUpdateCheck()
|
|
456
456
|
|
|
457
457
|
// ── Pending images attached to next user turn ──
|
|
458
458
|
const [pendingImages, setPendingImages] = useState<import("./queue/inputQueue.js").PendingImage[]>([])
|
|
@@ -536,6 +536,9 @@ export function App() {
|
|
|
536
536
|
runAgent,
|
|
537
537
|
runGoalCommand,
|
|
538
538
|
goalRunning,
|
|
539
|
+
goalStatus,
|
|
540
|
+
goalTodoId,
|
|
541
|
+
resetGoalView,
|
|
539
542
|
abortRef,
|
|
540
543
|
status: runnerStatus,
|
|
541
544
|
providerRequest,
|
|
@@ -774,6 +777,7 @@ export function App() {
|
|
|
774
777
|
dispatchUserTurn(text, systemPrompt, images, displayText, silent, restoreText, memoryQueryText, meta?.onAccepted),
|
|
775
778
|
getContextTokens: () => contextTokensRef.current,
|
|
776
779
|
onResetRuntimeState: () => {
|
|
780
|
+
resetGoalView()
|
|
777
781
|
tokenAccounting.promptOverhead = 0
|
|
778
782
|
setContextTokens(0, "estimated", null)
|
|
779
783
|
resetRunDiagnostics()
|
|
@@ -805,7 +809,7 @@ export function App() {
|
|
|
805
809
|
// stable; refs aren't deps. Only addLog/addToast/compactLogs/dispatchUserTurn
|
|
806
810
|
// could realistically change.
|
|
807
811
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
808
|
-
[addLog, addToast, compactLogs, dispatchUserTurn, runGoalCommand, exit, updateConfig, setContextTokens, resetRunDiagnostics, restoreMemoryQueryHistoryFromLogs, setCompactFailure, setMemoryFailure, bindQueue],
|
|
812
|
+
[addLog, addToast, compactLogs, dispatchUserTurn, runGoalCommand, exit, updateConfig, setContextTokens, resetRunDiagnostics, resetGoalView, restoreMemoryQueryHistoryFromLogs, setCompactFailure, setMemoryFailure, bindQueue],
|
|
809
813
|
)
|
|
810
814
|
|
|
811
815
|
// ── Turn dispatcher (unified handleSubmit + drain) ──
|
|
@@ -1085,25 +1089,10 @@ export function App() {
|
|
|
1085
1089
|
|
|
1086
1090
|
{!inModal && (
|
|
1087
1091
|
<>
|
|
1088
|
-
{dialog !== "queue" && <TodosPanel todos={todos} />}
|
|
1089
|
-
|
|
1090
|
-
<LiveActivity
|
|
1091
|
-
isRunning={isRunning}
|
|
1092
|
-
isStreaming={isStreaming}
|
|
1093
|
-
isThinking={isThinking}
|
|
1094
|
-
thinkingChars={thinkingText.length}
|
|
1095
|
-
status={turnActivity.status}
|
|
1096
|
-
providerRequest={providerRequest}
|
|
1097
|
-
activeTool={activeTool}
|
|
1098
|
-
activeToolBytes={activeToolBytes}
|
|
1099
|
-
termWidth={termWidth}
|
|
1100
|
-
pendingTools={pendingTools}
|
|
1101
|
-
lastCompletedTool={lastCompletedTool}
|
|
1102
|
-
stopHint={inputQueue.length || editingMessageId || pendingImages.length || dialog || palettes.slashOpen || palettes.fileOpen ? "Ctrl+C to stop" : undefined}
|
|
1103
|
-
/>
|
|
1092
|
+
{dialog !== "queue" && <TodosPanel todos={todos} goalId={goalStatus?.id} goalAttached={goalRunning} todoGoalId={goalTodoId} />}
|
|
1104
1093
|
|
|
1105
1094
|
<ToastContainer toasts={toasts} />
|
|
1106
|
-
<UpdateNotice
|
|
1095
|
+
<UpdateNotice state={updateCheck} />
|
|
1107
1096
|
|
|
1108
1097
|
<TokenWarning contextBudget={contextBudget} />
|
|
1109
1098
|
|
|
@@ -1112,6 +1101,25 @@ export function App() {
|
|
|
1112
1101
|
</>
|
|
1113
1102
|
)}
|
|
1114
1103
|
|
|
1104
|
+
{!inModal && <LiveActivity
|
|
1105
|
+
isRunning={isRunning}
|
|
1106
|
+
isStreaming={isStreaming}
|
|
1107
|
+
isThinking={isThinking}
|
|
1108
|
+
thinkingChars={thinkingText.length}
|
|
1109
|
+
status={turnActivity.status}
|
|
1110
|
+
providerRequest={providerRequest}
|
|
1111
|
+
activeTool={activeTool}
|
|
1112
|
+
activeToolBytes={activeToolBytes}
|
|
1113
|
+
termWidth={termWidth}
|
|
1114
|
+
pendingTools={pendingTools}
|
|
1115
|
+
lastCompletedTool={lastCompletedTool}
|
|
1116
|
+
goal={goalStatus}
|
|
1117
|
+
goalAttached={goalRunning}
|
|
1118
|
+
goalTodos={goalStatus?.id === goalTodoId ? todos : []}
|
|
1119
|
+
goalAwaitingInput={!!pendingApproval || !!pendingPlan || !!pendingQuestions}
|
|
1120
|
+
stopHint={inputQueue.length || editingMessageId || pendingImages.length || dialog || palettes.slashOpen || palettes.fileOpen ? "Ctrl+C to stop" : undefined}
|
|
1121
|
+
/>}
|
|
1122
|
+
|
|
1115
1123
|
{!inModal && pendingApproval && (
|
|
1116
1124
|
<ApprovalBar
|
|
1117
1125
|
key={pendingApproval.id}
|
|
@@ -1159,7 +1167,7 @@ export function App() {
|
|
|
1159
1167
|
// LiveActivity above provides its own marginTop=1; doubling it
|
|
1160
1168
|
// on the prompt creates the "live indicator floats too far from
|
|
1161
1169
|
// the prompt" gap.
|
|
1162
|
-
noTopMargin={isRunning || isStreaming || isThinking || pendingTools.length > 0}
|
|
1170
|
+
noTopMargin={!!goalStatus || isRunning || isStreaming || isThinking || pendingTools.length > 0}
|
|
1163
1171
|
/>
|
|
1164
1172
|
)}
|
|
1165
1173
|
|
|
@@ -1178,7 +1186,7 @@ export function App() {
|
|
|
1178
1186
|
* defocused while the dialog owns the keyboard (see focused= prop
|
|
1179
1187
|
* above). */}
|
|
1180
1188
|
{dialog === "restoring" && <Text>Restoring saved session…</Text>}
|
|
1181
|
-
{dialog === "update" && <UpdateDialog
|
|
1189
|
+
{dialog === "update" && <UpdateDialog busy={isRunning} sessionId={getCurrentSessionId()} beforeInstall={() => {
|
|
1182
1190
|
readCurrentSessionLogs()
|
|
1183
1191
|
const persistence = getSessionPersistenceStatus()
|
|
1184
1192
|
if (persistence.pendingWrites || persistence.lastFailure) throw new Error("Save the current session successfully before updating.")
|
|
@@ -575,13 +575,7 @@ export function createRunHandlers(deps: RunHandlersDeps): RunHandlers {
|
|
|
575
575
|
const d = e.detail as
|
|
576
576
|
| { messageCount?: number; tokenEstimate?: number; trigger?: string }
|
|
577
577
|
| undefined
|
|
578
|
-
const msgs = d?.messageCount ?? 0
|
|
579
578
|
const tok = d?.tokenEstimate ?? 0
|
|
580
|
-
const reason = d?.trigger === "force" ? "overflow recovery" : d?.trigger === "tokens" ? "token threshold" : "char threshold"
|
|
581
|
-
deps.addLog(
|
|
582
|
-
"system",
|
|
583
|
-
`🗜 Compacting context — ${msgs} messages / ~${Math.round(tok / 1000)}k tokens (${reason})`,
|
|
584
|
-
)
|
|
585
579
|
// The shared planner already counted schemas and transient context.
|
|
586
580
|
// Do not add the previous provider-calibrated overhead a second time.
|
|
587
581
|
if (tok > 0) {
|
|
@@ -499,17 +499,7 @@ export function dispatchSlashCommand(
|
|
|
499
499
|
// conversation.compress).
|
|
500
500
|
return (async () => {
|
|
501
501
|
const controller = deps.beginManualCompact?.() ?? new AbortController()
|
|
502
|
-
//
|
|
503
|
-
// signals "this is going to take a few seconds" up front. compactLogs
|
|
504
|
-
// below will replace the log array post-success anyway; the row's
|
|
505
|
-
// job is to bridge the 3-10s wait.
|
|
506
|
-
const ctxTokens = conversation.estimatedTokens
|
|
507
|
-
deps.addLog("system", `🗜 Compacting context — ~${Math.round(ctxTokens / 1000)}k tokens (manual)`)
|
|
508
|
-
// Flip the App-level status so LiveActivity renders its spinner +
|
|
509
|
-
// "Compacting" label during the 3-10s LLM summary call. Without
|
|
510
|
-
// this, the manual path had a start log but no live indicator,
|
|
511
|
-
// making the UI look frozen. Reset to "ready" in finally so we
|
|
512
|
-
// never leave the bar spinning if compress throws.
|
|
502
|
+
// Show transient inline maintenance without adding a scrollback row.
|
|
513
503
|
deps.setStatus("compacting")
|
|
514
504
|
try {
|
|
515
505
|
// Capture pre-compact messages BEFORE compress so the post-compact
|
package/src/goal-command.ts
CHANGED
|
@@ -67,7 +67,7 @@ export function startGoalBackgroundRunner(goal: GoalRecord): void {
|
|
|
67
67
|
}
|
|
68
68
|
|
|
69
69
|
/** The same command implementation is used by the TUI and the CLI. */
|
|
70
|
-
export function goalCommand(args: string[], cwd: string, currentMode: import("./config.js").PermissionMode = "default", platform: NodeJS.Platform = process.platform, sessionId?: string, onForeground?: (goal: GoalRecord) => void, enforceSessionMode = false): string {
|
|
70
|
+
export function goalCommand(args: string[], cwd: string, currentMode: import("./config.js").PermissionMode = "default", platform: NodeJS.Platform = process.platform, sessionId?: string, onForeground?: (goal: GoalRecord) => void, enforceSessionMode = false, onSelected?: (goal: GoalRecord) => void): string {
|
|
71
71
|
const action = args[0] ?? ""
|
|
72
72
|
if (!action || action === "help") return [
|
|
73
73
|
"Usage: /goal <objective> [--background] [--artifact] [--strict] [--accept-edits | --permission-mode=MODE] [--check=bun|npm|pytest|go] [--install=npm] [--tokens=N] [--minutes=N] [--model-calls=N] [--tool-calls=N] | status [id] | list | pause [id] | resume [id] | cancel [id] | budget extend [id] --tokens=N --minutes=N",
|
|
@@ -109,7 +109,7 @@ export function goalCommand(args: string[], cwd: string, currentMode: import("./
|
|
|
109
109
|
const requested = args.includes("--accept-edits") ? "acceptEdits" : modeArgs[0]?.slice("--permission-mode=".length) ?? currentMode
|
|
110
110
|
if (requested !== currentMode) throw new Error("Goal uses the current session permission mode; change the session mode before starting a Goal")
|
|
111
111
|
}
|
|
112
|
-
const launch = (goal: GoalRecord) => background ? startGoalBackgroundRunner(goal) : onForeground!(goal)
|
|
112
|
+
const launch = (goal: GoalRecord) => { onSelected?.(goal); return background ? startGoalBackgroundRunner(goal) : onForeground!(goal) }
|
|
113
113
|
const store = new GoalStore(goalDatabasePath(), { requireLedger: true })
|
|
114
114
|
try {
|
|
115
115
|
if (action === "list") {
|
package/src/goal-session.ts
CHANGED
|
@@ -11,6 +11,9 @@ export interface GoalSessionOptions {
|
|
|
11
11
|
sessionId?: string
|
|
12
12
|
signal?: AbortSignal
|
|
13
13
|
onStart?: (goal: GoalRecord) => void
|
|
14
|
+
onSelected?: (goal: GoalRecord) => void
|
|
15
|
+
/** The TUI keeps Goal state above input instead of appending protocol notices. */
|
|
16
|
+
compact?: boolean
|
|
14
17
|
onMessage: (text: string) => void
|
|
15
18
|
onResult?: (markdown: string) => void
|
|
16
19
|
onState?: (goal: GoalRecord) => void
|
|
@@ -30,16 +33,19 @@ export async function executeGoalCommand(args: string[], cwd: string, options: G
|
|
|
30
33
|
const detach = attached.get(key)
|
|
31
34
|
if (!detach || args.length > 2 || args[1] && args[1] !== detach.id) throw new Error("No foreground Goal in this session")
|
|
32
35
|
detach.background()
|
|
33
|
-
options.onMessage("Goal will switch to background at the next safe phase boundary.")
|
|
36
|
+
options.onMessage(options.compact ? "将在当前步骤安全结束后转为后台。" : "Goal will switch to background at the next safe phase boundary.")
|
|
34
37
|
return 0
|
|
35
38
|
}
|
|
36
39
|
if (attached.has(key) && (!args[0] || !["status", "watch", "list", "pause", "cancel", "budget", "help"].includes(args[0]))) throw new Error("A foreground Goal is already running in this session")
|
|
37
40
|
let foreground: GoalRecord | undefined
|
|
41
|
+
let selected: GoalRecord | undefined
|
|
38
42
|
const message = goalCommand(args, cwd, options.permissionMode, process.platform, options.sessionId, goal => {
|
|
39
43
|
if (attached.has(key)) throw new Error("A foreground Goal is already running in this session")
|
|
40
44
|
foreground = goal
|
|
41
|
-
}, !!options.runTurn)
|
|
42
|
-
options.onMessage(message)
|
|
45
|
+
}, !!options.runTurn, goal => { selected = goal; options.onSelected?.(goal) })
|
|
46
|
+
if (!options.compact) options.onMessage(message)
|
|
47
|
+
else if (!selected) options.onMessage(args[0] === "pause" ? "已请求暂停目标。" : args[0] === "cancel" ? "已请求取消目标。" : message)
|
|
48
|
+
else if (!foreground) options.onMessage("目标已在后台启动。")
|
|
43
49
|
if (!foreground) return 0
|
|
44
50
|
const goal = foreground as GoalRecord
|
|
45
51
|
let backgroundRequested = false
|
|
@@ -66,12 +72,14 @@ export async function executeGoalCommand(args: string[], cwd: string, options: G
|
|
|
66
72
|
onOutcome: value => { outcome = value },
|
|
67
73
|
})
|
|
68
74
|
if (backgroundRequested && outcome?.status === "paused" && outcome.stopReason === "USER_INPUT_PENDING") {
|
|
69
|
-
|
|
70
|
-
options.onMessage(
|
|
75
|
+
const resumed = goalCommand(["resume", goal.id, "--background"], cwd, options.permissionMode, process.platform, options.sessionId)
|
|
76
|
+
if (!options.compact) options.onMessage(resumed)
|
|
77
|
+
options.onMessage(options.compact ? "目标已转为后台运行。" : `Goal ${goal.id} is now running in background.`)
|
|
71
78
|
return 0
|
|
72
79
|
}
|
|
73
80
|
if (outcome) {
|
|
74
|
-
options.onMessage(`Goal ${outcome.id} · ${outcome.status}${outcome.stopReason ? ` · ${outcome.stopReason}` : ""}`)
|
|
81
|
+
if (!options.compact) options.onMessage(`Goal ${outcome.id} · ${outcome.status}${outcome.stopReason ? ` · ${outcome.stopReason}` : ""}`)
|
|
82
|
+
else if (outcome.status === "blocked" || outcome.status === "failed") options.onMessage(`目标暂时无法继续:${outcome.stopReason ?? "执行未完成"}`)
|
|
75
83
|
const acceptance = goalAcceptanceSummary(outcome)
|
|
76
84
|
if (acceptance) options.onMessage(acceptance)
|
|
77
85
|
const markdown = ["completed", "ready_for_delivery"].includes(outcome.status) ? goalDeliveryMarkdown(outcome.delivery) : undefined
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { isFinishedGoal, type GoalView } from "./goal-view.js"
|
|
2
|
+
|
|
3
|
+
interface GoalViewPollingOptions {
|
|
4
|
+
read: () => GoalView | undefined
|
|
5
|
+
publish: (view: GoalView | undefined) => void
|
|
6
|
+
onReadError?: (error: unknown) => void
|
|
7
|
+
schedule?: (callback: () => void, delay: number) => () => void
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/** Detached work stays responsive; waiting states and failed reads back off.
|
|
11
|
+
* Scheduling one read at a time also prevents a slow ledger from queuing work. */
|
|
12
|
+
export function startGoalViewPolling({ read, publish, onReadError, schedule = (callback, delay) => {
|
|
13
|
+
const timer = setTimeout(callback, delay)
|
|
14
|
+
return () => clearTimeout(timer)
|
|
15
|
+
} }: GoalViewPollingOptions): () => void {
|
|
16
|
+
let stopped = false
|
|
17
|
+
let cancelNext: (() => void) | undefined
|
|
18
|
+
let lastView = ""
|
|
19
|
+
let unchanged = 0
|
|
20
|
+
let failures = 0
|
|
21
|
+
const poll = () => {
|
|
22
|
+
if (stopped) return
|
|
23
|
+
let delay: number
|
|
24
|
+
try {
|
|
25
|
+
const view = read()
|
|
26
|
+
if (stopped) return
|
|
27
|
+
publish(view)
|
|
28
|
+
failures = 0
|
|
29
|
+
if (!view || isFinishedGoal(view.status)) return
|
|
30
|
+
const key = JSON.stringify(view)
|
|
31
|
+
unchanged = key === lastView ? Math.min(unchanged + 1, 3) : 0
|
|
32
|
+
lastView = key
|
|
33
|
+
delay = view.status === "running" || view.status === "created" ? 1000 : Math.min(30_000, 5000 * 2 ** unchanged)
|
|
34
|
+
} catch (error) {
|
|
35
|
+
if (stopped) return
|
|
36
|
+
if (failures === 0) { try { onReadError?.(error) } catch { /* Diagnostics cannot break input. */ } }
|
|
37
|
+
failures = Math.min(failures + 1, 6)
|
|
38
|
+
delay = Math.min(60_000, 1000 * 2 ** failures)
|
|
39
|
+
}
|
|
40
|
+
if (!stopped) cancelNext = schedule(poll, delay)
|
|
41
|
+
}
|
|
42
|
+
poll()
|
|
43
|
+
return () => { stopped = true; cancelNext?.() }
|
|
44
|
+
}
|
package/src/goal-view.ts
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { Database } from "bun:sqlite"
|
|
2
|
+
import { existsSync } from "node:fs"
|
|
3
|
+
import { stripVTControlCharacters } from "node:util"
|
|
4
|
+
import type { GoalRecord, GoalStatus } from "../zapsdk/goal/contracts.js"
|
|
5
|
+
import type { Todo } from "../zapsdk/index.js"
|
|
6
|
+
import { goalDatabasePath } from "./goal-command.js"
|
|
7
|
+
|
|
8
|
+
export interface GoalView {
|
|
9
|
+
id: string
|
|
10
|
+
objective: string
|
|
11
|
+
status: GoalStatus
|
|
12
|
+
phase?: GoalRecord["phase"]
|
|
13
|
+
stopReason?: string
|
|
14
|
+
accepted: boolean
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function goalView(goal: GoalRecord): GoalView {
|
|
18
|
+
return { id: goal.id, objective: goal.objective, status: goal.status, phase: goal.phase,
|
|
19
|
+
stopReason: goal.stopReason, accepted: goal.finalReceipt?.status === "passed" }
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export const isFinishedGoal = (status: GoalStatus) => ["completed", "cancelled", "failed"].includes(status)
|
|
23
|
+
|
|
24
|
+
/** Display polling never creates/migrates the ledger or changes Goal ownership. */
|
|
25
|
+
export function readSessionGoalView(cwd: string, sessionId: string, selectedId?: string, path = goalDatabasePath()): GoalView | undefined {
|
|
26
|
+
if (!existsSync(path)) return undefined
|
|
27
|
+
const db = new Database(path, { readonly: true, strict: true })
|
|
28
|
+
try {
|
|
29
|
+
db.exec("PRAGMA busy_timeout=50")
|
|
30
|
+
const row = selectedId
|
|
31
|
+
? db.query<{ revision: number; record: string }, [string]>("SELECT revision,record FROM goals WHERE id=?").get(selectedId)
|
|
32
|
+
: db.query<{ revision: number; record: string }, [string, string]>("SELECT revision,record FROM goals WHERE json_extract(record,'$.cwd')=? AND json_extract(record,'$.sessionId')=? ORDER BY rowid DESC LIMIT 1").get(cwd, sessionId)
|
|
33
|
+
if (!row) return undefined
|
|
34
|
+
const value = JSON.parse(row.record) as GoalRecord
|
|
35
|
+
if (value.stateRevision !== row.revision || typeof value.objective !== "string") throw new Error("CORRUPT_GOAL_STATE")
|
|
36
|
+
if (value.cwd !== cwd || !selectedId && value.sessionId !== sessionId) return undefined
|
|
37
|
+
return goalView(value)
|
|
38
|
+
} finally { db.close() }
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function goalObjectiveText(objective: string): string {
|
|
42
|
+
return stripVTControlCharacters(objective).replace(/[\x00-\x1f\x7f]/g, " ").replace(/\s+/g, " ").trim()
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function goalActionText(goal: GoalView, attached: boolean, todos: readonly Todo[] = [], activeTool = ""): string {
|
|
46
|
+
if (goal.status === "completed") return goal.accepted ? "目标已完成,验收通过" : "目标已完成"
|
|
47
|
+
if (goal.status === "cancelled") return "目标已取消"
|
|
48
|
+
if (goal.status === "failed") return "目标执行失败,用 /goal status 查看原因"
|
|
49
|
+
if (goal.status === "paused") return goal.stopReason === "DEADLINE_EXCEEDED" ? "已达到你设置的时间限制" : "已暂停,进度已保留"
|
|
50
|
+
if (goal.status === "blocked") return "目标暂时无法继续,用 /goal status 查看原因"
|
|
51
|
+
if (goal.status === "awaiting_acceptance") return "等待补充信息或确认"
|
|
52
|
+
if (goal.status === "budget_limited") return "已达到你设置的用量限制"
|
|
53
|
+
if (goal.status === "ready_for_delivery") return goal.accepted ? "验收通过,等待交付授权" : "等待交付授权"
|
|
54
|
+
let text: string
|
|
55
|
+
if (goal.phase === "verifying" || goal.phase === "final_verifying") text = "正在独立验收结果"
|
|
56
|
+
else if (goal.phase === "integrating" || goal.phase === "delivering") text = "正在整理并交付结果"
|
|
57
|
+
else if (goal.phase === "sealing") text = "正在停止当前工作"
|
|
58
|
+
else if (goal.status === "created" || goal.phase === "planning") text = "正在准备执行目标"
|
|
59
|
+
else if (!attached) text = goal.phase === "repairing" ? "正在修正验收发现的问题" : "正在推进目标"
|
|
60
|
+
else {
|
|
61
|
+
const current = todos.find(todo => todo.status === "in_progress")
|
|
62
|
+
text = current ? goalObjectiveText(current.activeForm || current.content)
|
|
63
|
+
: goal.phase === "repairing" ? "正在修正验收发现的问题"
|
|
64
|
+
: activeTool && activeTool !== "todo_write" ? `正在使用 ${activeTool}` : "正在推进目标"
|
|
65
|
+
}
|
|
66
|
+
return attached ? text : `后台目标 · ${text}`
|
|
67
|
+
}
|
|
@@ -3,6 +3,7 @@ import { RetryProvider } from "../../zapsdk/core/retry.js"
|
|
|
3
3
|
import type { AgentOutcomeV1 } from "../../zapsdk/runtime/outcome.js"
|
|
4
4
|
import { executeGoalCommand } from "../goal-session.js"
|
|
5
5
|
import { createGoalContentFilter } from "../goal-output.js"
|
|
6
|
+
import { useGoalView } from "./useGoalView.js"
|
|
6
7
|
import { createGoalPresentation } from "../agent/goalPresentation.js"
|
|
7
8
|
import { AgentBudget } from "../../zapsdk/agent/budget.js"
|
|
8
9
|
import { RequestMeter } from "../../zapsdk/agent/request-meter.js"
|
|
@@ -361,6 +362,9 @@ export function useAgentRunner({
|
|
|
361
362
|
}: UseAgentRunnerOptions) {
|
|
362
363
|
const [status, setStatus] = useState("ready")
|
|
363
364
|
const [goalRunning, setGoalRunning] = useState(false)
|
|
365
|
+
const { view: goalStatus, select: selectGoalView, update: updateGoalView, clear: resetGoalView } = useGoalView(currentSessionId, cwd, goalRunning, undefined, appLogger)
|
|
366
|
+
const [goalTodoId, setGoalTodoId] = useState<string>()
|
|
367
|
+
useEffect(() => { setGoalTodoId(undefined) }, [currentSessionId])
|
|
364
368
|
const [outputThroughput, setOutputThroughput] = useState<OutputThroughputSample>()
|
|
365
369
|
const [providerRequest, setProviderRequest] = useState<ProviderRequestEvent>()
|
|
366
370
|
const [step, setStep] = useState(0)
|
|
@@ -545,6 +549,7 @@ export function useAgentRunner({
|
|
|
545
549
|
invocation?: { goalTurn?: GoalTurnInput; goalController?: AbortController; onOutcome?: (outcome: AgentOutcomeV1) => void; signal?: AbortSignal; propagateErrors?: boolean; resultSchema?: "outcome-v1" | "legacy" } & Pick<import("../../zapsdk/agent/loop.js").RunOptions,
|
|
546
550
|
"onInputAccepted" | "hasSteering" | "takeSteering" | "onSteeringAccepted">,
|
|
547
551
|
): Promise<LoopAgentResult | undefined> => {
|
|
552
|
+
if (!invocation?.goalTurn) { resetGoalView(true); setGoalTodoId(undefined) }
|
|
548
553
|
running.current = true
|
|
549
554
|
agentRunStore.clear()
|
|
550
555
|
const controller = new AbortController()
|
|
@@ -947,6 +952,7 @@ export function useAgentRunner({
|
|
|
947
952
|
recordContextDiagnostics,
|
|
948
953
|
recordUsage,
|
|
949
954
|
registerStaticFlushCallback,
|
|
955
|
+
resetGoalView,
|
|
950
956
|
replaceLog,
|
|
951
957
|
todoStore,
|
|
952
958
|
todosRef,
|
|
@@ -957,15 +963,19 @@ export function useAgentRunner({
|
|
|
957
963
|
const runGoalCommand = useCallback(async (args: string[]): Promise<number> => {
|
|
958
964
|
const controller = new AbortController()
|
|
959
965
|
let presentation: ReturnType<typeof createGoalPresentation> | undefined
|
|
960
|
-
let stateLabel = ""
|
|
961
966
|
try {
|
|
962
967
|
return await executeGoalCommand(args, cwd, {
|
|
968
|
+
compact: true,
|
|
969
|
+
onSelected: goal => { selectGoalView(goal); setGoalTodoId(previous => previous === goal.id ? previous : undefined) },
|
|
963
970
|
runTurn: async input => {
|
|
964
971
|
presentation?.finish()
|
|
965
972
|
let outcome: AgentOutcomeV1 | undefined
|
|
966
973
|
try {
|
|
967
974
|
const result = await runAgent(input.prompt, undefined, undefined, input.prompt, {
|
|
968
|
-
signal: input.signal, goalTurn: input,
|
|
975
|
+
signal: input.signal, goalTurn: { ...input, onEvent: event => {
|
|
976
|
+
input.onEvent(event)
|
|
977
|
+
if (!event.path?.length && event.type === "content_final" && event.kind === "tool_result" && event.toolName === "todo_write" && event.result.success) setGoalTodoId(input.goalId)
|
|
978
|
+
} }, goalController: controller, onOutcome: value => { outcome = value }, resultSchema: "outcome-v1", propagateErrors: true,
|
|
969
979
|
})
|
|
970
980
|
if (!result || !outcome) throw new Error("GOAL_TURN_OUTCOME_MISSING")
|
|
971
981
|
return { text: result.text, outcome, toolCalls: result.toolResults.length, sessionId: getCurrentSessionId() }
|
|
@@ -988,12 +998,8 @@ export function useAgentRunner({
|
|
|
988
998
|
},
|
|
989
999
|
onEvent: (event, scope) => presentation?.event(event, scope),
|
|
990
1000
|
onState: goal => {
|
|
991
|
-
|
|
992
|
-
if (
|
|
993
|
-
stateLabel = label
|
|
994
|
-
addLog("system", `Goal ${label}${goal.stopReason ? ` · ${goal.stopReason}` : ""}`)
|
|
995
|
-
if (!controller.signal.aborted) setStatus(goal.phase ?? "preparing")
|
|
996
|
-
}
|
|
1001
|
+
updateGoalView(goal)
|
|
1002
|
+
if (!controller.signal.aborted) setStatus(goal.phase ?? "preparing")
|
|
997
1003
|
},
|
|
998
1004
|
onMessage: text => addLog("system", text),
|
|
999
1005
|
onResult: text => { presentation?.finish(); addLog("agent", text) },
|
|
@@ -1005,7 +1011,7 @@ export function useAgentRunner({
|
|
|
1005
1011
|
setGoalRunning(false); setStatus("ready"); setActiveTool(""); setStep(0); setProviderRequest(undefined)
|
|
1006
1012
|
}
|
|
1007
1013
|
}
|
|
1008
|
-
}, [config, cwd, addLog, replaceLog, peekNextLogId, getIsFrozen, registerStaticFlushCallback, agentRunStore, runAgent])
|
|
1014
|
+
}, [config, cwd, addLog, replaceLog, peekNextLogId, getIsFrozen, registerStaticFlushCallback, agentRunStore, runAgent, selectGoalView, updateGoalView])
|
|
1009
1015
|
|
|
1010
1016
|
const runAgentRef = useRef(runAgent)
|
|
1011
1017
|
runAgentRef.current = runAgent
|
|
@@ -1049,6 +1055,9 @@ export function useAgentRunner({
|
|
|
1049
1055
|
runAgent,
|
|
1050
1056
|
runGoalCommand,
|
|
1051
1057
|
goalRunning,
|
|
1058
|
+
goalStatus,
|
|
1059
|
+
goalTodoId,
|
|
1060
|
+
resetGoalView,
|
|
1052
1061
|
running,
|
|
1053
1062
|
abortRef,
|
|
1054
1063
|
status,
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { useCallback, useEffect, useRef, useState } from "react"
|
|
2
|
+
import type { GoalRecord } from "../../zapsdk/goal/contracts.js"
|
|
3
|
+
import type { Logger } from "../../zapsdk/debug/logger.js"
|
|
4
|
+
import { goalView, isFinishedGoal, readSessionGoalView, type GoalView } from "../goal-view.js"
|
|
5
|
+
import { startGoalViewPolling } from "../goal-view-poller.js"
|
|
6
|
+
|
|
7
|
+
interface Binding { sessionId: string; selectedId?: string; view?: GoalView; hidden?: boolean }
|
|
8
|
+
|
|
9
|
+
export function useGoalView(sessionId: string, cwd: string, attached: boolean, databasePath?: string, logger?: Pick<Logger, "debug">) {
|
|
10
|
+
const activeSession = useRef(sessionId)
|
|
11
|
+
activeSession.current = sessionId
|
|
12
|
+
const [binding, setBinding] = useState<Binding>({ sessionId })
|
|
13
|
+
const current = binding.sessionId === sessionId ? binding : undefined
|
|
14
|
+
const select = useCallback((goal: GoalRecord) => {
|
|
15
|
+
if (activeSession.current !== sessionId) return
|
|
16
|
+
setBinding({ sessionId, selectedId: goal.id, view: goalView(goal) })
|
|
17
|
+
}, [sessionId])
|
|
18
|
+
const update = useCallback((goal: GoalRecord) => {
|
|
19
|
+
if (activeSession.current !== sessionId) return
|
|
20
|
+
const view = goalView(goal)
|
|
21
|
+
setBinding(previous => previous.sessionId !== sessionId || previous.hidden || previous.selectedId !== goal.id
|
|
22
|
+
|| JSON.stringify(previous.view) === JSON.stringify(view) ? previous : { ...previous, view })
|
|
23
|
+
}, [sessionId])
|
|
24
|
+
const clear = useCallback((finishedOnly = false) => {
|
|
25
|
+
setBinding(previous => previous.sessionId === sessionId && (!finishedOnly || previous.view && isFinishedGoal(previous.view.status))
|
|
26
|
+
? { sessionId, hidden: true } : previous)
|
|
27
|
+
}, [sessionId])
|
|
28
|
+
|
|
29
|
+
useEffect(() => {
|
|
30
|
+
if (attached || current?.hidden) return
|
|
31
|
+
let disposed = false
|
|
32
|
+
const stop = startGoalViewPolling({
|
|
33
|
+
read: () => readSessionGoalView(cwd, sessionId, current?.selectedId, databasePath),
|
|
34
|
+
publish: view => {
|
|
35
|
+
if (disposed || activeSession.current !== sessionId) return
|
|
36
|
+
setBinding(previous => previous.sessionId === sessionId && (previous.hidden || previous.selectedId !== current?.selectedId) ? previous
|
|
37
|
+
: previous.sessionId === sessionId && JSON.stringify(previous.view) === JSON.stringify(view) ? previous
|
|
38
|
+
: { sessionId, selectedId: current?.selectedId, view })
|
|
39
|
+
},
|
|
40
|
+
// Do not log record contents, paths or raw SQLite errors.
|
|
41
|
+
onReadError: error => logger?.debug("goal_view_read_failed", {
|
|
42
|
+
category: error instanceof Error && error.message === "CORRUPT_GOAL_STATE" ? "corrupt" : "unavailable",
|
|
43
|
+
}),
|
|
44
|
+
})
|
|
45
|
+
return () => { disposed = true; stop() }
|
|
46
|
+
}, [sessionId, cwd, attached, current?.selectedId, current?.hidden, databasePath, logger])
|
|
47
|
+
|
|
48
|
+
return { view: current?.hidden ? undefined : current?.view, select, update, clear }
|
|
49
|
+
}
|
package/src/hooks/useSpinner.ts
CHANGED
|
@@ -7,12 +7,15 @@ const DIAG = process.env.ZAPCODE_DIAG === "1"
|
|
|
7
7
|
export function useSpinner(status: string) {
|
|
8
8
|
const [spinIdx, setSpinIdx] = useState(0)
|
|
9
9
|
const [elapsed, setElapsed] = useState(0)
|
|
10
|
+
const [elapsedStatus, setElapsedStatus] = useState(status)
|
|
10
11
|
// Per-second tick counter — when CPU spikes we want log evidence of how
|
|
11
12
|
// many frames the spinner is forcing through React per second. Reset on
|
|
12
13
|
// each second boundary; emit only when DIAG is on so prod logs stay clean.
|
|
13
14
|
const tickStatsRef = useRef({ ticks: 0, windowStart: Date.now() })
|
|
14
15
|
|
|
15
16
|
useEffect(() => {
|
|
17
|
+
setElapsedStatus(status)
|
|
18
|
+
setElapsed(0)
|
|
16
19
|
if (DIAG) appLogger.debug("spinner_status", { status })
|
|
17
20
|
if (status === "ready" || status === "cancelled") {
|
|
18
21
|
setElapsed(0)
|
|
@@ -36,5 +39,5 @@ export function useSpinner(status: string) {
|
|
|
36
39
|
return () => clearInterval(timer)
|
|
37
40
|
}, [status])
|
|
38
41
|
|
|
39
|
-
return { spinIdx, elapsed, spinnerFrames: SPINNER_FRAMES }
|
|
42
|
+
return { spinIdx, elapsed: elapsedStatus === status ? elapsed : 0, spinnerFrames: SPINNER_FRAMES }
|
|
40
43
|
}
|
|
@@ -1,15 +1,21 @@
|
|
|
1
1
|
import { useEffect, useState } from "react"
|
|
2
2
|
import { join } from "node:path"
|
|
3
3
|
import { getAppDataDir } from "../../zapsdk/utils/platform.js"
|
|
4
|
-
import { shouldCheckForUpdates, startUpdateCheck } from "../update-check.js"
|
|
4
|
+
import { shouldCheckForUpdates, startUpdateCheck, startUpdateStatusCheck, type UpdateCheckState } from "../update-check.js"
|
|
5
5
|
import { VERSION } from "../version.js"
|
|
6
6
|
|
|
7
|
-
|
|
8
|
-
|
|
7
|
+
/** Explicit /update requests bypass the automatic-check opt-out as well as the cache. */
|
|
8
|
+
export function useUpdateCheck(manual = false, request = 0): UpdateCheckState {
|
|
9
|
+
const enabled = manual || shouldCheckForUpdates()
|
|
10
|
+
const [state, setState] = useState<UpdateCheckState>({ status: !enabled ? "disabled" : manual ? "checking" : "idle" })
|
|
9
11
|
useEffect(() => {
|
|
10
|
-
if (!
|
|
12
|
+
if (!enabled) { setState({ status: "disabled" }); return }
|
|
13
|
+
if (manual) return startUpdateStatusCheck({ currentVersion: VERSION }, setState)
|
|
14
|
+
// A quiet automatic check retains the success/failure cache. Only explicit
|
|
15
|
+
// dialog requests need fresh metadata and a full checking/error state.
|
|
16
|
+
setState({ status: "idle" })
|
|
11
17
|
return startUpdateCheck({ currentVersion: VERSION,
|
|
12
|
-
cachePath: join(getAppDataDir(), "cache", "update-check.json") },
|
|
13
|
-
}, [])
|
|
14
|
-
return
|
|
18
|
+
cachePath: join(getAppDataDir(), "cache", "update-check.json") }, version => setState({ status: "available", version }))
|
|
19
|
+
}, [enabled, manual, request])
|
|
20
|
+
return state
|
|
15
21
|
}
|
package/src/ui/UpdateNotice.tsx
CHANGED
|
@@ -2,10 +2,10 @@
|
|
|
2
2
|
import { Box, Text } from "ink"
|
|
3
3
|
import { c } from "./theme.js"
|
|
4
4
|
import { VERSION } from "../version.js"
|
|
5
|
+
import type { UpdateCheckState } from "../update-check.js"
|
|
5
6
|
|
|
6
|
-
export function UpdateNotice({
|
|
7
|
-
if (
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
</Text></Box>
|
|
7
|
+
export function UpdateNotice({ state }: { state: UpdateCheckState }) {
|
|
8
|
+
if (state.status !== "available") return null
|
|
9
|
+
const message = `Update available: v${VERSION} → v${state.version} · /update to download, install and restart`
|
|
10
|
+
return <Box paddingX={1}><Text color={c.info}>{message}</Text></Box>
|
|
11
11
|
}
|
package/src/ui/dialog-update.tsx
CHANGED
|
@@ -1,30 +1,43 @@
|
|
|
1
1
|
/** @jsxImportSource react */
|
|
2
2
|
import { useEffect, useRef, useState } from "react"
|
|
3
3
|
import { Text, useInput } from "ink"
|
|
4
|
+
import { useUpdateCheck } from "../hooks/useUpdateCheck.js"
|
|
5
|
+
import { VERSION } from "../version.js"
|
|
4
6
|
import { DialogFrame } from "./dialog-frame.js"
|
|
5
7
|
import { installSelfUpdate, planSelfUpdate, type RestartRequest, type UpdatePlan } from "../self-update.js"
|
|
6
8
|
|
|
7
|
-
export function UpdateDialog({
|
|
8
|
-
|
|
9
|
+
export function UpdateDialog({ busy, sessionId, beforeInstall, onRestart, onCancel }: {
|
|
10
|
+
busy: boolean; sessionId: string
|
|
9
11
|
beforeInstall: () => void
|
|
10
12
|
onRestart: (request: RestartRequest) => void; onCancel: () => void
|
|
11
13
|
}) {
|
|
14
|
+
const [request, setRequest] = useState(0)
|
|
15
|
+
const check = useUpdateCheck(true, request)
|
|
12
16
|
const [plan, setPlan] = useState<UpdatePlan | null>(null)
|
|
13
|
-
const [message, setMessage] = useState("Checking
|
|
17
|
+
const [message, setMessage] = useState("Checking for zapAgent updates…")
|
|
14
18
|
const [installing, setInstalling] = useState(false)
|
|
15
19
|
const started = useRef(false)
|
|
16
20
|
useEffect(() => {
|
|
17
21
|
let active = true
|
|
18
|
-
|
|
22
|
+
setPlan(null)
|
|
23
|
+
if (check.status !== "available") {
|
|
24
|
+
setMessage(check.status === "current" ? `zapAgent v${VERSION} is up to date.`
|
|
25
|
+
: check.status === "error" ? "Could not check for updates. Press r to retry."
|
|
26
|
+
: "Checking for zapAgent updates…")
|
|
27
|
+
return
|
|
28
|
+
}
|
|
29
|
+
const version = check.version
|
|
19
30
|
if (busy) { setMessage("Wait for the current task and queued messages to finish before updating."); return }
|
|
31
|
+
setMessage("Checking installation…")
|
|
20
32
|
void planSelfUpdate(version).then(result => {
|
|
21
33
|
if (active) { setPlan(result); setMessage(`Install v${version} and restart? Your saved session will be restored.`) }
|
|
22
34
|
}, error => { if (active) setMessage(error instanceof Error ? error.message : "Could not prepare update") })
|
|
23
35
|
return () => { active = false }
|
|
24
|
-
}, [
|
|
36
|
+
}, [check, busy])
|
|
25
37
|
useInput((input, key) => {
|
|
26
38
|
if (started.current) return
|
|
27
39
|
if (key.escape || input === "n") { onCancel(); return }
|
|
40
|
+
if (input === "r" && check.status === "error") { setRequest(value => value + 1); return }
|
|
28
41
|
// Enter does not approve: a deliberate 'y' prevents a trailing slash-command
|
|
29
42
|
// Return event from accidentally confirming installation.
|
|
30
43
|
if (input !== "y" || !plan || busy) return
|
|
@@ -38,7 +51,7 @@ export function UpdateDialog({ version, busy, sessionId, beforeInstall, onRestar
|
|
|
38
51
|
setMessage(`Update failed: ${error instanceof Error ? error.message : "unknown error"}. Close this dialog to continue.`)
|
|
39
52
|
})
|
|
40
53
|
})
|
|
41
|
-
return <DialogFrame title="Update zapAgent" hint={installing ? "Please wait — restart follows successful installation" : "y download, install and restart · esc/n later"}>
|
|
54
|
+
return <DialogFrame title="Update zapAgent" hint={installing ? "Please wait — restart follows successful installation" : plan ? "y download, install and restart · esc/n later" : check.status === "error" ? "r retry · esc/n close" : "esc/n close"}>
|
|
42
55
|
<Text>{message}</Text>
|
|
43
56
|
</DialogFrame>
|
|
44
57
|
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/** @jsxImportSource react */
|
|
2
|
+
import { memo, type ReactNode } from "react"
|
|
3
|
+
import { Box, Text } from "ink"
|
|
4
|
+
import type { Todo } from "../../zapsdk/index.js"
|
|
5
|
+
import { goalActionText, goalObjectiveText, type GoalView } from "../goal-view.js"
|
|
6
|
+
import { displayWidth, truncateToWidth } from "./truncate.js"
|
|
7
|
+
import { c } from "./theme.js"
|
|
8
|
+
|
|
9
|
+
export interface GoalStatusProps {
|
|
10
|
+
goal: GoalView
|
|
11
|
+
termWidth: number
|
|
12
|
+
attached?: boolean
|
|
13
|
+
todos?: readonly Todo[]
|
|
14
|
+
children?: ReactNode
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Dynamic input-area content, never an item in Transcript's Static history. */
|
|
18
|
+
export const GoalStatus = memo(function GoalStatus({ goal, termWidth, attached = false, todos = [], children }: GoalStatusProps) {
|
|
19
|
+
const width = Math.max(1, termWidth - 4)
|
|
20
|
+
const prefix = "◇ 目标:"
|
|
21
|
+
const progress = attached && todos.length && width >= 40 ? `已完成 ${todos.filter(todo => todo.status === "completed").length}/${todos.length} 步` : ""
|
|
22
|
+
const title = truncateToWidth(prefix + goalObjectiveText(goal.objective), Math.max(1, width - (progress ? displayWidth(progress) + 2 : 0)))
|
|
23
|
+
const warning = ["blocked", "paused", "awaiting_acceptance", "budget_limited", "failed"].includes(goal.status)
|
|
24
|
+
const symbol = goal.status === "completed" ? "✓" : goal.status === "paused" ? "Ⅱ" : warning ? "!" : "·"
|
|
25
|
+
return (
|
|
26
|
+
<Box flexDirection="column" paddingX={2} marginTop={1}>
|
|
27
|
+
<Box flexDirection="row">
|
|
28
|
+
<Text color={c.text.primary} wrap="truncate-end">{title}</Text>
|
|
29
|
+
{progress ? <Text color={c.text.faint}>{` ${progress}`}</Text> : null}
|
|
30
|
+
</Box>
|
|
31
|
+
{children ?? <Text color={goal.status === "failed" ? c.error : warning ? c.warning : c.text.muted} wrap="truncate-end">
|
|
32
|
+
{truncateToWidth(`${symbol} ${goalActionText(goal, attached, todos)}`, width)}
|
|
33
|
+
</Text>}
|
|
34
|
+
</Box>
|
|
35
|
+
)
|
|
36
|
+
})
|
package/src/ui/live-activity.tsx
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
/** @jsxImportSource react */
|
|
2
2
|
import { shellCommandDisplay } from "../../zapsdk/utils/shell.js";
|
|
3
|
-
import { memo, useEffect, useRef } from "react"
|
|
3
|
+
import { memo, useEffect, useRef, type ReactNode } from "react"
|
|
4
4
|
import { Box, Text } from "ink"
|
|
5
5
|
import type { LogEntry } from "./types.js"
|
|
6
|
+
import { GoalStatus } from "./goal-status.js"
|
|
7
|
+
import { goalActionText, type GoalView } from "../goal-view.js"
|
|
8
|
+
import type { Todo } from "../../zapsdk/index.js"
|
|
6
9
|
import type { ProviderRequestEvent } from "../../zapsdk/core/llm.js"
|
|
7
10
|
import { c } from "./theme.js"
|
|
8
11
|
import { shortAgentLabel } from "./group-logs.js"
|
|
@@ -13,6 +16,7 @@ import { useSpinner } from "../hooks/useSpinner.js"
|
|
|
13
16
|
import {
|
|
14
17
|
activityProgress,
|
|
15
18
|
buildLiveActivityCopy,
|
|
19
|
+
formatActivityDuration,
|
|
16
20
|
type ActivityProgressKind,
|
|
17
21
|
} from "./activity-status.js"
|
|
18
22
|
|
|
@@ -99,6 +103,10 @@ export function collectPendingTools(logs: LogEntry[]): LogEntry[] {
|
|
|
99
103
|
}
|
|
100
104
|
|
|
101
105
|
export interface LiveActivityProps {
|
|
106
|
+
goal?: GoalView
|
|
107
|
+
goalAttached?: boolean
|
|
108
|
+
goalTodos?: readonly Todo[]
|
|
109
|
+
goalAwaitingInput?: boolean
|
|
102
110
|
isRunning: boolean
|
|
103
111
|
isStreaming: boolean
|
|
104
112
|
isThinking: boolean
|
|
@@ -128,14 +136,34 @@ function statusLabel(status: string, activeTool: string): string {
|
|
|
128
136
|
return STATUS_LABELS[status] ?? status ?? "Working"
|
|
129
137
|
}
|
|
130
138
|
|
|
139
|
+
/** A quiet, transient maintenance row; never appended to conversation history. */
|
|
140
|
+
export function CompactActivity({ elapsed, stopHint = "Esc twice to stop", termWidth, embedded = false }: {
|
|
141
|
+
elapsed: number; stopHint?: string; termWidth: number; embedded?: boolean
|
|
142
|
+
}) {
|
|
143
|
+
return (
|
|
144
|
+
<Box flexDirection="column" paddingLeft={embedded ? 0 : 2} marginTop={embedded ? 0 : 1}>
|
|
145
|
+
<Text wrap="truncate-end">
|
|
146
|
+
<Text color={c.maintenance}>· Compacting conversation…</Text>
|
|
147
|
+
<Text color={c.text.faint}> ({formatActivityDuration(elapsed)})</Text>
|
|
148
|
+
</Text>
|
|
149
|
+
<Text color={c.text.faint} wrap="truncate-end">
|
|
150
|
+
{truncateToWidth(` └ Tip: ${stopHint} compaction.`, Math.max(1, termWidth - (embedded ? 4 : 2)))}
|
|
151
|
+
</Text>
|
|
152
|
+
</Box>
|
|
153
|
+
)
|
|
154
|
+
}
|
|
155
|
+
|
|
131
156
|
export const LiveActivity = memo(function LiveActivity({
|
|
132
157
|
isRunning, isStreaming, isThinking, thinkingChars,
|
|
133
158
|
status, activeTool, activeToolBytes = 0, termWidth, pendingTools,
|
|
134
159
|
lastCompletedTool, providerRequest, stopHint = "Esc twice to stop",
|
|
160
|
+
goal, goalAttached = false, goalTodos = [], goalAwaitingInput = false,
|
|
135
161
|
}: LiveActivityProps) {
|
|
136
162
|
// Keep the 150ms animation state inside this small row. Hosting it in App
|
|
137
163
|
// made every spinner tick reconcile the transcript, prompt and palettes.
|
|
138
|
-
const { spinIdx, elapsed } = useSpinner(status)
|
|
164
|
+
const { spinIdx, elapsed, spinnerFrames } = useSpinner(status)
|
|
165
|
+
const goalActive = !!goal && goalAttached && ["created", "running"].includes(goal.status)
|
|
166
|
+
const waitingForGoalInput = goalActive && goalAwaitingInput
|
|
139
167
|
const progress = activityProgress(isThinking, thinkingChars, activeToolBytes)
|
|
140
168
|
const progressRef = useRef<{
|
|
141
169
|
kind: ActivityProgressKind
|
|
@@ -158,13 +186,23 @@ export const LiveActivity = memo(function LiveActivity({
|
|
|
158
186
|
}
|
|
159
187
|
}, [isRunning, progress.kind, progress.value])
|
|
160
188
|
|
|
189
|
+
const withGoal = (activity: ReactNode) => goal ? <GoalStatus goal={goal} termWidth={termWidth} attached={goalAttached} todos={goalTodos}>
|
|
190
|
+
{!goalActive && <Text color={c.text.muted} wrap="truncate-end">{truncateToWidth(goalActionText(goal, goalAttached), Math.max(1, termWidth - 4))}</Text>}
|
|
191
|
+
{activity}
|
|
192
|
+
</GoalStatus> : activity
|
|
193
|
+
|
|
194
|
+
if (status === "compacting") return withGoal(<CompactActivity elapsed={elapsed} stopHint={stopHint} termWidth={termWidth} embedded={!!goal} />)
|
|
195
|
+
|
|
161
196
|
// Always render a single-row Box (even when idle) so the frame
|
|
162
197
|
// height stays stable across the running→idle transition. Without
|
|
163
198
|
// this, log-update under-erases by 1 row when LiveActivity
|
|
164
199
|
// dismounts and leaves a stray horizontal artifact above the
|
|
165
200
|
// prompt after the first agent response. Cheap: just one blank
|
|
166
201
|
// row of vertical space.
|
|
167
|
-
if (
|
|
202
|
+
if (goal && !goalActive && (!isRunning || goalAttached)) {
|
|
203
|
+
return <GoalStatus goal={goal} termWidth={termWidth} attached={goalAttached} todos={goalTodos} />
|
|
204
|
+
}
|
|
205
|
+
if (!isRunning && !isStreaming && !isThinking && pendingTools.length === 0 && !goal) {
|
|
168
206
|
return <Box height={1} marginTop={1} />
|
|
169
207
|
}
|
|
170
208
|
// Spinner ticks freely and elapsed updates every 150ms. This is safe
|
|
@@ -177,7 +215,7 @@ export const LiveActivity = memo(function LiveActivity({
|
|
|
177
215
|
// output policy. (The earlier "freeze spinner during streaming" patch
|
|
178
216
|
// was a defensive no-op against a tall-frame yank that no longer
|
|
179
217
|
// exists in this architecture.)
|
|
180
|
-
const spinner = SPINNER_FRAMES[spinIdx % SPINNER_FRAMES.length]
|
|
218
|
+
const spinner = goalActive ? spinnerFrames[spinIdx % spinnerFrames.length] : SPINNER_FRAMES[spinIdx % SPINNER_FRAMES.length]
|
|
181
219
|
const toolsSegment = formatPendingToolsLabel(pendingTools)
|
|
182
220
|
const primaryLabel = toolsSegment || statusLabel(status, activeTool)
|
|
183
221
|
const copy = buildLiveActivityCopy({
|
|
@@ -192,26 +230,26 @@ export const LiveActivity = memo(function LiveActivity({
|
|
|
192
230
|
const lastActionSegment = pendingTools.length === 0 && lastCompletedTool?.tool
|
|
193
231
|
? `after ${formatToolLabel(lastCompletedTool.tool.name, lastCompletedTool.tool.arguments)}`
|
|
194
232
|
: ""
|
|
195
|
-
const
|
|
233
|
+
const goalTool = pendingTools.length > 0 || activeToolBytes > 0 ? activeTool : ""
|
|
234
|
+
const segments = [goalActive ? waitingForGoalInput ? "等待你确认操作" : goalActionText(goal!, goalAttached, goalTodos, goalTool) : copy.primaryLabel, copy.elapsed, waitingForGoalInput ? "" : copy.progress, goalActive ? "" : lastActionSegment]
|
|
196
235
|
.filter(Boolean)
|
|
197
236
|
.join(" · ")
|
|
198
|
-
const interruptHint =
|
|
237
|
+
const interruptHint = goal && termWidth < 70
|
|
238
|
+
? goalActive ? "" : stopHint.startsWith("Ctrl+C") ? " Ctrl+C" : termWidth < 40 ? " Esc×2" : " Esc×2 stop"
|
|
239
|
+
: ` ⏎ ${stopHint}`
|
|
199
240
|
const spinnerWidth = displayWidth(spinner) + 1
|
|
200
241
|
const hintWidth = displayWidth(interruptHint)
|
|
201
|
-
const segmentBudget = Math.max(20, termWidth - spinnerWidth - hintWidth - 4)
|
|
242
|
+
const segmentBudget = Math.max(goal ? 1 : 20, termWidth - spinnerWidth - hintWidth - 4)
|
|
202
243
|
const truncated = truncateToWidth(segments, segmentBudget)
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
// colored spinner during compact_start → compact_end.
|
|
207
|
-
const spinnerColor = status === "compacting" || copy.mayBeStalled ? c.warning : c.accent
|
|
208
|
-
return (
|
|
209
|
-
<Box flexDirection="row" paddingLeft={2} marginTop={1}>
|
|
244
|
+
const spinnerColor = copy.mayBeStalled ? c.warning : c.accent
|
|
245
|
+
const activity = (
|
|
246
|
+
<Box flexDirection="row" paddingLeft={goal ? 0 : 2} marginTop={goal ? 0 : 1}>
|
|
210
247
|
<Text color={spinnerColor} wrap="truncate-end">{spinner} </Text>
|
|
211
248
|
<Text color={c.text.muted} wrap="truncate-end">{truncated}</Text>
|
|
212
249
|
<Text color={c.text.faint} wrap="truncate-end">{interruptHint}</Text>
|
|
213
250
|
</Box>
|
|
214
251
|
)
|
|
252
|
+
return withGoal(activity)
|
|
215
253
|
})
|
|
216
254
|
|
|
217
255
|
export function liveActivityHeight(active: boolean): number {
|
package/src/ui/theme.ts
CHANGED
|
@@ -41,6 +41,7 @@ const palette = {
|
|
|
41
41
|
olive: "#94b369", // success — was #7d9655
|
|
42
42
|
mustard: "#dab74a", // warning — was #cba037
|
|
43
43
|
brick: "#cc6651", // error — was #b85543
|
|
44
|
+
periwinkle: "#91a4ff", // context maintenance — distinct from warnings
|
|
44
45
|
sage: "#b6c7b7", // info — was #9fb0a0
|
|
45
46
|
|
|
46
47
|
// Absolute — cool warm-white (slightly brighter than gray100), peat-deep ink
|
|
@@ -76,6 +77,7 @@ export const c = {
|
|
|
76
77
|
warning: palette.mustard,
|
|
77
78
|
error: palette.brick,
|
|
78
79
|
info: palette.sage,
|
|
80
|
+
maintenance: palette.periwinkle,
|
|
79
81
|
|
|
80
82
|
// Cursor / selection
|
|
81
83
|
cursor: palette.tundra400,
|
package/src/ui/todos-panel.tsx
CHANGED
|
@@ -19,8 +19,16 @@ function countBy(todos: Todo[], status: Todo["status"]): number {
|
|
|
19
19
|
return n
|
|
20
20
|
}
|
|
21
21
|
|
|
22
|
-
export
|
|
23
|
-
|
|
22
|
+
export interface TodosPanelProps {
|
|
23
|
+
todos: Todo[]
|
|
24
|
+
goalId?: string
|
|
25
|
+
goalAttached?: boolean
|
|
26
|
+
todoGoalId?: string
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export const TodosPanel = memo(function TodosPanel({ todos, goalId, goalAttached = false, todoGoalId }: TodosPanelProps) {
|
|
30
|
+
// A retained paused/background Goal must not hide a new ordinary turn's list.
|
|
31
|
+
if (todos.length === 0 || goalId && (goalAttached || todoGoalId === goalId)) return null
|
|
24
32
|
const doneCount = countBy(todos, "completed")
|
|
25
33
|
return (
|
|
26
34
|
<Box flexDirection="column" paddingX={2}>
|
package/src/update-check.ts
CHANGED
|
@@ -58,7 +58,7 @@ async function writeCache(path: string, value: Cache): Promise<void> {
|
|
|
58
58
|
finally { await unlink(temporary).catch(() => {}) }
|
|
59
59
|
}
|
|
60
60
|
|
|
61
|
-
export async function fetchLatestRelease(options: UpdateCheckOptions): Promise<string> {
|
|
61
|
+
export async function fetchLatestRelease(options: Omit<UpdateCheckOptions, "cachePath"> & { cachePath?: string }): Promise<string> {
|
|
62
62
|
const controller = new AbortController()
|
|
63
63
|
let timer: ReturnType<typeof setTimeout> | undefined
|
|
64
64
|
let onAbort: (() => void) | undefined
|
|
@@ -127,3 +127,29 @@ export function startUpdateCheck(options: Omit<UpdateCheckOptions, "signal">, no
|
|
|
127
127
|
}).catch(() => {})
|
|
128
128
|
return () => controller.abort()
|
|
129
129
|
}
|
|
130
|
+
|
|
131
|
+
/** Explicit UI checks are fresh; automatic checks stay quiet and cache-aware. */
|
|
132
|
+
export type UpdateCheckState =
|
|
133
|
+
| { status: "checking" | "disabled" | "idle" }
|
|
134
|
+
| { status: "current"; version: string }
|
|
135
|
+
| { status: "available"; version: string }
|
|
136
|
+
| { status: "error" }
|
|
137
|
+
|
|
138
|
+
export async function checkForUpdateStatus(options: Omit<UpdateCheckOptions, "cachePath">): Promise<UpdateCheckState> {
|
|
139
|
+
try {
|
|
140
|
+
const latest = await fetchLatestRelease(options)
|
|
141
|
+
if (options.signal?.aborted) return { status: "error" }
|
|
142
|
+
return { status: isNewerRelease(latest, options.currentVersion) ? "available" : "current", version: latest }
|
|
143
|
+
} catch { return { status: "error" } }
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** Each mount/request owns its cancellation; closed dialogs cannot publish stale results. */
|
|
147
|
+
export function startUpdateStatusCheck(options: Omit<UpdateCheckOptions, "signal" | "cachePath">,
|
|
148
|
+
notify: (state: UpdateCheckState) => void): () => void {
|
|
149
|
+
const controller = new AbortController()
|
|
150
|
+
notify({ status: "checking" })
|
|
151
|
+
void checkForUpdateStatus({ ...options, signal: controller.signal }).then(state => {
|
|
152
|
+
if (!controller.signal.aborted) notify(state)
|
|
153
|
+
})
|
|
154
|
+
return () => controller.abort()
|
|
155
|
+
}
|