zcode-app-cli 3.7.3-10 → 3.7.5-11

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.
@@ -1,6 +1,6 @@
1
1
  import { createRequire } from "node:module";
2
2
  import { spawn } from "node:child_process";
3
- import { accessSync, appendFileSync, constants } from "node:fs";
3
+ import { accessSync, appendFileSync, closeSync, constants, fstatSync, openSync, readSync } from "node:fs";
4
4
  import { randomUUID } from "node:crypto";
5
5
  import { link, mkdir, open, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
6
6
  import { homedir } from "node:os";
@@ -51,6 +51,7 @@ var config_example_default = {
51
51
  "skill": true,
52
52
  "mcp": true
53
53
  },
54
+ subagents: { "autoBackgroundMs": 1e3 },
54
55
  memory: {
55
56
  "use": true,
56
57
  "write": true,
@@ -156736,6 +156737,305 @@ var AssistantStream = class {
156736
156737
  }
156737
156738
  };
156738
156739
  //#endregion
156740
+ //#region packages/zcode-tui/src/background-task-events.ts
156741
+ const maximumEntriesPerTask = 32;
156742
+ const maximumCharactersPerTask = 64e3;
156743
+ const maximumEntryCharacters = 2e4;
156744
+ const maximumScopedTurnIds = 256;
156745
+ const maximumScopedToolCallIds = 512;
156746
+ function autonomousInputSource(source) {
156747
+ return source === "background_task" || source === "subagent_message";
156748
+ }
156749
+ function taskIdFor(event) {
156750
+ return event.taskId ?? event.agentId;
156751
+ }
156752
+ function terminalTaskStatus(status) {
156753
+ return status === "completed" || status === "failed" || status === "timed_out" || status === "cancelled" || status === "spawn_error" || status === "lost" || status === "stopped";
156754
+ }
156755
+ function taskFailure(status) {
156756
+ return status === "failed" || status === "timed_out" || status === "spawn_error" || status === "lost";
156757
+ }
156758
+ function bounded(value) {
156759
+ return value.length <= maximumEntryCharacters ? value : value.slice(0, maximumEntryCharacters) + "\n[truncated]";
156760
+ }
156761
+ function backgroundAgentToolName(name) {
156762
+ const normalized = name?.trim().toLowerCase();
156763
+ return normalized === "agent" || normalized === "subagent";
156764
+ }
156765
+ function record$1(value) {
156766
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
156767
+ }
156768
+ function explicitlyBackgroundAgentInput(value) {
156769
+ return record$1(value)?.run_in_background === true;
156770
+ }
156771
+ function asyncAgentResult(value) {
156772
+ const root = record$1(value);
156773
+ return [
156774
+ root,
156775
+ record$1(root?.output),
156776
+ record$1(root?.result)
156777
+ ].some((candidate) => candidate?.isAsync === true || candidate?.status === "async_launched" || candidate?.status === "backgrounded" || typeof candidate?.backgroundTaskId === "string");
156778
+ }
156779
+ function toolScope(event) {
156780
+ const part = event.part?.type === "tool" ? event.part : void 0;
156781
+ return {
156782
+ id: event.toolCallId ?? part?.toolCallId ?? part?.partId,
156783
+ name: event.toolName ?? part?.toolName,
156784
+ parentId: event.progress?.parentToolCallId ?? part?.parentToolCallId
156785
+ };
156786
+ }
156787
+ var BackgroundTaskEventStore = class {
156788
+ activities = /* @__PURE__ */ new Map();
156789
+ handoffTurns = /* @__PURE__ */ new Map();
156790
+ pendingBackgroundTasks = /* @__PURE__ */ new Set();
156791
+ pendingSubagentMessages = /* @__PURE__ */ new Set();
156792
+ scopedTurnIds = /* @__PURE__ */ new Set();
156793
+ scopedToolCallIds = /* @__PURE__ */ new Set();
156794
+ toolParents = /* @__PURE__ */ new Map();
156795
+ seenEventIds = /* @__PURE__ */ new Set();
156796
+ recentTerminalNotices = /* @__PURE__ */ new Map();
156797
+ handle(event) {
156798
+ this.rememberScopedTool(event);
156799
+ if (event.turnId && autonomousInputSource(event.inputSource)) this.rememberScopedTurn(event.turnId);
156800
+ if (event.eventId && !this.claim(event.eventId)) return {
156801
+ changed: false,
156802
+ handoffSettled: false,
156803
+ notices: []
156804
+ };
156805
+ const notices = [];
156806
+ let changed = false;
156807
+ let handoffSettled = false;
156808
+ const taskId = taskIdFor(event);
156809
+ if (event.type === "background_task_completed" && taskId) {
156810
+ this.pendingBackgroundTasks.add(taskId);
156811
+ const status = event.taskStatus ?? "completed";
156812
+ this.record(taskId, "system", `Task ${status.replaceAll("_", " ")}.`, event.turnId);
156813
+ if (taskFailure(status) && event.message) this.record(taskId, "error", event.message, event.turnId);
156814
+ changed = true;
156815
+ if (this.claimTerminalNotice(taskId, status)) notices.push({
156816
+ notification: taskFailure(status) ? "failed" : "completed",
156817
+ summary: `${taskId} · /tasks`,
156818
+ title: taskFailure(status) ? "Background task needs attention" : "Background task completed",
156819
+ tone: taskFailure(status) ? "error" : "muted"
156820
+ });
156821
+ } else if (event.type === "subagent_message" && taskId) {
156822
+ this.pendingSubagentMessages.add(taskId);
156823
+ if (event.message?.trim()) this.record(taskId, "assistant", event.message, event.turnId);
156824
+ changed = true;
156825
+ notices.push({
156826
+ notification: "completed",
156827
+ summary: `${taskId} · /tasks`,
156828
+ title: "Background agent replied",
156829
+ tone: "muted"
156830
+ });
156831
+ } else if (event.type === "subagent_stopped" && taskId) {
156832
+ const status = event.taskStatus ?? "stopped";
156833
+ const detail = event.message ?? `Agent ${status.replaceAll("_", " ")}.`;
156834
+ this.record(taskId, taskFailure(status) ? "error" : "system", detail, event.turnId);
156835
+ changed = true;
156836
+ if (taskFailure(status) && this.claimTerminalNotice(taskId, status)) notices.push({
156837
+ notification: "failed",
156838
+ summary: `${taskId} · /tasks`,
156839
+ title: "Background agent needs attention",
156840
+ tone: "error"
156841
+ });
156842
+ } else if ((event.type === "background_task_started" || event.type === "background_task_updated") && taskId && terminalTaskStatus(event.taskStatus)) changed = true;
156843
+ if ((event.type === "turn_started" || event.type === "turn.started") && event.turnId && autonomousInputSource(event.inputSource)) {
156844
+ const pending = event.inputSource === "background_task" ? this.pendingBackgroundTasks : this.pendingSubagentMessages;
156845
+ const taskIds = [.../* @__PURE__ */ new Set([...event.taskIds ?? [], ...pending])];
156846
+ pending.clear();
156847
+ this.handoffTurns.set(event.turnId, {
156848
+ source: event.inputSource,
156849
+ taskIds
156850
+ });
156851
+ changed = taskIds.length > 0 || changed;
156852
+ return {
156853
+ changed,
156854
+ handoffSettled: false,
156855
+ notices
156856
+ };
156857
+ }
156858
+ const handoff = event.turnId ? this.handoffTurns.get(event.turnId) : void 0;
156859
+ if (handoff && event.kind === "text_delta" && event.delta) {
156860
+ for (const id of handoff.taskIds) this.appendHandoffDelta(id, event.turnId, event.delta);
156861
+ changed = handoff.taskIds.length > 0 || changed;
156862
+ }
156863
+ const completed = event.type === "turn_complete" || event.type === "turn.completed";
156864
+ const failed = event.type === "turn_error" || event.type === "turn.failed";
156865
+ if (handoff && (completed || failed)) {
156866
+ this.handoffTurns.delete(event.turnId);
156867
+ handoffSettled = true;
156868
+ if (failed) {
156869
+ const detail = event.message ?? "The task finished, but ZCode could not process its result.";
156870
+ for (const id of handoff.taskIds) this.record(id, "error", detail, event.turnId);
156871
+ notices.push({
156872
+ notification: "failed",
156873
+ summary: handoff.taskIds.length > 0 ? `${handoff.taskIds.join(", ")} · /tasks` : "/tasks",
156874
+ title: "Background result processing failed",
156875
+ tone: "error"
156876
+ });
156877
+ changed = true;
156878
+ }
156879
+ }
156880
+ return {
156881
+ changed,
156882
+ handoffSettled,
156883
+ notices
156884
+ };
156885
+ }
156886
+ entries(taskId) {
156887
+ return this.activities.get(taskId) ?? [];
156888
+ }
156889
+ hasActiveHandoffs() {
156890
+ return this.handoffTurns.size > 0;
156891
+ }
156892
+ settleActiveHandoffs() {
156893
+ const count = this.handoffTurns.size;
156894
+ this.handoffTurns.clear();
156895
+ return count;
156896
+ }
156897
+ isTaskScoped(event) {
156898
+ return autonomousInputSource(event.inputSource) || Boolean(event.turnId && this.scopedTurnIds.has(event.turnId)) || this.isBackgroundToolScoped(event);
156899
+ }
156900
+ isBackgroundToolScoped(event) {
156901
+ const scope = toolScope(event);
156902
+ const part = event.part?.type === "tool" ? event.part : void 0;
156903
+ return Boolean(backgroundAgentToolName(scope.name) && (explicitlyBackgroundAgentInput(event.input ?? part?.input) || asyncAgentResult(event.result ?? part?.output))) || Boolean(scope.id && this.scopedTool(scope.id)) || Boolean(scope.parentId && this.scopedTool(scope.parentId));
156904
+ }
156905
+ recordUserMessage(taskId, message) {
156906
+ this.record(taskId, "user", message);
156907
+ }
156908
+ recordSystemMessage(taskId, message, failed = false) {
156909
+ this.record(taskId, failed ? "error" : "system", message);
156910
+ }
156911
+ appendHandoffDelta(taskId, turnId, delta) {
156912
+ const entries = this.activities.get(taskId) ?? [];
156913
+ const id = `handoff:${turnId}`;
156914
+ const existing = entries.find((entry) => entry.id === id);
156915
+ if (existing) {
156916
+ existing.text = bounded(existing.text + delta);
156917
+ existing.timestamp = Date.now();
156918
+ } else entries.push({
156919
+ id,
156920
+ kind: "assistant",
156921
+ text: bounded(delta),
156922
+ timestamp: Date.now(),
156923
+ turnId
156924
+ });
156925
+ this.retain(taskId, entries);
156926
+ }
156927
+ record(taskId, kind, text, turnId) {
156928
+ const value = text.trim();
156929
+ if (!value) return;
156930
+ const entries = this.activities.get(taskId) ?? [];
156931
+ entries.push({
156932
+ id: `task-event:${crypto.randomUUID()}`,
156933
+ kind,
156934
+ text: bounded(value),
156935
+ timestamp: Date.now(),
156936
+ ...turnId ? { turnId } : {}
156937
+ });
156938
+ this.retain(taskId, entries);
156939
+ }
156940
+ retain(taskId, entries) {
156941
+ while (entries.length > maximumEntriesPerTask || entries.reduce((total, entry) => total + entry.text.length, 0) > maximumCharactersPerTask) entries.shift();
156942
+ this.activities.set(taskId, entries);
156943
+ }
156944
+ claim(eventId) {
156945
+ if (this.seenEventIds.has(eventId)) return false;
156946
+ this.seenEventIds.add(eventId);
156947
+ if (this.seenEventIds.size > 4096) {
156948
+ const oldest = this.seenEventIds.values().next().value;
156949
+ if (oldest) this.seenEventIds.delete(oldest);
156950
+ }
156951
+ return true;
156952
+ }
156953
+ rememberScopedTurn(turnId) {
156954
+ if (this.scopedTurnIds.has(turnId)) return;
156955
+ this.scopedTurnIds.add(turnId);
156956
+ if (this.scopedTurnIds.size > maximumScopedTurnIds) {
156957
+ const oldest = this.scopedTurnIds.values().next().value;
156958
+ if (oldest) this.scopedTurnIds.delete(oldest);
156959
+ }
156960
+ }
156961
+ rememberScopedTool(event) {
156962
+ const scope = toolScope(event);
156963
+ if (scope.id && scope.parentId) this.rememberToolParent(scope.id, scope.parentId);
156964
+ const part = event.part?.type === "tool" ? event.part : void 0;
156965
+ const backgroundLifecycleParent = (event.type === "background_task_started" || event.type === "background_task_updated") && (event.taskKind === "local_agent" || event.toolName === "Agent") ? event.progress?.parentToolCallId : void 0;
156966
+ if (backgroundLifecycleParent) this.rememberScopedToolCall(backgroundLifecycleParent);
156967
+ if (!scope.id) return;
156968
+ if (backgroundAgentToolName(scope.name) && (explicitlyBackgroundAgentInput(event.input ?? part?.input) || asyncAgentResult(event.result ?? part?.output)) || Boolean(scope.parentId && this.scopedTool(scope.parentId))) this.rememberScopedToolCall(scope.id);
156969
+ }
156970
+ scopedTool(toolCallId) {
156971
+ let current = toolCallId;
156972
+ const visited = /* @__PURE__ */ new Set();
156973
+ while (current && !visited.has(current)) {
156974
+ if (this.scopedToolCallIds.has(current)) return true;
156975
+ visited.add(current);
156976
+ current = this.toolParents.get(current);
156977
+ }
156978
+ return false;
156979
+ }
156980
+ rememberToolParent(toolCallId, parentToolCallId) {
156981
+ this.toolParents.delete(toolCallId);
156982
+ this.toolParents.set(toolCallId, parentToolCallId);
156983
+ if (this.toolParents.size > maximumScopedToolCallIds) {
156984
+ const oldest = this.toolParents.keys().next().value;
156985
+ if (oldest) this.toolParents.delete(oldest);
156986
+ }
156987
+ }
156988
+ rememberScopedToolCall(toolCallId) {
156989
+ if (this.scopedToolCallIds.has(toolCallId)) return;
156990
+ this.scopedToolCallIds.add(toolCallId);
156991
+ if (this.scopedToolCallIds.size > maximumScopedToolCallIds) {
156992
+ const oldest = this.scopedToolCallIds.values().next().value;
156993
+ if (oldest) this.scopedToolCallIds.delete(oldest);
156994
+ }
156995
+ }
156996
+ claimTerminalNotice(taskId, status) {
156997
+ const now = Date.now();
156998
+ const recent = this.recentTerminalNotices.get(taskId);
156999
+ this.recentTerminalNotices.set(taskId, {
157000
+ status,
157001
+ timestamp: now
157002
+ });
157003
+ return !recent || recent.status !== status || now - recent.timestamp > 5e3;
157004
+ }
157005
+ };
157006
+ //#endregion
157007
+ //#region packages/zcode-tui/src/background-task-output.ts
157008
+ const defaultMaximumBytes = 64 * 1024;
157009
+ function readBackgroundTaskOutput(path, maximumBytes = defaultMaximumBytes) {
157010
+ if (!path || !Number.isSafeInteger(maximumBytes) || maximumBytes <= 0) return void 0;
157011
+ let descriptor;
157012
+ try {
157013
+ descriptor = openSync(path, "r");
157014
+ const metadata = fstatSync(descriptor);
157015
+ if (!metadata.isFile() || metadata.size <= 0) return void 0;
157016
+ const byteCount = Math.min(metadata.size, maximumBytes);
157017
+ const position = metadata.size - byteCount;
157018
+ const buffer = Buffer.allocUnsafe(byteCount);
157019
+ let bytesRead = 0;
157020
+ while (bytesRead < byteCount) {
157021
+ const count = readSync(descriptor, buffer, bytesRead, byteCount - bytesRead, position + bytesRead);
157022
+ if (count === 0) break;
157023
+ bytesRead += count;
157024
+ }
157025
+ let start = 0;
157026
+ while (start < Math.min(bytesRead, 3) && (buffer[start] & 192) === 128) start += 1;
157027
+ const text = buffer.subarray(start, bytesRead).toString("utf8").trim();
157028
+ return text ? {
157029
+ text,
157030
+ truncated: position > 0
157031
+ } : void 0;
157032
+ } catch {
157033
+ return;
157034
+ } finally {
157035
+ if (descriptor !== void 0) closeSync(descriptor);
157036
+ }
157037
+ }
157038
+ //#endregion
156739
157039
  //#region packages/zcode-tui/src/bounded-tool-text.ts
156740
157040
  const MAX_ACTIVE_TOOL_TEXT_CHARACTERS = 64e3;
156741
157041
  const markerReserveCharacters = 128;
@@ -157305,6 +157605,8 @@ function normalizeEvent(value) {
157305
157605
  const part = normalizeRestoredPart(partValue);
157306
157606
  const error = body.error;
157307
157607
  const errorRecord = isRecord(error) ? error : void 0;
157608
+ const originMeta = nestedRecord$1(body, "originMeta");
157609
+ const subagentMessage = nestedRecord$1(body, "subagentMessage");
157308
157610
  const streamRecovery = nestedRecord$1(body, "streamRecovery");
157309
157611
  const recordNumber = (record, key) => {
157310
157612
  const field = record?.[key];
@@ -157331,6 +157633,15 @@ function normalizeEvent(value) {
157331
157633
  messageId: asString(body.messageId) ?? asString(body.messageID) ?? asString(body.assistantMessageId) ?? part?.messageId,
157332
157634
  partId: asString(body.partId) ?? asString(body.partID) ?? part?.partId,
157333
157635
  turnId: envelopeString("turnId") ?? envelopeString("turnID"),
157636
+ eventId: asString(value.eventId) ?? (params && asString(params.eventId)) ?? asString(value.id) ?? (params && asString(params.id)) ?? asString(body.eventId) ?? asString(body.id),
157637
+ inputSource: envelopeString("inputSource"),
157638
+ taskId: envelopeString("taskId") ?? envelopeString("taskID") ?? (originMeta && asString(originMeta.workId)),
157639
+ taskIds: strings("taskIds") ?? strings("taskIDs") ?? (originMeta && (Array.isArray(originMeta.workIds) ? originMeta.workIds.filter((item) => typeof item === "string") : asString(originMeta.workId) ? [asString(originMeta.workId)] : void 0)),
157640
+ taskKind: envelopeString("taskKind") ?? envelopeString("taskType"),
157641
+ taskStatus: envelopeString("status"),
157642
+ agentId: envelopeString("agentId") ?? (subagentMessage && asString(subagentMessage.agentId)),
157643
+ agentType: envelopeString("agentType") ?? (subagentMessage && asString(subagentMessage.agentType)),
157644
+ childSessionId: envelopeString("childSessionId") ?? (subagentMessage && asString(subagentMessage.childSessionId)),
157334
157645
  targetTurnId: envelopeString("targetTurnId") ?? envelopeString("targetTurnID"),
157335
157646
  inputId: asString(body.inputId) ?? asString(body.inputID),
157336
157647
  pendingInputId: asString(body.pendingInputId) ?? asString(body.pendingInputID),
@@ -157346,7 +157657,7 @@ function normalizeEvent(value) {
157346
157657
  errorCode: asString(body.errorCode),
157347
157658
  errorPhase: asString(body.errorPhase),
157348
157659
  exceptionType: asString(body.exceptionType),
157349
- message: asString(body.message) ?? (errorRecord && asString(errorRecord.message)),
157660
+ message: asString(body.message) ?? asString(body.summaryText) ?? (type === "subagent_message" ? asString(body.text) : void 0) ?? asString(error) ?? (errorRecord && asString(errorRecord.message)),
157350
157661
  progress: {
157351
157662
  elapsedMs: number("elapsedMs"),
157352
157663
  durationMs: number("durationMs") ?? number("duration"),
@@ -157616,6 +157927,7 @@ const turnTimerFrames = [
157616
157927
  "🕚"
157617
157928
  ];
157618
157929
  const settledTurnTimerFrame = "🕛";
157930
+ const completedTurnTimerFrame = "✓";
157619
157931
  const reducedMotionValues = /* @__PURE__ */ new Set([
157620
157932
  "1",
157621
157933
  "true",
@@ -157638,9 +157950,9 @@ function formatElapsed$1(milliseconds) {
157638
157950
  if (totalSeconds < 3600) return `${Math.floor(totalSeconds / 60)}m ${seconds.toString().padStart(2, "0")}s`;
157639
157951
  return `${Math.floor(totalSeconds / 3600)}h ${Math.floor(totalSeconds % 3600 / 60).toString().padStart(2, "0")}m ${seconds.toString().padStart(2, "0")}s`;
157640
157952
  }
157641
- function turnStatusText(activity, elapsedMilliseconds, showElapsed = true, animateTimer = false) {
157953
+ function turnStatusText(activity, elapsedMilliseconds, showElapsed = true, animateTimer = false, completed = false) {
157642
157954
  if (!showElapsed) return activity;
157643
- const elapsed = `[ ${turnTimerFrame(elapsedMilliseconds, animateTimer)} ${formatElapsed$1(elapsedMilliseconds)} ]`;
157955
+ const elapsed = `[ ${completed ? completedTurnTimerFrame : turnTimerFrame(elapsedMilliseconds, animateTimer)} ${formatElapsed$1(elapsedMilliseconds)} ]`;
157644
157956
  return activity ? `${activity} ── ${elapsed}` : elapsed;
157645
157957
  }
157646
157958
  //#endregion
@@ -161568,16 +161880,29 @@ function backgroundJobFrom(value) {
161568
161880
  const taskId = stringField(value, "taskId", "taskID", "id");
161569
161881
  const status = stringField(value, "status");
161570
161882
  if (!taskId || !status || !backgroundStatuses.has(status)) return void 0;
161883
+ const rawKind = stringField(value, "taskKind", "taskType", "type")?.toLowerCase();
161884
+ const toolName = stringField(value, "toolName");
161885
+ const taskKind = rawKind === "agent" || rawKind === "local_agent" || toolName === "Agent" ? "local_agent" : rawKind === "bash" || rawKind === "local_bash" || toolName === "Bash" ? "local_bash" : rawKind === "workflow" || rawKind === "local_workflow" || toolName === "Workflow" ? "local_workflow" : rawKind === "monitor_mcp" || toolName === "Monitor" ? "monitor_mcp" : "unknown";
161886
+ const rawError = isRecord(value.error) ? value.error : void 0;
161571
161887
  return {
161572
161888
  taskId,
161889
+ taskKind,
161573
161890
  toolCallId: stringField(value, "toolCallId", "toolCallID"),
161574
- toolName: stringField(value, "toolName"),
161891
+ toolName,
161892
+ agentId: stringField(value, "agentId"),
161893
+ agentType: stringField(value, "agentType", "subagentType"),
161894
+ childSessionId: stringField(value, "childSessionId", "childSessionID"),
161895
+ parentSessionId: stringField(value, "parentSessionId", "parentSessionID"),
161896
+ parentToolCallId: stringField(value, "parentToolCallId", "parentToolCallID"),
161897
+ turnId: stringField(value, "turnId", "turnID"),
161575
161898
  blocked: typeof value.blocked === "boolean" ? value.blocked : void 0,
161576
161899
  blockedReason: stringField(value, "blockedReason"),
161577
161900
  cancellable: typeof value.cancellable === "boolean" ? value.cancellable : void 0,
161578
161901
  cancelRequestedAt: timestamp(value.cancelRequestedAt),
161579
161902
  command: stringField(value, "command"),
161580
161903
  description: stringField(value, "description"),
161904
+ prompt: stringField(value, "prompt"),
161905
+ error: stringField(value, "error") ?? (rawError && stringField(rawError, "message")),
161581
161906
  status,
161582
161907
  pid: positiveInteger(value.pid),
161583
161908
  startedAt: timestamp(value.startedAt),
@@ -161637,6 +161962,10 @@ function normalizeRuntimeProjection(value) {
161637
161962
  const runtime = isRecord(value.runtime) ? value.runtime : void 0;
161638
161963
  const rawActiveTools = projection.activeToolCalls;
161639
161964
  const rawBackgroundJobs = projection.backgroundJobs ?? projection.backgroundTasks;
161965
+ const taskDetails = new Map(records(projection.backgroundTaskDetails ?? value.backgroundTaskDetails).flatMap((item) => {
161966
+ const taskId = stringField(item, "taskId", "taskID", "id");
161967
+ return taskId ? [[taskId, item]] : [];
161968
+ }));
161640
161969
  const rawLastError = isRecord(projection.lastError) ? projection.lastError : void 0;
161641
161970
  const lastErrorType = rawLastError && stringField(rawLastError, "type");
161642
161971
  const lastErrorMessage = rawLastError && stringField(rawLastError, "message");
@@ -161652,7 +161981,11 @@ function normalizeRuntimeProjection(value) {
161652
161981
  return tool ? [tool] : [];
161653
161982
  }),
161654
161983
  backgroundJobs: records(rawBackgroundJobs).flatMap((item) => {
161655
- const job = backgroundJobFrom(item);
161984
+ const taskId = stringField(item, "taskId", "taskID", "id");
161985
+ const job = backgroundJobFrom(taskId && taskDetails.has(taskId) ? {
161986
+ ...taskDetails.get(taskId),
161987
+ ...item
161988
+ } : item);
161656
161989
  return job ? [job] : [];
161657
161990
  }),
161658
161991
  contextUsage: contextUsageFrom(runtime?.contextUsage ?? value.contextUsage, projection),
@@ -161758,6 +162091,9 @@ var RuntimeActivityView = class {
161758
162091
  //#region packages/zcode-tui/src/runtime-poll.ts
161759
162092
  const ACTIVE_RUNTIME_POLL_INTERVAL_MS = 1e3;
161760
162093
  const IDLE_RUNTIME_POLL_INTERVAL_MS = 5e3;
162094
+ function runtimeActivityActive(projection) {
162095
+ return Boolean(projection?.activeToolCalls.some(isActiveRuntimeTool) || projection?.backgroundJobs.some(isActiveBackgroundJob));
162096
+ }
161761
162097
  function runtimePollInterval(active) {
161762
162098
  return active ? ACTIVE_RUNTIME_POLL_INTERVAL_MS : IDLE_RUNTIME_POLL_INTERVAL_MS;
161763
162099
  }
@@ -163505,6 +163841,75 @@ var TurnPresentationRegistry = class {
163505
163841
  }
163506
163842
  };
163507
163843
  //#endregion
163844
+ //#region packages/zcode-tui/src/turn-work-tracker.ts
163845
+ const terminalStatuses = /* @__PURE__ */ new Set([
163846
+ "completed",
163847
+ "failed",
163848
+ "timed_out",
163849
+ "cancelled",
163850
+ "spawn_error",
163851
+ "lost",
163852
+ "stopped"
163853
+ ]);
163854
+ function eventTaskId(event) {
163855
+ return event.taskId ?? event.agentId ?? event.progress?.agentId;
163856
+ }
163857
+ function startsTask(event) {
163858
+ return event.type === "background_task_started" || event.type === "subagent_spawned" || event.type === "background_task_updated" && !terminalStatuses.has(event.taskStatus ?? "running");
163859
+ }
163860
+ function settlesTask(event) {
163861
+ return event.type === "background_task_completed" || event.type === "subagent_stopped" || terminalStatuses.has(event.taskStatus ?? "");
163862
+ }
163863
+ var TurnWorkTracker = class {
163864
+ foregroundActive = false;
163865
+ awaitingProjection = false;
163866
+ turnId;
163867
+ taskIds = /* @__PURE__ */ new Set();
163868
+ begin() {
163869
+ this.foregroundActive = true;
163870
+ this.awaitingProjection = false;
163871
+ this.turnId = void 0;
163872
+ this.taskIds.clear();
163873
+ }
163874
+ bindTurn(turnId) {
163875
+ if (turnId) this.turnId = turnId;
163876
+ }
163877
+ handle(event) {
163878
+ const taskId = eventTaskId(event);
163879
+ if (!taskId) return this.isActive();
163880
+ if (settlesTask(event)) {
163881
+ this.taskIds.delete(taskId);
163882
+ return this.isActive();
163883
+ }
163884
+ if (startsTask(event) && this.accepts(event.turnId)) this.taskIds.add(taskId);
163885
+ return this.isActive();
163886
+ }
163887
+ finishForeground(awaitProjection) {
163888
+ this.foregroundActive = false;
163889
+ this.awaitingProjection = awaitProjection;
163890
+ return this.isActive();
163891
+ }
163892
+ reconcile(jobs) {
163893
+ for (const job of jobs) {
163894
+ if (!(this.taskIds.has(job.taskId) || Boolean(this.turnId && job.turnId === this.turnId))) continue;
163895
+ if (job.status === "running") this.taskIds.add(job.taskId);
163896
+ else this.taskIds.delete(job.taskId);
163897
+ }
163898
+ if (!this.foregroundActive) this.awaitingProjection = false;
163899
+ return this.isActive();
163900
+ }
163901
+ isActive() {
163902
+ return this.foregroundActive || this.awaitingProjection || this.taskIds.size > 0;
163903
+ }
163904
+ ownsTask(taskId) {
163905
+ return Boolean(taskId && this.taskIds.has(taskId));
163906
+ }
163907
+ accepts(turnId) {
163908
+ if (turnId && this.turnId) return turnId === this.turnId;
163909
+ return this.foregroundActive || this.awaitingProjection;
163910
+ }
163911
+ };
163912
+ //#endregion
163508
163913
  //#region packages/zcode-tui/src/update-available-view.ts
163509
163914
  const updateCommand = "npm install -g zcode-app-cli@latest";
163510
163915
  const releaseNotesUrl = "https://github.com/kingsword09/zcode-cli/releases/latest";
@@ -164002,6 +164407,29 @@ async function enrichWorkspaceFiles(snapshot, workspaceDirectory) {
164002
164407
  }));
164003
164408
  }
164004
164409
  //#endregion
164410
+ //#region packages/zcode-tui/src/work-duration-view.ts
164411
+ function workedDurationLabel(elapsedMilliseconds) {
164412
+ if (Math.floor(elapsedMilliseconds / 1e3) <= 60) return void 0;
164413
+ return `Worked for ${formatElapsed$1(elapsedMilliseconds)}`;
164414
+ }
164415
+ /** Codex-style settled-work divider retained in the transcript after the task group ends. */
164416
+ var WorkDurationView = class {
164417
+ theme;
164418
+ label;
164419
+ constructor(elapsedMilliseconds, theme) {
164420
+ this.theme = theme;
164421
+ this.label = workedDurationLabel(elapsedMilliseconds);
164422
+ }
164423
+ render(width) {
164424
+ if (!this.label || width <= 0) return [];
164425
+ const available = Math.max(1, width - 1);
164426
+ const content = `─ ${this.label} ─`;
164427
+ const line = content.length >= available ? truncateToWidth(content, available) : `${content}${"─".repeat(available - content.length)}`;
164428
+ return [` ${this.theme.muted(line)}`];
164429
+ }
164430
+ invalidate() {}
164431
+ };
164432
+ //#endregion
164005
164433
  //#region packages/zcode-tui/src/index.ts
164006
164434
  const toolLifecycleEventKinds = /* @__PURE__ */ new Set([
164007
164435
  "tool_input_start",
@@ -164019,6 +164447,55 @@ const terminalThemeQueryTimeoutMs = 100;
164019
164447
  const exitUsageQueryTimeoutMs = 250;
164020
164448
  const updateAvailableBlockId = "update_available";
164021
164449
  const modelRetryBlockIdPrefix = "model_retry_status";
164450
+ const backgroundTaskAttentionStatuses = /* @__PURE__ */ new Set([
164451
+ "failed",
164452
+ "timed_out",
164453
+ "spawn_error",
164454
+ "lost"
164455
+ ]);
164456
+ function backgroundTaskKindLabel(job) {
164457
+ switch (job.taskKind) {
164458
+ case "local_agent": return job.agentType ? `Agent (${job.agentType})` : "Agent";
164459
+ case "local_bash": return "Bash";
164460
+ case "local_workflow": return "Workflow";
164461
+ case "monitor_mcp": return "Monitor";
164462
+ default: return job.toolName ?? "Task";
164463
+ }
164464
+ }
164465
+ function backgroundTaskSortRank(job) {
164466
+ if (isActiveBackgroundJob(job)) return 0;
164467
+ if (backgroundTaskAttentionStatuses.has(job.status)) return 1;
164468
+ return 2;
164469
+ }
164470
+ function backgroundAgentPart(part) {
164471
+ if (part.type !== "tool") return false;
164472
+ const name = part.toolName.trim().toLowerCase();
164473
+ if (name !== "agent" && name !== "subagent") return false;
164474
+ const input = isRecord(part.input) ? part.input : void 0;
164475
+ const output = isRecord(part.output) ? part.output : void 0;
164476
+ const nestedOutput = isRecord(output?.output) ? output.output : void 0;
164477
+ return input?.run_in_background === true || output?.isAsync === true || output?.status === "async_launched" || output?.status === "backgrounded" || typeof output?.backgroundTaskId === "string" || nestedOutput?.isAsync === true || nestedOutput?.status === "async_launched" || nestedOutput?.status === "backgrounded" || typeof nestedOutput?.backgroundTaskId === "string";
164478
+ }
164479
+ function backgroundToolPartIds(parts) {
164480
+ const hidden = /* @__PURE__ */ new Set();
164481
+ for (const part of parts) {
164482
+ if (!backgroundAgentPart(part) || part.type !== "tool") continue;
164483
+ const id = part.toolCallId ?? part.partId;
164484
+ if (id) hidden.add(id);
164485
+ }
164486
+ let changed = true;
164487
+ while (changed) {
164488
+ changed = false;
164489
+ for (const part of parts) {
164490
+ if (part.type !== "tool" || !part.parentToolCallId || !hidden.has(part.parentToolCallId)) continue;
164491
+ const id = part.toolCallId ?? part.partId;
164492
+ if (!id || hidden.has(id)) continue;
164493
+ hidden.add(id);
164494
+ changed = true;
164495
+ }
164496
+ }
164497
+ return hidden;
164498
+ }
164022
164499
  function modelRetryProgress(event, phase) {
164023
164500
  const retryNumber = phase === "started" ? Math.max(1, (event.attempt ?? 2) - 1) : Math.max(1, (event.nextAttempt ?? (event.attempt ?? 1) + 1) - 1);
164024
164501
  const maxRetries = event.maxRetries ?? (event.maxAttempts !== void 0 ? Math.max(1, event.maxAttempts - 1) : void 0);
@@ -164071,6 +164548,16 @@ function restoredToolState(status) {
164071
164548
  default: return "interrupted";
164072
164549
  }
164073
164550
  }
164551
+ var ConditionalContainer = class extends Container {
164552
+ visible;
164553
+ constructor(visible) {
164554
+ super();
164555
+ this.visible = visible;
164556
+ }
164557
+ render(width) {
164558
+ return this.visible() ? super.render(width) : [];
164559
+ }
164560
+ };
164074
164561
  var ZCodeTui = class {
164075
164562
  options;
164076
164563
  animateTurnTimer;
@@ -164081,6 +164568,7 @@ var ZCodeTui = class {
164081
164568
  ui;
164082
164569
  transcript;
164083
164570
  choiceHost = new Container();
164571
+ composerHost = new ConditionalContainer(() => this.choiceDepth === 0);
164084
164572
  runtimeActivity;
164085
164573
  status;
164086
164574
  turnStatus;
@@ -164097,6 +164585,7 @@ var ZCodeTui = class {
164097
164585
  queuedSelectionCommand;
164098
164586
  inputQueue;
164099
164587
  turnAbortController;
164588
+ foregroundTurnInterrupt;
164100
164589
  steerAbortControllers = /* @__PURE__ */ new Set();
164101
164590
  primaryTurnActive = false;
164102
164591
  primaryTurnInputId;
@@ -164130,6 +164619,10 @@ var ZCodeTui = class {
164130
164619
  lastAssistantText = "";
164131
164620
  turnAssistantText = "";
164132
164621
  unsubscribeWorkflow;
164622
+ unsubscribeSession;
164623
+ backgroundTaskEvents = new BackgroundTaskEventStore();
164624
+ turnWork = new TurnWorkTracker();
164625
+ backgroundCoordinatorMessageIds = /* @__PURE__ */ new Set();
164133
164626
  workflowPanel;
164134
164627
  workflowView;
164135
164628
  workflowRefreshInFlight = false;
@@ -164142,6 +164635,7 @@ var ZCodeTui = class {
164142
164635
  turnStartedAt;
164143
164636
  turnElapsedMilliseconds = 0;
164144
164637
  turnTimingVisible = false;
164638
+ turnHadWorkActivity = false;
164145
164639
  turnTimer;
164146
164640
  pendingTurnNotification;
164147
164641
  pendingTurnNotificationDetail = "";
@@ -164159,6 +164653,8 @@ var ZCodeTui = class {
164159
164653
  runtimeRefreshPending = false;
164160
164654
  runtimeRefreshTimer;
164161
164655
  runtimePollTimer;
164656
+ backgroundDrainScheduled = false;
164657
+ backgroundHandoffInterruptInFlight = false;
164162
164658
  updateCheckAbortController;
164163
164659
  loginRequired;
164164
164660
  loginWarning = new Text("", 1, 0);
@@ -164243,6 +164739,9 @@ var ZCodeTui = class {
164243
164739
  if (!this.loginRequired) this.refreshSessionUsage();
164244
164740
  this.scheduleRuntimePoll(0);
164245
164741
  this.loadHistory();
164742
+ if (this.options.subscribeSessionEvents) this.unsubscribeSession = this.options.subscribeSessionEvents((event) => {
164743
+ this.onSessionEvent(event);
164744
+ }) ?? void 0;
164246
164745
  if (this.options.subscribeWorkflowEvents) this.unsubscribeWorkflow = this.options.subscribeWorkflowEvents((event) => {
164247
164746
  this.debugEvent("workflow", event);
164248
164747
  this.refreshWorkflowFromEvent();
@@ -164274,11 +164773,12 @@ var ZCodeTui = class {
164274
164773
  this.ui.addChild(this.transcript);
164275
164774
  this.ui.addChild(this.runtimeActivity);
164276
164775
  this.ui.addChild(this.choiceHost);
164277
- this.ui.addChild(this.turnStatus);
164278
- this.ui.addChild(this.queuedInputView);
164279
- this.ui.addChild(this.attachmentBar);
164280
- this.ui.addChild(this.editor);
164281
- this.ui.addChild(this.status);
164776
+ this.composerHost.addChild(this.turnStatus);
164777
+ this.composerHost.addChild(this.queuedInputView);
164778
+ this.composerHost.addChild(this.attachmentBar);
164779
+ this.composerHost.addChild(this.editor);
164780
+ this.composerHost.addChild(this.status);
164781
+ this.ui.addChild(this.composerHost);
164282
164782
  const commands = this.autocompleteCommands();
164283
164783
  const workspaceDirectory = this.options.workspaceDirectory ?? process.cwd();
164284
164784
  this.editor.setAutocompleteProvider(new WorkspaceAutocompleteProvider(commands, workspaceDirectory, this.options.listWorkspacePathSuggestions, this.skillCatalog, this.options.listPluginReferences ?? createRuntimePluginReferenceLister(workspaceDirectory)));
@@ -164412,8 +164912,8 @@ var ZCodeTui = class {
164412
164912
  },
164413
164913
  {
164414
164914
  name: "tasks",
164415
- description: "Inspect or stop background tasks",
164416
- argumentHint: "[stop <task-id>]"
164915
+ description: "Inspect, message or recover background tasks",
164916
+ argumentHint: "[message|resume|stop <task-id>]"
164417
164917
  },
164418
164918
  {
164419
164919
  name: "diff",
@@ -164548,6 +165048,10 @@ var ZCodeTui = class {
164548
165048
  return { consume: true };
164549
165049
  }
164550
165050
  if (matchesKey(data, "escape")) {
165051
+ if (this.backgroundTaskEvents.hasActiveHandoffs()) {
165052
+ this.clearRewindEscape();
165053
+ return { consume: true };
165054
+ }
164551
165055
  if (this.turnAbortController) {
164552
165056
  this.clearRewindEscape();
164553
165057
  const pendingSteer = this.inputQueue.hasPendingSteers();
@@ -164556,11 +165060,7 @@ var ZCodeTui = class {
164556
165060
  return { consume: true };
164557
165061
  }
164558
165062
  if (pendingSteer) this.requestPendingSteerInterrupt();
164559
- else {
164560
- this.pendingSteerInterrupt = void 0;
164561
- this.turnAbortController.abort();
164562
- this.updateActivity("cancelling…");
164563
- }
165063
+ else this.requestForegroundTurnInterrupt();
164564
165064
  return { consume: true };
164565
165065
  }
164566
165066
  if (this.transcript.searchStatus() || this.transcript.cursorStatus()) {
@@ -164630,6 +165130,14 @@ var ZCodeTui = class {
164630
165130
  await this.stopBackgroundTask(input.slice(12).trim());
164631
165131
  return;
164632
165132
  }
165133
+ if (input.startsWith("/tasks message ")) {
165134
+ await this.sendTaskCommand(input.slice(15), false);
165135
+ return;
165136
+ }
165137
+ if (input.startsWith("/tasks resume ")) {
165138
+ await this.sendTaskCommand(input.slice(14), true);
165139
+ return;
165140
+ }
164633
165141
  if (input === "/diff") {
164634
165142
  await this.showDiffBrowser();
164635
165143
  return;
@@ -164673,6 +165181,14 @@ var ZCodeTui = class {
164673
165181
  });
164674
165182
  return;
164675
165183
  }
165184
+ if (!steering && this.backgroundTaskEvents.hasActiveHandoffs()) {
165185
+ this.inputQueue.queueFollowUp({
165186
+ ...submission,
165187
+ recordHistory: false
165188
+ });
165189
+ this.interruptBackgroundHandoffForInput();
165190
+ return;
165191
+ }
164676
165192
  const turnEpoch = steering ? this.activeTurnEpoch : ++this.turnEpoch;
164677
165193
  if (turnEpoch === void 0) {
164678
165194
  this.inputQueue.queueFollowUp({
@@ -164706,7 +165222,10 @@ var ZCodeTui = class {
164706
165222
  };
164707
165223
  const pendingSteer = steering ? this.inputQueue.trackSteer(submission, inputId, callOptions.expectedTurnId, pendingInputId) : void 0;
164708
165224
  if (steering) this.recentSteerCommit = void 0;
164709
- if (!steering) this.addUserMessage(submission.displayInput, attachments.length);
165225
+ if (!steering) {
165226
+ this.backgroundCoordinatorMessageIds.clear();
165227
+ this.addUserMessage(submission.displayInput, attachments.length);
165228
+ }
164710
165229
  if (submission.pending) this.addNotice([
164711
165230
  submission.pending.primary,
164712
165231
  submission.pending.secondary,
@@ -164760,7 +165279,8 @@ var ZCodeTui = class {
164760
165279
  } catch (error) {
164761
165280
  if (steering && this.activeTurnEpoch !== turnEpoch) return;
164762
165281
  const interruptedForSteer = !steering && this.isPendingSteerInterrupt(turnEpoch, abortController);
164763
- if (abortController.signal.aborted || interruptedForSteer) {
165282
+ const interruptedForeground = !steering && this.foregroundTurnInterrupt === abortController;
165283
+ if (abortController.signal.aborted || interruptedForSteer || interruptedForeground) {
164764
165284
  unfinishedToolState = "cancelled";
164765
165285
  if (!steering) {
164766
165286
  this.inputQueue.autoSend = false;
@@ -164804,6 +165324,7 @@ var ZCodeTui = class {
164804
165324
  const turnFinishState = abortController.signal.aborted ? "cancelled" : unfinishedToolState;
164805
165325
  const recoveryReason = turnFinishState === "cancelled" ? "turn_cancelled" : turnFinishState === "failed" ? "turn_failed" : "turn_ended";
164806
165326
  const targetTurnId = this.activeTurnId;
165327
+ this.turnWork.bindTurn(targetTurnId);
164807
165328
  const pendingSteerInterrupt = this.isPendingSteerInterrupt(turnEpoch, abortController) ? this.pendingSteerInterrupt : void 0;
164808
165329
  const autoSendRecoveredSteers = turnFinishState === "cancelled" && pendingSteerInterrupt !== void 0;
164809
165330
  this.primaryTurnActive = false;
@@ -164811,6 +165332,7 @@ var ZCodeTui = class {
164811
165332
  this.activeTurnId = void 0;
164812
165333
  this.activeTurnEpoch = void 0;
164813
165334
  this.pendingSteerInterrupt = void 0;
165335
+ if (this.foregroundTurnInterrupt === abortController) this.foregroundTurnInterrupt = void 0;
164814
165336
  this.recentSteerCommit = void 0;
164815
165337
  if (this.turnAbortController === abortController) this.turnAbortController = void 0;
164816
165338
  for (const controller of this.steerAbortControllers) controller.abort();
@@ -164857,6 +165379,25 @@ var ZCodeTui = class {
164857
165379
  if (this.isPendingSteerInterrupt(turnEpoch, abortController)) abortController.abort();
164858
165380
  });
164859
165381
  }
165382
+ requestForegroundTurnInterrupt() {
165383
+ const abortController = this.turnAbortController;
165384
+ if (!abortController || abortController.signal.aborted) return;
165385
+ if (this.foregroundTurnInterrupt === abortController) return;
165386
+ this.pendingSteerInterrupt = void 0;
165387
+ this.foregroundTurnInterrupt = abortController;
165388
+ this.updateActivity("cancelling…");
165389
+ const interruptTurn = this.options.interruptTurn;
165390
+ if (!interruptTurn) {
165391
+ abortController.abort();
165392
+ return;
165393
+ }
165394
+ interruptTurn({ reason: "TUI interrupted the active foreground turn." }).then((outcome) => {
165395
+ if (this.turnAbortController !== abortController || abortController.signal.aborted) return;
165396
+ if (!isRecord(outcome) || asString(outcome.kind) !== "stopped") abortController.abort();
165397
+ }).catch(() => {
165398
+ if (this.turnAbortController === abortController && !abortController.signal.aborted) abortController.abort();
165399
+ });
165400
+ }
164860
165401
  isPendingSteerInterrupt(turnEpoch, abortController) {
164861
165402
  const pending = this.pendingSteerInterrupt;
164862
165403
  return pending?.turnEpoch === turnEpoch && pending.abortController === abortController;
@@ -164929,9 +165470,24 @@ var ZCodeTui = class {
164929
165470
  if (turnEpoch !== void 0 && turnEpoch !== this.activeTurnEpoch) return;
164930
165471
  const event = normalizeEvent(value);
164931
165472
  if (!event) return;
165473
+ const taskScoped = this.backgroundTaskEvents.isTaskScoped(event);
165474
+ this.applyBackgroundTaskEvent(event);
165475
+ if (!taskScoped && event.kind && toolLifecycleEventKinds.has(event.kind)) this.turnHadWorkActivity = true;
165476
+ if (this.backgroundTaskEvents.isBackgroundToolScoped(event)) {
165477
+ this.suppressBackgroundToolTranscript(event);
165478
+ this.suppressBackgroundCoordinatorMessage(event.messageId);
165479
+ }
165480
+ if (taskScoped || this.backgroundTaskEvents.isTaskScoped(event)) {
165481
+ if (runtimeRefreshNeeded(event)) this.scheduleRuntimeRefresh();
165482
+ return;
165483
+ }
165484
+ if (this.isBackgroundCoordinatorReasoning(event)) return;
164932
165485
  const steerQueued = event.type === "turn_steer_queued" || event.type === "turn.steerQueued";
164933
165486
  if (this.turnAbortController && steerQueued && event.inputId && this.inputQueue.findSteer(event.inputId) && event.targetTurnId && !this.activeTurnId) this.activeTurnId = event.targetTurnId;
164934
- if ((event.type === "turn_started" || event.type === "turn.started") && event.inputId === this.primaryTurnInputId) this.activeTurnId = event.turnId ?? event.targetTurnId ?? this.activeTurnId;
165487
+ if ((event.type === "turn_started" || event.type === "turn.started") && event.inputId === this.primaryTurnInputId) {
165488
+ this.activeTurnId = event.turnId ?? event.targetTurnId ?? this.activeTurnId;
165489
+ this.turnWork.bindTurn(this.activeTurnId);
165490
+ }
164935
165491
  if (runtimeRefreshNeeded(event)) this.scheduleRuntimeRefresh();
164936
165492
  if (this.inputQueue.handleLifecycleEvent(event)) {
164937
165493
  this.requestStreamRender();
@@ -165007,7 +165563,7 @@ var ZCodeTui = class {
165007
165563
  detail: event.error instanceof Error ? event.error.message : asString(event.error) ?? event.message
165008
165564
  });
165009
165565
  else if (event.type === "model_request_started") this.updateActivity(event.attempt !== void 0 && event.attempt > 1 ? `retrying model request · ${modelRetryProgress(event, "started")}…` : "waiting for model…", false);
165010
- else if (event.type === "turn.failed") {
165566
+ else if (event.type === "turn.failed" || event.type === "turn_error") {
165011
165567
  this.finalizeUnresolvedTools("failed", event.message ?? "Turn failed.");
165012
165568
  this.addSystemEvent({
165013
165569
  tone: "error",
@@ -165059,6 +165615,109 @@ var ZCodeTui = class {
165059
165615
  });
165060
165616
  this.requestStreamRender();
165061
165617
  }
165618
+ onSessionEvent(value) {
165619
+ this.debugEvent("session-subscription", value);
165620
+ const event = normalizeEvent(value);
165621
+ if (!event) return;
165622
+ this.applyBackgroundTaskEvent(event);
165623
+ }
165624
+ isBackgroundCoordinatorReasoning(event) {
165625
+ if (!event.messageId || !this.backgroundCoordinatorMessageIds.has(event.messageId)) return false;
165626
+ return event.kind === "reasoning_start" || event.kind === "reasoning_delta" || event.kind === "reasoning_end" || event.part?.type === "thought" || event.field === "reasoning";
165627
+ }
165628
+ suppressBackgroundCoordinatorMessage(messageId) {
165629
+ if (!messageId) return;
165630
+ this.backgroundCoordinatorMessageIds.add(messageId);
165631
+ let changed = false;
165632
+ for (const [partId, thinking] of [...this.thinkingParts]) {
165633
+ if (this.protocolPartMessages.get(partId) !== messageId) continue;
165634
+ this.thinkingParts.delete(partId);
165635
+ this.protocolPartKinds.delete(partId);
165636
+ this.protocolPartMessages.delete(partId);
165637
+ changed = this.transcript.removeBlock(partId) || changed;
165638
+ if (this.currentThinking === thinking) {
165639
+ this.currentThinking = void 0;
165640
+ this.currentThinkingPartId = void 0;
165641
+ }
165642
+ }
165643
+ if (changed) this.ui.requestRender();
165644
+ }
165645
+ suppressBackgroundToolTranscript(event) {
165646
+ const part = event.part?.type === "tool" ? event.part : void 0;
165647
+ const toolId = event.toolCallId ?? part?.toolCallId ?? part?.partId;
165648
+ let tool = toolId ? this.toolViews.get(toolId) : void 0;
165649
+ const visited = /* @__PURE__ */ new Set();
165650
+ while (tool?.parentToolCallId && !visited.has(tool.id)) {
165651
+ visited.add(tool.id);
165652
+ tool = this.toolViews.get(tool.parentToolCallId) ?? tool;
165653
+ if (visited.has(tool.id)) break;
165654
+ }
165655
+ if (tool && this.transcript.removeBlock(tool.blockId)) this.ui.requestRender();
165656
+ }
165657
+ applyBackgroundTaskEvent(event) {
165658
+ const taskId = event.taskId ?? event.agentId ?? event.progress?.agentId;
165659
+ const startsTask = event.type === "background_task_started" || event.type === "background_task_updated" || event.type === "subagent_spawned";
165660
+ if (this.turnStartedAt !== void 0) {
165661
+ const wasOwned = this.turnWork.ownsTask(taskId);
165662
+ const remainsActive = this.turnWork.handle(event);
165663
+ if (startsTask && !wasOwned && this.turnWork.ownsTask(taskId)) this.turnHadWorkActivity = true;
165664
+ if (!remainsActive) this.settleTurnTiming();
165665
+ }
165666
+ const update = this.backgroundTaskEvents.handle(event);
165667
+ if (update.changed) {
165668
+ this.scheduleRuntimeRefresh(0);
165669
+ this.updateRuntimeActivity();
165670
+ }
165671
+ for (const notice of update.notices) {
165672
+ this.addSystemEvent({
165673
+ tone: notice.tone,
165674
+ title: notice.title,
165675
+ summary: notice.summary,
165676
+ detail: notice.detail
165677
+ });
165678
+ this.notifications.notify(notice.notification, notice.detail ?? `${notice.title} · ${notice.summary}`);
165679
+ }
165680
+ if (update.handoffSettled) this.drainInputAfterBackgroundHandoff();
165681
+ if (update.changed || update.notices.length > 0) this.requestStreamRender();
165682
+ }
165683
+ drainInputAfterBackgroundHandoff() {
165684
+ if (this.backgroundDrainScheduled) return;
165685
+ this.backgroundDrainScheduled = true;
165686
+ queueMicrotask(() => {
165687
+ this.backgroundDrainScheduled = false;
165688
+ if (this.stopped || this.activeSubmissions > 0 || this.backgroundHandoffInterruptInFlight || this.backgroundTaskEvents.hasActiveHandoffs() || !this.inputQueue.autoSend) return;
165689
+ const next = this.inputQueue.takeNextFollowUp();
165690
+ if (next) this.submit(next.input, next);
165691
+ });
165692
+ }
165693
+ interruptBackgroundHandoffForInput() {
165694
+ if (this.backgroundHandoffInterruptInFlight) return;
165695
+ if (!this.options.interruptTurn) {
165696
+ this.addNotice("The background result turn cannot be interrupted in this runtime.", "warning");
165697
+ return;
165698
+ }
165699
+ this.backgroundHandoffInterruptInFlight = true;
165700
+ this.updateActivity("interrupting background result processing…");
165701
+ this.options.interruptTurn({
165702
+ pendingInputIds: [],
165703
+ reason: "User input preempted background result processing.",
165704
+ reservationId: `background_handoff_${crypto.randomUUID()}`,
165705
+ waitForIdle: true
165706
+ }).then((outcome) => {
165707
+ const kind = isRecord(outcome) ? asString(outcome.kind) : void 0;
165708
+ if (kind !== "stopped" && kind !== "idle") throw new Error(`Runtime returned ${kind ?? "an unsupported response"}.`);
165709
+ const settled = this.backgroundTaskEvents.settleActiveHandoffs();
165710
+ this.inputQueue.resetAutoSend();
165711
+ if (settled > 0) this.addNotice("Background result processing was interrupted; starting your queued input.", "muted");
165712
+ }).catch((error) => {
165713
+ const detail = error instanceof Error ? error.message : String(error);
165714
+ this.addNotice(`Unable to interrupt background result processing: ${detail}`, "error");
165715
+ }).finally(() => {
165716
+ this.backgroundHandoffInterruptInFlight = false;
165717
+ this.updateActivity(void 0);
165718
+ this.drainInputAfterBackgroundHandoff();
165719
+ });
165720
+ }
165062
165721
  handleProtocolPartEvent(event) {
165063
165722
  if ((event.type === "part.started" || event.type === "part.upserted") && event.part) {
165064
165723
  this.upsertProtocolPart(event.part);
@@ -165217,9 +165876,11 @@ var ZCodeTui = class {
165217
165876
  this.pendingTurnNotificationDetail = "";
165218
165877
  this.currentToolGroup = void 0;
165219
165878
  this.turnDiffs.beginTurn(prompt);
165220
- this.turnStartedAt = Date.now();
165879
+ this.turnStartedAt = performance.now();
165221
165880
  this.turnElapsedMilliseconds = 0;
165222
165881
  this.turnTimingVisible = true;
165882
+ this.turnHadWorkActivity = false;
165883
+ this.turnWork.begin();
165223
165884
  if (this.turnTimer) clearInterval(this.turnTimer);
165224
165885
  this.turnTimer = setInterval(() => this.updateTurnStatus(), TURN_TIMER_FRAME_DURATION_MS);
165225
165886
  this.turnTimer.unref?.();
@@ -165231,6 +165892,7 @@ var ZCodeTui = class {
165231
165892
  this.assistantStream.clear();
165232
165893
  this.currentThinking = void 0;
165233
165894
  this.currentThinkingPartId = void 0;
165895
+ this.backgroundCoordinatorMessageIds.clear();
165234
165896
  this.presentationRegistry.clear();
165235
165897
  this.turnDiffs.clear();
165236
165898
  this.currentToolGroup = void 0;
@@ -165619,7 +166281,16 @@ var ZCodeTui = class {
165619
166281
  if (text) this.addUserMessage(text, 0, message.messageId);
165620
166282
  continue;
165621
166283
  }
165622
- for (const part of message.parts) this.restorePart(part, message.role, message.messageId);
166284
+ const hiddenToolIds = message.role === "assistant" ? backgroundToolPartIds(message.parts) : /* @__PURE__ */ new Set();
166285
+ const coordinatesBackgroundAgents = message.parts.some(backgroundAgentPart);
166286
+ for (const part of message.parts) {
166287
+ if (coordinatesBackgroundAgents && part.type === "thought") continue;
166288
+ if (part.type === "tool") {
166289
+ const toolId = part.toolCallId ?? part.partId;
166290
+ if (backgroundAgentPart(part) || Boolean(toolId && hiddenToolIds.has(toolId))) continue;
166291
+ }
166292
+ this.restorePart(part, message.role, message.messageId);
166293
+ }
165623
166294
  }
165624
166295
  this.currentToolGroup = void 0;
165625
166296
  this.currentToolGroupBlockId = void 0;
@@ -166632,44 +167303,132 @@ var ZCodeTui = class {
166632
167303
  }
166633
167304
  }
166634
167305
  async showBackgroundTasks() {
166635
- await this.refreshRuntimeState();
166636
- const jobs = [...this.runtimeProjection?.backgroundJobs ?? []].sort((left, right) => Number(isActiveBackgroundJob(right)) - Number(isActiveBackgroundJob(left)) || (right.startedAt ?? 0) - (left.startedAt ?? 0));
166637
- if (jobs.length === 0) {
166638
- this.addNotice("No background tasks.", "muted");
166639
- return;
166640
- }
166641
- const selected = await this.showChoice({
166642
- title: "Background tasks",
166643
- prompt: "Select a task to inspect or stop.",
166644
- items: jobs.map((job) => ({
166645
- value: job.taskId,
166646
- label: job.description ?? job.command ?? job.toolName ?? job.taskId,
166647
- description: [
166648
- job.status,
166649
- job.taskId,
166650
- job.pid ? `pid ${job.pid}` : void 0
167306
+ while (true) {
167307
+ await this.refreshRuntimeState();
167308
+ const jobs = [...this.runtimeProjection?.backgroundJobs ?? []].sort((left, right) => backgroundTaskSortRank(left) - backgroundTaskSortRank(right) || (right.startedAt ?? 0) - (left.startedAt ?? 0));
167309
+ if (jobs.length === 0) {
167310
+ this.addNotice("No background tasks yet. New background work will appear in /tasks.", "muted");
167311
+ return;
167312
+ }
167313
+ const active = jobs.filter(isActiveBackgroundJob).length;
167314
+ const attention = jobs.filter((job) => backgroundTaskAttentionStatuses.has(job.status)).length;
167315
+ const selected = await this.showChoice({
167316
+ title: "Background tasks",
167317
+ prompt: [
167318
+ active > 0 ? `${active} active` : void 0,
167319
+ attention > 0 ? `${attention} need attention` : void 0,
167320
+ `${jobs.length} total`
166651
167321
  ].filter(Boolean).join(" · "),
166652
- payload: job
166653
- }))
166654
- });
166655
- if (!selected || !isRecord(selected.payload)) return;
166656
- const job = jobs.find((candidate) => candidate.taskId === selected.value);
166657
- if (!job) return;
166658
- const canStop = isActiveBackgroundJob(job) && job.cancellable !== false && Boolean(this.options.cancelBackgroundTask);
166659
- if ((await this.showChoice({
166660
- title: `Background task · ${job.taskId}`,
166661
- prompt: job.blocked ? job.blockedReason ?? "This task is blocked." : `Status: ${job.status}.`,
166662
- content: new Text(this.backgroundTaskDetail(job), 1, 0),
166663
- items: [...canStop ? [{
166664
- value: "stop",
166665
- label: "Stop task",
166666
- description: "Request cancellation"
166667
- }] : [], {
166668
- value: "close",
166669
- label: "Close",
166670
- description: "Return to the prompt"
166671
- }]
166672
- }))?.value === "stop") await this.stopBackgroundTask(job.taskId);
167322
+ help: "Type to filter · Up/Down select · Ctrl+O expand activity · Enter manage · Esc return",
167323
+ items: jobs.map((job) => ({
167324
+ value: job.taskId,
167325
+ label: job.description ?? job.command ?? job.toolName ?? job.taskId,
167326
+ description: [
167327
+ job.status.replaceAll("_", " "),
167328
+ backgroundTaskKindLabel(job),
167329
+ job.taskId,
167330
+ job.pid ? `pid ${job.pid}` : void 0
167331
+ ].filter(Boolean).join(" · "),
167332
+ preview: new Text(this.backgroundTaskDetail(job), 1, 0),
167333
+ payload: job
167334
+ }))
167335
+ });
167336
+ if (!selected) return;
167337
+ if (await this.showBackgroundTaskDetail(selected.value) === "close") return;
167338
+ }
167339
+ }
167340
+ async showBackgroundTaskDetail(taskId) {
167341
+ while (true) {
167342
+ await this.refreshRuntimeState();
167343
+ const job = this.runtimeProjection?.backgroundJobs.find((candidate) => candidate.taskId === taskId);
167344
+ if (!job) {
167345
+ this.addNotice(`Background task ${taskId} is no longer available.`, "warning");
167346
+ return "back";
167347
+ }
167348
+ const active = isActiveBackgroundJob(job);
167349
+ const canMessage = job.taskKind === "local_agent" && Boolean(this.options.sendBackgroundTaskMessage);
167350
+ const canStop = active && job.cancellable !== false && Boolean(this.options.cancelBackgroundTask);
167351
+ const items = [
167352
+ ...canMessage ? [{
167353
+ value: "message",
167354
+ label: active ? "Message agent" : "Resume agent",
167355
+ description: active ? "Send guidance to this task" : "Continue from the saved child session"
167356
+ }] : [],
167357
+ ...canMessage && active ? [{
167358
+ value: "restart",
167359
+ label: "Restart agent",
167360
+ description: "Stop this run and resume from the saved child session"
167361
+ }] : [],
167362
+ ...canStop ? [{
167363
+ value: "stop",
167364
+ label: "Stop task",
167365
+ description: "Request cancellation"
167366
+ }] : [],
167367
+ ...!active && job.taskKind === "local_bash" && job.command ? [{
167368
+ value: "prepare-rerun",
167369
+ label: "Prepare rerun",
167370
+ description: "Place a reviewed rerun request in the editor"
167371
+ }] : [],
167372
+ ...job.taskKind === "local_workflow" && this.options.refreshWorkflowPanel ? [{
167373
+ value: "workflow",
167374
+ label: "Open workflow run",
167375
+ description: "Inspect phases, events and workflow controls"
167376
+ }] : [],
167377
+ {
167378
+ value: "refresh",
167379
+ label: "Refresh task",
167380
+ description: "Read the latest status and output"
167381
+ },
167382
+ {
167383
+ value: "back",
167384
+ label: "Back to tasks",
167385
+ description: "Choose another background task"
167386
+ },
167387
+ {
167388
+ value: "close",
167389
+ label: "Close task center",
167390
+ description: "Return to the prompt"
167391
+ }
167392
+ ];
167393
+ const action = await this.showChoice({
167394
+ title: `${backgroundTaskKindLabel(job)} task · ${job.taskId}`,
167395
+ prompt: job.blocked ? job.blockedReason ?? "This task is blocked." : `Status: ${job.status.replaceAll("_", " ")}.`,
167396
+ contentLabel: "Task activity",
167397
+ content: new Text(this.backgroundTaskDetail(job), 1, 0),
167398
+ items
167399
+ });
167400
+ if (!action || action.value === "back") return "back";
167401
+ if (action.value === "close") return "close";
167402
+ if (action.value === "refresh") continue;
167403
+ if (action.value === "stop") {
167404
+ await this.stopBackgroundTask(job.taskId);
167405
+ continue;
167406
+ }
167407
+ if (action.value === "message" || action.value === "restart") {
167408
+ const restart = action.value === "restart";
167409
+ const message = await this.showTextPrompt({
167410
+ title: restart ? "Restart background agent" : active ? "Message background agent" : "Resume background agent",
167411
+ prompt: restart ? `Describe what ${job.agentId ?? job.taskId} should continue or repair after restart.` : active ? `Send guidance to ${job.agentId ?? job.taskId}.` : `Describe what ${job.agentId ?? job.taskId} should continue or repair.`
167412
+ });
167413
+ if (message?.trim()) await this.messageBackgroundTask(job, message.trim(), restart);
167414
+ continue;
167415
+ }
167416
+ if (action.value === "prepare-rerun" && job.command) {
167417
+ this.editor.setText([
167418
+ "Run this command again in the background and report when it finishes:",
167419
+ "",
167420
+ job.command
167421
+ ].join("\n"));
167422
+ this.addNotice(`Prepared a rerun request for ${job.taskId}. Review it, then press Enter.`, "muted");
167423
+ return "close";
167424
+ }
167425
+ if (action.value === "workflow" && this.options.refreshWorkflowPanel) try {
167426
+ const panel = await this.options.refreshWorkflowPanel({ runId: job.taskId });
167427
+ if (isRecord(panel)) await this.showWorkflowPanel(panel);
167428
+ } catch (error) {
167429
+ this.addNotice(error instanceof Error ? error.message : String(error), "error");
167430
+ }
167431
+ }
166673
167432
  }
166674
167433
  async showActivityDetails() {
166675
167434
  await this.refreshRuntimeState();
@@ -166700,22 +167459,101 @@ var ZCodeTui = class {
166700
167459
  const stderr = safe(job.stderrTail);
166701
167460
  const terminalId = safe(job.terminalId);
166702
167461
  const outputPath = safe(job.outputPath);
167462
+ const taskEntries = this.backgroundTaskEvents.entries(job.taskId);
167463
+ const persistedOutput = job.outputPath && !job.outputTail && !job.stdoutTail && !taskEntries.some((entry) => entry.kind === "assistant") ? readBackgroundTaskOutput(job.outputPath) : void 0;
167464
+ const conversation = taskEntries.flatMap((entry) => {
167465
+ const label = entry.kind === "user" ? "You" : entry.kind === "assistant" ? "Agent" : entry.kind === "error" ? "Error" : "Update";
167466
+ const text = safe(entry.text);
167467
+ if (!text) return [];
167468
+ const line = `${label}: ${text}`;
167469
+ return [entry.kind === "error" ? this.theme.error(line) : line];
167470
+ });
166703
167471
  return sanitizeTerminalText([
166704
167472
  safe(job.description),
167473
+ safe(job.prompt),
166705
167474
  safe(job.command),
166706
167475
  [
166707
- safe(job.toolName),
167476
+ backgroundTaskKindLabel(job),
167477
+ job.agentId && job.agentId !== job.taskId ? `agent ${safe(job.agentId)}` : void 0,
167478
+ job.childSessionId ? `session ${safe(job.childSessionId)}` : void 0,
166708
167479
  job.pid ? `pid ${job.pid}` : void 0,
166709
167480
  terminalId ? `terminal ${terminalId}` : void 0,
166710
167481
  job.outputBytes !== void 0 ? `${job.outputBytes.toLocaleString()} output bytes` : void 0
166711
167482
  ].filter(Boolean).join(" · "),
166712
167483
  outputPath ? `Output: ${outputPath}` : void 0,
166713
167484
  job.outputTruncated ? "Output is truncated" : void 0,
167485
+ job.error ? this.theme.error(`Error: ${safe(job.error)}`) : void 0,
166714
167486
  safe(job.stdoutTail),
166715
167487
  stderr ? this.theme.error(stderr) : void 0,
166716
- safe(job.outputTail)
167488
+ safe(job.outputTail),
167489
+ ...persistedOutput ? [
167490
+ "",
167491
+ this.theme.bold("Saved task result"),
167492
+ persistedOutput.truncated ? this.theme.muted("Showing the latest 64 KiB") : void 0,
167493
+ safe(persistedOutput.text)
167494
+ ] : [],
167495
+ ...conversation.length > 0 ? [
167496
+ "",
167497
+ this.theme.bold("Task activity"),
167498
+ ...conversation
167499
+ ] : []
166717
167500
  ].filter((line) => Boolean(line)).join("\n"), { preserveSgr: true });
166718
167501
  }
167502
+ async sendTaskCommand(command, resume) {
167503
+ const value = command.trim();
167504
+ const separator = value.search(/\s/u);
167505
+ const taskId = separator < 0 ? value : value.slice(0, separator);
167506
+ const suppliedMessage = separator < 0 ? "" : value.slice(separator).trim();
167507
+ if (!taskId) {
167508
+ this.addNotice(`Usage: /tasks ${resume ? "resume" : "message"} <task-id> ${resume ? "[instructions]" : "<message>"}`, "muted");
167509
+ return;
167510
+ }
167511
+ await this.refreshRuntimeState();
167512
+ const job = this.runtimeProjection?.backgroundJobs.find((candidate) => candidate.taskId === taskId);
167513
+ if (!job) {
167514
+ this.addNotice(`No background task found with ID ${taskId}.`, "warning");
167515
+ return;
167516
+ }
167517
+ const message = suppliedMessage || (resume ? "Continue the assigned task from the last completed step. Re-check the current workspace state and finish the remaining work." : "");
167518
+ if (!message) {
167519
+ this.addNotice(`Usage: /tasks message ${taskId} <message>`, "muted");
167520
+ return;
167521
+ }
167522
+ await this.messageBackgroundTask(job, message, resume && isActiveBackgroundJob(job));
167523
+ }
167524
+ async messageBackgroundTask(job, message, restart = false) {
167525
+ if (job.taskKind !== "local_agent") {
167526
+ this.addNotice(`${backgroundTaskKindLabel(job)} tasks cannot receive messages.`, "warning");
167527
+ return;
167528
+ }
167529
+ if (!this.options.sendBackgroundTaskMessage) {
167530
+ this.addNotice("Background agent messaging is unavailable in this runtime.", "warning");
167531
+ return;
167532
+ }
167533
+ this.backgroundTaskEvents.recordUserMessage(job.taskId, message);
167534
+ this.updateActivity(restart && isActiveBackgroundJob(job) ? "restarting background agent…" : isActiveBackgroundJob(job) ? "sending task message…" : "resuming background agent…");
167535
+ try {
167536
+ const result = await this.options.sendBackgroundTaskMessage({
167537
+ taskId: job.taskId,
167538
+ message,
167539
+ summary: message.replace(/\s+/gu, " ").trim().slice(0, 200),
167540
+ restart
167541
+ });
167542
+ const record = isRecord(result) ? result : void 0;
167543
+ const status = asString(record?.status);
167544
+ const detail = asString(record?.message) ?? asString(record?.delivery)?.replaceAll("_", " ") ?? "Message delivered.";
167545
+ if (status === "failed") throw new Error(asString(record?.error) ?? detail);
167546
+ this.backgroundTaskEvents.recordSystemMessage(job.taskId, detail);
167547
+ this.addNotice(detail, "muted");
167548
+ await this.refreshRuntimeState();
167549
+ } catch (error) {
167550
+ const detail = error instanceof Error ? error.message : String(error);
167551
+ this.backgroundTaskEvents.recordSystemMessage(job.taskId, detail, true);
167552
+ this.addNotice(`${restart ? "Restart" : "Message"} for ${job.taskId} failed: ${detail}`, "error");
167553
+ } finally {
167554
+ this.updateActivity(void 0);
167555
+ }
167556
+ }
166719
167557
  async stopBackgroundTask(taskId) {
166720
167558
  if (!taskId) {
166721
167559
  this.addNotice("Usage: /tasks stop <task-id>", "muted");
@@ -166873,9 +167711,9 @@ var ZCodeTui = class {
166873
167711
  this.updateTurnStatus(requestRender);
166874
167712
  }
166875
167713
  updateTurnStatus(requestRender = true) {
166876
- if (this.turnStartedAt !== void 0) this.turnElapsedMilliseconds = Math.max(0, Date.now() - this.turnStartedAt);
167714
+ if (this.turnStartedAt !== void 0) this.turnElapsedMilliseconds = Math.max(0, performance.now() - this.turnStartedAt);
166877
167715
  const showElapsed = this.turnStartedAt !== void 0 || !this.activity && this.turnTimingVisible;
166878
- const text = turnStatusText(this.activity, this.turnElapsedMilliseconds, showElapsed, this.turnStartedAt !== void 0 && this.animateTurnTimer) ?? "";
167716
+ const text = turnStatusText(this.activity, this.turnElapsedMilliseconds, showElapsed, this.turnStartedAt !== void 0 && this.animateTurnTimer, this.turnStartedAt === void 0 && this.turnTimingVisible) ?? "";
166879
167717
  const left = text ? this.activity ? this.theme.accent(text) : this.theme.muted(text) : "";
166880
167718
  const goalText = goalStatusText(this.goal);
166881
167719
  const goalLabel = goalStatusLabel(this.goal);
@@ -166898,7 +167736,7 @@ var ZCodeTui = class {
166898
167736
  }, delay);
166899
167737
  this.runtimeRefreshTimer.unref?.();
166900
167738
  }
166901
- scheduleRuntimePoll(delay = runtimePollInterval(this.turnStartedAt !== void 0)) {
167739
+ scheduleRuntimePoll(delay = runtimePollInterval(this.turnStartedAt !== void 0 || runtimeActivityActive(this.runtimeProjection))) {
166902
167740
  if (this.stopped || !this.options.readRuntimeProjection && !this.options.readTodos) return;
166903
167741
  if (this.runtimePollTimer) return;
166904
167742
  this.runtimePollTimer = setTimeout(() => {
@@ -166917,6 +167755,7 @@ var ZCodeTui = class {
166917
167755
  applyRuntimeProjection(projection) {
166918
167756
  if (!projection) return;
166919
167757
  this.runtimeProjection = projection;
167758
+ this.reconcileTurnTiming(projection);
166920
167759
  if (projection.sessionId) this.sessionId = projection.sessionId;
166921
167760
  this.sessionMetrics = mergeMetrics(this.sessionMetrics, {
166922
167761
  contextUsed: projection.contextUsage?.used,
@@ -166955,6 +167794,7 @@ var ZCodeTui = class {
166955
167794
  if (isRecord(projectionResult.value) && Array.isArray(projectionResult.value.todoGroups)) next.todoGroups = normalizeTodoGroups(projectionResult.value);
166956
167795
  }
166957
167796
  if (todosResult.status === "fulfilled" && todosResult.value !== void 0) next.todos = normalizeTodos(todosResult.value);
167797
+ if (next.projection) this.reconcileTurnTiming(next.projection);
166958
167798
  if (runtimePollStateChanged({
166959
167799
  projection: this.runtimeProjection,
166960
167800
  todos: this.todos,
@@ -166965,7 +167805,7 @@ var ZCodeTui = class {
166965
167805
  if (next.projection) this.applyRuntimeProjection(next.projection);
166966
167806
  else this.updateRuntimeActivity(false);
166967
167807
  this.updateMetadata();
166968
- }
167808
+ } else if (runtimeActivityActive(next.projection)) this.updateRuntimeActivity();
166969
167809
  } while (this.runtimeRefreshPending);
166970
167810
  } finally {
166971
167811
  this.runtimeRefreshInFlight = false;
@@ -167035,19 +167875,30 @@ var ZCodeTui = class {
167035
167875
  this.finalizeUnresolvedTools(unfinishedToolState);
167036
167876
  this.turnDiffs.finishTurn();
167037
167877
  this.currentToolGroup = void 0;
167878
+ if (!this.turnWork.finishForeground(Boolean(this.options.readRuntimeProjection))) this.settleTurnTiming();
167879
+ this.activity = void 0;
167880
+ this.updateTurnStatus();
167881
+ this.scheduleRuntimeRefresh(0);
167882
+ this.rescheduleRuntimePoll();
167883
+ if (notification) this.notifications.notify(notification, notificationDetail);
167884
+ }
167885
+ reconcileTurnTiming(projection) {
167886
+ if (this.turnStartedAt !== void 0 && !this.turnWork.reconcile(projection.backgroundJobs)) this.settleTurnTiming();
167887
+ }
167888
+ settleTurnTiming() {
167889
+ if (!(this.turnStartedAt !== void 0 || this.turnTimer !== void 0)) return;
167038
167890
  if (this.turnStartedAt !== void 0) {
167039
- this.turnElapsedMilliseconds = Math.max(0, Date.now() - this.turnStartedAt);
167891
+ this.turnElapsedMilliseconds = Math.max(0, performance.now() - this.turnStartedAt);
167040
167892
  this.turnStartedAt = void 0;
167041
167893
  }
167042
167894
  if (this.turnTimer) {
167043
167895
  clearInterval(this.turnTimer);
167044
167896
  this.turnTimer = void 0;
167045
167897
  }
167046
- this.activity = void 0;
167898
+ const workedLabel = this.turnHadWorkActivity ? workedDurationLabel(this.turnElapsedMilliseconds) : void 0;
167899
+ if (workedLabel) this.transcript.addBlock(new WorkDurationView(this.turnElapsedMilliseconds, this.theme), { kind: "work-duration" });
167900
+ this.turnTimingVisible = workedLabel === void 0;
167047
167901
  this.updateTurnStatus();
167048
- this.scheduleRuntimeRefresh(0);
167049
- this.rescheduleRuntimePoll();
167050
- if (notification) this.notifications.notify(notification, notificationDetail);
167051
167902
  }
167052
167903
  debugEvent(channel, value) {
167053
167904
  const path = process.env.ZCODE_TUI_DEBUG_EVENTS;
@@ -167071,8 +167922,9 @@ var ZCodeTui = class {
167071
167922
  if (this.rewindEscapeTimer) clearTimeout(this.rewindEscapeTimer);
167072
167923
  if (this.runtimeRefreshTimer) clearTimeout(this.runtimeRefreshTimer);
167073
167924
  if (this.runtimePollTimer) clearTimeout(this.runtimePollTimer);
167925
+ this.unsubscribeSession?.();
167074
167926
  this.unsubscribeWorkflow?.();
167075
- const elapsedMilliseconds = this.turnStartedAt === void 0 ? this.turnElapsedMilliseconds : Math.max(0, Date.now() - this.turnStartedAt);
167927
+ const elapsedMilliseconds = this.turnStartedAt === void 0 ? this.turnElapsedMilliseconds : Math.max(0, performance.now() - this.turnStartedAt);
167076
167928
  this.notifications.stop();
167077
167929
  this.ui.stop();
167078
167930
  this.finishStop(elapsedMilliseconds);