zapagent 1.14.16 → 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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "zapagent",
3
- "version": "1.14.16",
3
+ "version": "1.14.18",
4
4
  "packageManager": "bun@1.3.14",
5
5
  "author": "",
6
6
  "main": "src/index.tsx",
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 availableUpdate = useUpdateCheck()
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 version={availableUpdate} />
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 version={availableUpdate} busy={isRunning} sessionId={getCurrentSessionId()} beforeInstall={() => {
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.")
@@ -53,6 +53,8 @@ export interface RunHandlersDeps {
53
53
  currentConfig: AppConfig
54
54
  controller: AbortController
55
55
  preview: StreamingPreview
56
+ /** Optional display-only projection; persisted runtime events stay intact. */
57
+ presentContent?: (event: AgentEvent) => AgentEvent | undefined
56
58
 
57
59
  setStatus: (s: string) => void
58
60
  setOutputThroughput?: (sample: OutputThroughputSample | undefined) => void
@@ -332,8 +334,9 @@ export function createRunHandlers(deps: RunHandlersDeps): RunHandlers {
332
334
  // as part of the next successful response.
333
335
  deps.preview.onThinkingFinal(e.id)
334
336
  })
335
- agent.on("content_delta", (e: AgentEvent) => {
336
- if (e.type !== "content_delta") return
337
+ agent.on("content_delta", (event: AgentEvent) => {
338
+ const e = deps.presentContent ? deps.presentContent(event) : event
339
+ if (e?.type !== "content_delta") return
337
340
  if (e.kind === "text") {
338
341
  deps.setStatus("writing")
339
342
  deps.preview.onTextDelta(e.id, e.text)
@@ -343,8 +346,9 @@ export function createRunHandlers(deps: RunHandlersDeps): RunHandlers {
343
346
  }
344
347
  })
345
348
 
346
- agent.on("content_final", (e: AgentEvent) => {
347
- if (e.type !== "content_final") return
349
+ agent.on("content_final", (event: AgentEvent) => {
350
+ const e = deps.presentContent ? deps.presentContent(event) : event
351
+ if (e?.type !== "content_final") return
348
352
  switch (e.kind) {
349
353
  case "text": {
350
354
  // Flush every paragraph + the trailing in-flight paragraph as a
@@ -571,13 +575,7 @@ export function createRunHandlers(deps: RunHandlersDeps): RunHandlers {
571
575
  const d = e.detail as
572
576
  | { messageCount?: number; tokenEstimate?: number; trigger?: string }
573
577
  | undefined
574
- const msgs = d?.messageCount ?? 0
575
578
  const tok = d?.tokenEstimate ?? 0
576
- const reason = d?.trigger === "force" ? "overflow recovery" : d?.trigger === "tokens" ? "token threshold" : "char threshold"
577
- deps.addLog(
578
- "system",
579
- `🗜 Compacting context — ${msgs} messages / ~${Math.round(tok / 1000)}k tokens (${reason})`,
580
- )
581
579
  // The shared planner already counted schemas and transient context.
582
580
  // Do not add the previous provider-calibrated overhead a second time.
583
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
- // Mirror the in-loop autocompact_start log so manual /compact also
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
@@ -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-host.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { createHash, randomUUID } from "node:crypto"
2
+ import { createGoalContentFilter } from "./goal-output.js"
2
3
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"
3
4
  import { cp, lstat, rm } from "node:fs/promises"
4
5
  import { join, relative, sep } from "node:path"
@@ -185,8 +186,9 @@ export class LocalGoalHost implements GoalHost {
185
186
  }
186
187
  private getWorkspace(): GoalWorkspace { if (!this.workspace) throw new Error("Goal workspace unavailable"); return this.workspace }
187
188
  private phaseHooks(context: GoalOperationContext) {
189
+ const present = createGoalContentFilter(["planning", "verifying", "final_verifying"].includes(context.goal.phase ?? ""))
188
190
  return {
189
- ...(this.onEvent ? { onEvent: (event: import("../zapsdk/agent/events.js").AgentEvent) => this.onEvent!(event, context.operationId) } : {}),
191
+ ...(this.onEvent ? { onEvent: (event: import("../zapsdk/agent/events.js").AgentEvent) => { const visible = present(event); if (visible) this.onEvent!(visible, context.operationId) } } : {}),
190
192
  onSpawn: (pid: number, mayLaunchSealedProcess: boolean) => {
191
193
  if (this.state?.phaseProcess) throw new Error("Previous Goal child process is unresolved")
192
194
  this.state!.phaseProcess = { pid, operationId: context.operationId, requiresReceipt: mayLaunchSealedProcess }; this.persist()
@@ -0,0 +1,90 @@
1
+ import type { AgentEvent } from "../zapsdk/agent/events.js"
2
+ import type { GoalRecord } from "../zapsdk/goal/contracts.js"
3
+
4
+ const dsmlPrefixes = ["||DSML||", "|DSML|", "||DSML||"].flatMap(marker => [`<${marker}`, `</${marker}`])
5
+
6
+ /** Presentation only: keep incomplete protocol tags out of streamed output,
7
+ * without buffering whole replies or stripping ordinary HTML/JSON/code. */
8
+ function dsmlStream() {
9
+ let pending = "", insideTag = false
10
+ return {
11
+ push(chunk: string): string {
12
+ const input = pending + chunk
13
+ pending = ""
14
+ let output = "", offset = 0
15
+ while (offset < input.length) {
16
+ if (insideTag) {
17
+ const end = input.indexOf(">", offset)
18
+ if (end < 0) return output
19
+ insideTag = false; offset = end + 1
20
+ continue
21
+ }
22
+ const start = input.indexOf("<", offset)
23
+ if (start < 0) return output + input.slice(offset)
24
+ output += input.slice(offset, start)
25
+ const tail = input.slice(start)
26
+ if (dsmlPrefixes.some(prefix => tail.startsWith(prefix))) {
27
+ insideTag = true; offset = start
28
+ } else if (dsmlPrefixes.some(prefix => prefix.startsWith(tail))) {
29
+ pending = tail
30
+ return output
31
+ } else {
32
+ output += "<"; offset = start + 1
33
+ }
34
+ }
35
+ return output
36
+ },
37
+ finish(): string {
38
+ const tail = /^<\/?[||]/.test(pending) ? "" : pending
39
+ pending = ""; insideTag = false
40
+ return tail
41
+ },
42
+ }
43
+ }
44
+
45
+ export function stripGoalProtocolTags(text: string): string {
46
+ const stream = dsmlStream()
47
+ return stream.push(text) + stream.finish()
48
+ }
49
+
50
+ /** Raw events still feed persistence and acceptance. Only their UI projection
51
+ * suppresses planner/verifier protocol prose; tool and lifecycle events remain. */
52
+ export function createGoalContentFilter(structured = false) {
53
+ const streams = new Map<string, ReturnType<typeof dsmlStream>>()
54
+ return (event: AgentEvent): AgentEvent | undefined => {
55
+ if ((event.type !== "content_delta" && event.type !== "content_final") || (event.kind !== "text" && event.kind !== "thinking")) return event
56
+ if (structured) return undefined
57
+ const key = JSON.stringify([event.path ?? [], event.kind, event.id])
58
+ if (event.type === "content_final") {
59
+ streams.delete(key)
60
+ return { ...event, text: stripGoalProtocolTags(event.text) }
61
+ }
62
+ let stream = streams.get(key)
63
+ if (!stream) { stream = dsmlStream(); streams.set(key, stream) }
64
+ const text = stream.push(event.text)
65
+ return text ? { ...event, text } : undefined
66
+ }
67
+ }
68
+
69
+ export function goalAcceptanceSummary(goal: GoalRecord): string | undefined {
70
+ const receipt = goal.finalReceipt ?? goal.tasks.find(task => task.receipt && task.receipt.status !== "passed")?.receipt
71
+ if (!receipt) return undefined
72
+ if (receipt.status === "passed") {
73
+ if (goal.status === "ready_for_delivery") return "Goal 验收通过,等待交付授权。"
74
+ return goal.status === "completed" ? "Goal 验收通过。" : "Goal 尚未完成最终验收和交付。"
75
+ }
76
+ if (receipt.status === "failed") return "Goal 验收未通过。"
77
+ if (receipt.status === "error") return "Goal 验收未完成:检查执行失败。"
78
+ return "Goal 验收尚未确认,需要补充信息或授权。"
79
+ }
80
+
81
+ export function goalDeliveryMarkdown(delivery: unknown): string | undefined {
82
+ if (!delivery || typeof delivery !== "object") return undefined
83
+ const value = delivery as { text?: unknown; path?: unknown }
84
+ if (typeof value.text === "string") {
85
+ const text = stripGoalProtocolTags(value.text)
86
+ return text.trim() ? text : undefined
87
+ }
88
+ if (typeof value.path === "string") return `Goal 产物目录:${value.path}`
89
+ return undefined
90
+ }
@@ -3,6 +3,7 @@ import { GoalStore } from "../zapsdk/goal/store.js"
3
3
  import type { GoalRecord } from "../zapsdk/goal/contracts.js"
4
4
  import type { AgentEvent } from "../zapsdk/agent/events.js"
5
5
  import type { PermissionMode } from "./config.js"
6
+ import { goalAcceptanceSummary, goalDeliveryMarkdown } from "./goal-output.js"
6
7
 
7
8
  export interface GoalSessionOptions {
8
9
  runTurn?: import("./goal-turn.js").GoalTurnExecutor
@@ -10,7 +11,11 @@ export interface GoalSessionOptions {
10
11
  sessionId?: string
11
12
  signal?: AbortSignal
12
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
13
17
  onMessage: (text: string) => void
18
+ onResult?: (markdown: string) => void
14
19
  onState?: (goal: GoalRecord) => void
15
20
  onEvent?: (event: AgentEvent, scope: string) => void
16
21
  }
@@ -28,16 +33,19 @@ export async function executeGoalCommand(args: string[], cwd: string, options: G
28
33
  const detach = attached.get(key)
29
34
  if (!detach || args.length > 2 || args[1] && args[1] !== detach.id) throw new Error("No foreground Goal in this session")
30
35
  detach.background()
31
- 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.")
32
37
  return 0
33
38
  }
34
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")
35
40
  let foreground: GoalRecord | undefined
41
+ let selected: GoalRecord | undefined
36
42
  const message = goalCommand(args, cwd, options.permissionMode, process.platform, options.sessionId, goal => {
37
43
  if (attached.has(key)) throw new Error("A foreground Goal is already running in this session")
38
44
  foreground = goal
39
- }, !!options.runTurn)
40
- 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("目标已在后台启动。")
41
49
  if (!foreground) return 0
42
50
  const goal = foreground as GoalRecord
43
51
  let backgroundRequested = false
@@ -64,13 +72,18 @@ export async function executeGoalCommand(args: string[], cwd: string, options: G
64
72
  onOutcome: value => { outcome = value },
65
73
  })
66
74
  if (backgroundRequested && outcome?.status === "paused" && outcome.stopReason === "USER_INPUT_PENDING") {
67
- options.onMessage(goalCommand(["resume", goal.id, "--background"], cwd, options.permissionMode, process.platform, options.sessionId))
68
- options.onMessage(`Goal ${goal.id} is now running in background.`)
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.`)
69
78
  return 0
70
79
  }
71
80
  if (outcome) {
72
- options.onMessage(`Goal ${outcome.id} · ${outcome.status}${outcome.stopReason ? ` · ${outcome.stopReason}` : ""}`)
73
- if (outcome.delivery) options.onMessage(`Goal delivery: ${JSON.stringify(outcome.delivery)}`)
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 ?? "执行未完成"}`)
83
+ const acceptance = goalAcceptanceSummary(outcome)
84
+ if (acceptance) options.onMessage(acceptance)
85
+ const markdown = ["completed", "ready_for_delivery"].includes(outcome.status) ? goalDeliveryMarkdown(outcome.delivery) : undefined
86
+ if (markdown) (options.onResult ?? options.onMessage)(markdown)
74
87
  }
75
88
  return code
76
89
  } finally { attached.delete(key); settle() }
@@ -1,4 +1,5 @@
1
1
  import { z } from "zod"
2
+ import { createGoalContentFilter } from "./goal-output.js"
2
3
  import { canonicalizeWithNearestExistingAncestorSync } from "../zapsdk/builtin-tools/filesystem.js"
3
4
  import { createHash, randomUUID } from "node:crypto"
4
5
  import { constants, existsSync, mkdirSync, readFileSync } from "node:fs"
@@ -207,7 +208,8 @@ export class GoalTurnHost implements GoalHost {
207
208
  return { kind: "retry" as const }
208
209
  }
209
210
  private async turn(context: GoalOperationContext, role: GoalTurnInput["role"], prompt: string, observe?: (event: AgentEvent) => void): Promise<GoalTurnResult> {
210
- const onEvent = (event: AgentEvent) => { observe?.(event); this.onEvent?.(event, context.operationId) }
211
+ const present = createGoalContentFilter(role === "planner" || role === "verifier")
212
+ const onEvent = (event: AgentEvent) => { observe?.(event); const visible = present(event); if (visible) this.onEvent?.(visible, context.operationId) }
211
213
  const input: GoalTurnInput = { cwd: context.goal.cwd, goalId: context.goal.id, epoch: context.goal.ownerEpoch, ledgerPath: goalDatabasePath(),
212
214
  role, prompt, permissionMode: context.goal.permissionMode, signal: context.signal, onEvent: this.executeTurn && ["worker", "repair"].includes(role) ? event => observe?.(event) : onEvent, sessionId: this.state!.sessionId }
213
215
  if (this.executeTurn && ["worker", "repair"].includes(role)) {
@@ -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
+ }
@@ -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
+ }
@@ -2,6 +2,8 @@ import { goalTurnMeter, type GoalTurnInput } from "../goal-turn.js"
2
2
  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
+ import { createGoalContentFilter } from "../goal-output.js"
6
+ import { useGoalView } from "./useGoalView.js"
5
7
  import { createGoalPresentation } from "../agent/goalPresentation.js"
6
8
  import { AgentBudget } from "../../zapsdk/agent/budget.js"
7
9
  import { RequestMeter } from "../../zapsdk/agent/request-meter.js"
@@ -360,6 +362,9 @@ export function useAgentRunner({
360
362
  }: UseAgentRunnerOptions) {
361
363
  const [status, setStatus] = useState("ready")
362
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])
363
368
  const [outputThroughput, setOutputThroughput] = useState<OutputThroughputSample>()
364
369
  const [providerRequest, setProviderRequest] = useState<ProviderRequestEvent>()
365
370
  const [step, setStep] = useState(0)
@@ -544,6 +549,7 @@ export function useAgentRunner({
544
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,
545
550
  "onInputAccepted" | "hasSteering" | "takeSteering" | "onSteeringAccepted">,
546
551
  ): Promise<LoopAgentResult | undefined> => {
552
+ if (!invocation?.goalTurn) { resetGoalView(true); setGoalTodoId(undefined) }
547
553
  running.current = true
548
554
  agentRunStore.clear()
549
555
  const controller = new AbortController()
@@ -726,6 +732,7 @@ export function useAgentRunner({
726
732
  currentConfig,
727
733
  controller,
728
734
  preview: runPreview,
735
+ presentContent: invocation?.goalTurn ? createGoalContentFilter() : undefined,
729
736
  setStatus, setStep, setActiveTool, setActiveToolBytes,
730
737
  setProviderRequest, setOutputThroughput,
731
738
  setContextTokens, setContextPending, setContextDiagnostics: recordContextDiagnostics,
@@ -945,6 +952,7 @@ export function useAgentRunner({
945
952
  recordContextDiagnostics,
946
953
  recordUsage,
947
954
  registerStaticFlushCallback,
955
+ resetGoalView,
948
956
  replaceLog,
949
957
  todoStore,
950
958
  todosRef,
@@ -955,15 +963,19 @@ export function useAgentRunner({
955
963
  const runGoalCommand = useCallback(async (args: string[]): Promise<number> => {
956
964
  const controller = new AbortController()
957
965
  let presentation: ReturnType<typeof createGoalPresentation> | undefined
958
- let stateLabel = ""
959
966
  try {
960
967
  return await executeGoalCommand(args, cwd, {
968
+ compact: true,
969
+ onSelected: goal => { selectGoalView(goal); setGoalTodoId(previous => previous === goal.id ? previous : undefined) },
961
970
  runTurn: async input => {
962
971
  presentation?.finish()
963
972
  let outcome: AgentOutcomeV1 | undefined
964
973
  try {
965
974
  const result = await runAgent(input.prompt, undefined, undefined, input.prompt, {
966
- signal: input.signal, goalTurn: input, goalController: controller, onOutcome: value => { outcome = value }, resultSchema: "outcome-v1", propagateErrors: true,
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,
967
979
  })
968
980
  if (!result || !outcome) throw new Error("GOAL_TURN_OUTCOME_MISSING")
969
981
  return { text: result.text, outcome, toolCalls: result.toolResults.length, sessionId: getCurrentSessionId() }
@@ -986,14 +998,11 @@ export function useAgentRunner({
986
998
  },
987
999
  onEvent: (event, scope) => presentation?.event(event, scope),
988
1000
  onState: goal => {
989
- const label = `${goal.status}/${goal.phase ?? "preparing"} · ${goal.tasks.filter(task => task.status === "passed").length}/${goal.tasks.length} tasks`
990
- if (label !== stateLabel) {
991
- stateLabel = label
992
- addLog("system", `Goal ${label}${goal.stopReason ? ` · ${goal.stopReason}` : ""}`)
993
- if (!controller.signal.aborted) setStatus(goal.phase ?? "preparing")
994
- }
1001
+ updateGoalView(goal)
1002
+ if (!controller.signal.aborted) setStatus(goal.phase ?? "preparing")
995
1003
  },
996
1004
  onMessage: text => addLog("system", text),
1005
+ onResult: text => { presentation?.finish(); addLog("agent", text) },
997
1006
  })
998
1007
  } finally {
999
1008
  if (presentation) {
@@ -1002,7 +1011,7 @@ export function useAgentRunner({
1002
1011
  setGoalRunning(false); setStatus("ready"); setActiveTool(""); setStep(0); setProviderRequest(undefined)
1003
1012
  }
1004
1013
  }
1005
- }, [config, cwd, addLog, replaceLog, peekNextLogId, getIsFrozen, registerStaticFlushCallback, agentRunStore, runAgent])
1014
+ }, [config, cwd, addLog, replaceLog, peekNextLogId, getIsFrozen, registerStaticFlushCallback, agentRunStore, runAgent, selectGoalView, updateGoalView])
1006
1015
 
1007
1016
  const runAgentRef = useRef(runAgent)
1008
1017
  runAgentRef.current = runAgent
@@ -1046,6 +1055,9 @@ export function useAgentRunner({
1046
1055
  runAgent,
1047
1056
  runGoalCommand,
1048
1057
  goalRunning,
1058
+ goalStatus,
1059
+ goalTodoId,
1060
+ resetGoalView,
1049
1061
  running,
1050
1062
  abortRef,
1051
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
+ }
@@ -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
- export function useUpdateCheck(): string | null {
8
- const [version, setVersion] = useState<string | null>(null)
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 (!shouldCheckForUpdates()) return
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") }, setVersion)
13
- }, [])
14
- return version
18
+ cachePath: join(getAppDataDir(), "cache", "update-check.json") }, version => setState({ status: "available", version }))
19
+ }, [enabled, manual, request])
20
+ return state
15
21
  }
package/src/index.tsx CHANGED
@@ -115,7 +115,7 @@ if (args[0] === "goal") {
115
115
  const [{ executeGoalCommand }, { loadAppConfig }, { getAppDataDir }] = await Promise.all([
116
116
  import("./goal-session.js"), import("./config.js"), import("../zapsdk/utils/platform.js"),
117
117
  ])
118
- const displayed = new Set<string>()
118
+ const displayed = new Map<string, string>()
119
119
  let lastPhase = ""
120
120
  try { process.exit(await executeGoalCommand(args.slice(1), process.cwd(), {
121
121
  permissionMode: loadAppConfig(join(getAppDataDir(), "config.json")).permissionMode,
@@ -123,9 +123,13 @@ if (args[0] === "goal") {
123
123
  onState: goal => { const phase = `${goal.status}/${goal.phase ?? "preparing"}`; if (phase !== lastPhase) { lastPhase = phase; process.stdout.write(`\nGoal ${phase} · ${goal.tasks.filter(t => t.status === "passed").length}/${goal.tasks.length} tasks\n`) } },
124
124
  onEvent: (event, scope) => {
125
125
  if ((event.type === "content_delta" || event.type === "content_final") && (event.kind === "text" || event.kind === "thinking")) {
126
- const key = `${scope}:${event.id}`
127
- if (event.type === "content_delta") { displayed.add(key); process.stdout.write(event.text) }
128
- else { if (!displayed.has(key)) process.stdout.write(event.text); process.stdout.write("\n") }
126
+ const key = JSON.stringify([scope, event.path ?? [], event.kind, event.id])
127
+ if (event.type === "content_delta") { displayed.set(key, (displayed.get(key) ?? "") + event.text); process.stdout.write(event.text) }
128
+ else {
129
+ const prior = displayed.get(key) ?? ""
130
+ if (event.text.startsWith(prior)) process.stdout.write(event.text.slice(prior.length))
131
+ displayed.delete(key); process.stdout.write("\n")
132
+ }
129
133
  } else if (event.type === "content_final" && event.kind === "tool_call") process.stdout.write(`\n${event.path?.length ? "Child " : ""}Tool ${event.toolName}: ${JSON.stringify(event.arguments)}\n`)
130
134
  else if (event.type === "content_final" && event.kind === "tool_result") process.stdout.write(`Tool ${event.toolName}: ${event.result.success ? "ok" : "failed"} ${event.result.output ?? event.result.error ?? ""}\n`)
131
135
  else if (event.type === "error") process.stderr.write(event.error + "\n")
@@ -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({ version }: { version: string | null }) {
7
- if (!version) return null
8
- return <Box paddingX={1}><Text color={c.info}>
9
- {`Update available: v${VERSION} → v${version} · /update to download, install and restart`}
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
  }
@@ -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({ version, busy, sessionId, beforeInstall, onRestart, onCancel }: {
8
- version: string | null; busy: boolean; sessionId: string
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 installation…")
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
- if (!version) { setMessage("No newer version is available yet."); return }
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
- }, [version, busy])
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
+ })
@@ -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 (!isRunning && !isStreaming && !isThinking && pendingTools.length === 0) {
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 segments = [copy.primaryLabel, copy.elapsed, copy.progress, lastActionSegment]
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 = ` ⏎ ${stopHint}`
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
- // Compact uses a distinct spinner color (warning) so the user can tell at
204
- // a glance "this isn't the agent thinking, it's the context being
205
- // compressed". Matches the Claude Code pattern of swapping to a system-
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,
@@ -19,8 +19,16 @@ function countBy(todos: Todo[], status: Todo["status"]): number {
19
19
  return n
20
20
  }
21
21
 
22
- export const TodosPanel = memo(function TodosPanel({ todos }: { todos: Todo[] }) {
23
- if (todos.length === 0) return null
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}>
@@ -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
+ }