@wherever-dev/client 0.3.1 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,62 @@
1
1
  # @wherever-dev/client
2
2
 
3
+ ## 0.3.3
4
+
5
+ ### Patch Changes
6
+
7
+ - 11c4dc8: Fix a crash that could take down the pi CLI (not the wherever server) when a session was torn down while the client's WebSocket was still connecting, typically when the wherever server is not running. Calling `close()` on a socket that is still in the `CONNECTING` state makes `ws` abort the handshake and emit an `'error'` event asynchronously on the next tick; because `disconnect()` had already removed every listener, that error became an unhandled `EventEmitter` error and surfaced as an `uncaughtException` ("WebSocket was closed before the connection was established"), exiting the process. The existing try/catch could not help since the error was emitted asynchronously rather than thrown synchronously. `disconnect()` now attaches a no-op `'error'` sink to the socket it is tearing down (in both the node `ws` and browser `WebSocket` environments) so the late handshake-abort error is swallowed instead of crashing pi.
8
+
9
+ ## 0.3.2
10
+
11
+ ### Patch Changes
12
+
13
+ - 4836b65: Fix dangling tool calls being hoisted to the end of the transcript on the web frontend, showing as a phantom "series of aborted tool calls" after the latest reply.
14
+
15
+ When loaded history contained a tool call with no matching tool result (e.g. an interrupted long-running `bash` that was superseded by a new user turn, then more replies), the web history mapping deferred every unmatched tool call and appended them all AFTER the last mapped message. So dangling calls from the MIDDLE of the conversation piled up below the latest assistant reply, even though the CLI (and the actual transcript) has them inline where they were issued. The reproducing session was a deliberate recoverability test ("Generate a long message..."/"long running tool call using bash sleep" then interrupting it).
16
+
17
+ The mapping now renders each tool call IN PLACE at its position in the stream: a result-less tool message is emitted when the tool call is seen, and its matching tool result fills it in later (oldest-open-first per tool name, preserving the parallel-call FIFO behaviour). A call that never receives a result stays exactly where it was issued, correctly marked `interrupted` (neutral "no result" state), instead of migrating to the end. On the live streaming tail, only the newest still-open call is kept streaming ("Elapsed" ticking); earlier open calls in the window are interrupted.
18
+
19
+ Tests: two new client tests covering (1) a mid-conversation dangling call staying in place with the final message still an assistant reply, and (2) multiple dangling calls where only the newest streams on the live tail while earlier ones are interrupted in place. All existing tool abort/interrupted/duration tests still pass.
20
+
21
+ - 12083e5: Render an aborted tool call as interrupted, not a red error.
22
+
23
+ When you hit the web "abort" button while tools are running, pi kills the in-flight tools and surfaces each as an errored result with a trailing "...aborted" status ("Command aborted" for bash, "Operation aborted" for edit/write). The web then rendered that as a red error tick, as if the tool had genuinely failed. With parallel tool calls this was especially confusing: a tool that happened to finish just before the abort showed a green success tick while the killed one showed a red error, even though the user aborted the whole turn.
24
+
25
+ The client now detects an abort result (an errored result whose trailing status line is "...aborted") and renders it with the neutral "interrupted" state (muted icon, neutral border) instead of a red error, on both the live tool_end path and when reconstructing from loaded history. A tool that genuinely completed keeps its green success, and a genuine failure keeps its red error. The match is anchored to the trailing status line, so ordinary command output that merely contains the word "aborted" is not misclassified.
26
+
27
+ Also fixes a related mismatch with PARALLEL same-named tools. Live tool_end frames were matched to a tool message by name via a last-match search, so with two concurrent bash calls both tool_end frames could land on the same message, leaving the other tool stuck streaming; it was then finalized by the agent_end sweep with no result and shown as a bogus green success tick. tool_end now claims the OLDEST still-streaming tool of that name (FIFO), so each concurrent call settles a distinct message. And any tool still streaming when the turn ends (agent_end) is now marked interrupted rather than left to render green, since its outcome is unknown.
28
+
29
+ Also adds a `tool-calls` (parallel tool_use) behavior to the test fake LLM to exercise concurrent tool execution.
30
+
31
+ - db16623: Render `read`-tool image output inline in the web frontend, mirroring the CLI's inline image display.
32
+
33
+ When the agent uses the builtin `read` tool on an image path, the pi tool result carries an image content block (`{type:'image', data, mimeType}`) alongside the text note. Previously the server's `extractToolResult` kept only text blocks, so the web never saw the image. The server now also pulls image blocks out of the tool result and ships them (base64 + mimeType) on the `tool_end` frame via a new optional `images` field, and reconstructs them from history when a session is reloaded. The client stores them on the `ChatMessage` (`images`), and the web renders each image inline right under the tool header, always visible (not hidden behind the collapse toggle), while the textual arguments/output stay collapsible. Click an image to open it full size. Text-only tools are unaffected.
34
+
35
+ - 9931867: Pair reconstructed tool results to their exact tool call by id, not just by tool name.
36
+
37
+ The server now forwards the tool-call id on both `tool_call` (the id the assistant issued) and `tool_result` (the `toolCallId` it satisfies) history messages, and the web history mapping matches a result to its exact call by that id, falling back to the previous oldest-open-first per-tool-name behaviour only when no id is present (older sessions, or the synthesized `bashExecution` pair).
38
+
39
+ This fixes mis-pairing when same-named calls interleave with some left dangling: e.g. two `bash` calls issued back-to-back where only the second returns a result. Name-FIFO alone would resolve the first call and leave the second dangling; id matching resolves the correct one and leaves the genuinely-interrupted call marked interrupted, in place.
40
+
41
+ Tests: a new client test covering id-exact pairing (result resolves call #2 by id, leaving call #1 dangling/interrupted, order preserved).
42
+
43
+ - 8536f30: Warn both the web frontend and the CLI when a CLI takeover discards an in-flight turn.
44
+
45
+ When a `pi` CLI resumes/registers a session while the standalone server is mid-turn for a web viewer, the CLI seizes control and the server disposes its live agent. Disposing mid-turn discards the whole in-flight turn without persisting it (persistence only happens on turn completion), so the web viewer, who was watching a tool run or a reply stream, lost it silently with no explanation.
46
+
47
+ The server now detects that the server-side agent was mid-turn at takeover and sends the attached web clients a non-fatal `session_notice` (level: warning). The web frontend renders it as a dismissible banner. The wording is tailored to what was lost: a running tool call (tracked via a per-session in-flight tool-execution count, so its result never arrives) or a streaming reply (the partial text is discarded and not saved). A takeover of an already-settled (idle) session is not flagged. The session stays attached (informational, unlike `session_interrupted`).
48
+
49
+ The notice also states the takeover semantics accurately: once the CLI has taken over it owns the session's execution loop, so messages sent from the web frontend are relayed to the CLI rather than wresting control back. The web frontend regains control only when the CLI disconnects.
50
+
51
+ The CLI side is covered too. On register, the server sends the taking-over CLI a `cli_takeover_interrupted` message, and the Wherever extension surfaces a single matching notice. This closes a blind spot: a still-streaming turn is never persisted, so the extension's own resumed-mid-tool-call check (which reads the saved transcript) cannot see the streaming-text case. For the tool-call case, the extension's transcript check already warns with the tool names, so the server-driven notice defers to it to avoid a duplicate.
52
+
53
+ Also fixes the web frontend rendering a killed-then-orphaned tool call as a green success tick. When a CLI takeover kills an in-flight tool (the pi SDK aborts the run and SIGKILLs the tool's process tree, so it does not keep running in the background), the transcript keeps a dangling toolCall with no toolResult. The web history mapping now flags such a result-less, non-streaming tool call as `interrupted`, and the UI shows a neutral "interrupted, no result" state (a muted ⊘ icon, neutral border, and an explanatory output note) instead of the green ✅ "Succeeded": its outcome is genuinely unknown, neither success nor failure.
54
+
55
+ Also cleans up the CLI's resumed-mid-run warning (the extension's dangling-tool-call widget):
56
+ - It now counts only the TRAILING dangling tool calls (those after the last user message on the active branch), not every unsatisfied tool call in the whole session. Earlier turns' interrupted tool calls are already superseded by a later human turn and do not block auto-continue, so they were over-counted (e.g. "4 tool calls" when only 1 was actually blocking).
57
+ - It shows a single persistent widget instead of a widget plus a duplicate transient notify.
58
+ - Its guidance is corrected: the CLI has already taken over, so it says to send a message to retry or continue, rather than the stale "send a message to take over".
59
+
3
60
  ## 0.3.1
4
61
 
5
62
  ### Patch Changes
package/dist/client.d.ts CHANGED
@@ -52,6 +52,18 @@ export declare class WhereverClient {
52
52
  private clearCreateWatchdog;
53
53
  private scheduleReconnect;
54
54
  private handleMessage;
55
+ /**
56
+ * True when an errored tool result is the product of a USER ABORT (e.g. the
57
+ * web "abort" button killed a running tool), rather than a genuine tool
58
+ * failure. The pi tools append a trailing status line on abort ("Command
59
+ * aborted" for bash, "Operation aborted" for edit/write, bare "aborted" for a
60
+ * pre-execution abort). We match that trailing status so the UI can render a
61
+ * neutral "interrupted" state instead of a red error: you cancelling a tool is
62
+ * not the tool failing. Only meaningful when isError is already true; matched
63
+ * as the LAST non-empty line to avoid false positives from command output that
64
+ * merely contains the word "aborted".
65
+ */
66
+ private isAbortedToolResult;
55
67
  /**
56
68
  * Map a server `HistoryMessage[]` window into UI `ChatMessage[]`. When
57
69
  * `applyStreamingTail` is true, the last assistant/thinking message and any
@@ -84,6 +96,7 @@ export declare class WhereverClient {
84
96
  ping(): void;
85
97
  clearMessages(): void;
86
98
  dismissSessionError(): void;
99
+ dismissNotice(): void;
87
100
  changeModel(model: string): void;
88
101
  setConfig(updates: Partial<WhereverClientConfig>): void;
89
102
  onMessage(cb: (msg: any) => void): () => void;
package/dist/client.js CHANGED
@@ -14,6 +14,7 @@ const defaultState = {
14
14
  clientId: null,
15
15
  conflict: null,
16
16
  isInterrupted: false,
17
+ notice: null,
17
18
  sessionError: null,
18
19
  readOnly: false,
19
20
  activeSessionFile: null,
@@ -285,11 +286,30 @@ export class WhereverClient {
285
286
  this.clearLoadWatchdog();
286
287
  this.clearCreateWatchdog();
287
288
  if (this.ws) {
289
+ const dyingWs = this.ws;
288
290
  try {
289
- if (typeof this.ws.removeAllListeners === 'function') {
290
- this.ws.removeAllListeners();
291
+ if (typeof dyingWs.removeAllListeners === 'function') {
292
+ dyingWs.removeAllListeners();
291
293
  }
292
- this.ws.close();
294
+ // Closing a socket that is still CONNECTING (e.g. the wherever server is
295
+ // not running so the handshake never completed) makes `ws` abort the
296
+ // handshake and emit an 'error' asynchronously on the next tick. With
297
+ // every listener removed, that 'error' would be an unhandled
298
+ // EventEmitter error and crash the whole process as an
299
+ // uncaughtException. Keep a no-op error sink on the socket we are
300
+ // tearing down so the late error is swallowed, in both the node (`ws`)
301
+ // and browser (`WebSocket`) environments.
302
+ const swallow = () => { };
303
+ if (typeof dyingWs.on === 'function') {
304
+ dyingWs.on('error', swallow);
305
+ }
306
+ else if (typeof dyingWs.addEventListener === 'function') {
307
+ dyingWs.addEventListener('error', swallow);
308
+ }
309
+ else {
310
+ dyingWs.onerror = swallow;
311
+ }
312
+ dyingWs.close();
293
313
  }
294
314
  catch (err) { }
295
315
  this.ws = null;
@@ -730,6 +750,13 @@ export class WhereverClient {
730
750
  ? {
731
751
  ...m,
732
752
  isStreaming: false,
753
+ // A tool still streaming when the turn ends never got a
754
+ // tool_end (e.g. the turn was aborted, or its result frame
755
+ // was lost): its outcome is unknown. Mark it interrupted
756
+ // (neutral), never let it fall through to a green success
757
+ // tick, which would falsely claim it succeeded. Assistant/
758
+ // thinking messages just stop streaming.
759
+ ...(m.role === 'tool' ? { interrupted: true } : {}),
733
760
  // Freeze a still-running tool's duration if it never got a
734
761
  // tool_end (turn ended between steps), so "Elapsed" stops
735
762
  // ticking and shows the final "Took".
@@ -804,15 +831,35 @@ export class WhereverClient {
804
831
  }
805
832
  case 'tool_end': {
806
833
  const result = msg.result ? `${msg.result}` : '';
834
+ // An abort (e.g. the web "abort" button killed the tool mid-run) surfaces
835
+ // as isError with a trailing "...aborted" status. That is not a tool
836
+ // FAILURE, so render it as the neutral interrupted state, not a red
837
+ // error.
838
+ const aborted = !!msg.isError && this.isAbortedToolResult(result);
839
+ const effectiveIsError = !!msg.isError && !aborted;
840
+ const toolImages = Array.isArray(msg.images) && msg.images.length > 0
841
+ ? msg.images
842
+ : undefined;
807
843
  this.stateStore.update((s) => {
808
- const toolMsg = [...s.messages]
809
- .reverse()
810
- .find((m) => m.role === 'tool' &&
844
+ // Claim the OLDEST still-streaming tool of this name (FIFO). Parallel
845
+ // tool calls share a name, so matching the LAST one (or any already
846
+ // finalized one) would let two tool_end frames land on the SAME
847
+ // message and leave the other tool stuck streaming: it would then be
848
+ // finalized by the 'aborted'/agent_end sweep with no result and render
849
+ // as a bogus green success. Preferring a streaming message means each
850
+ // tool_end settles a distinct in-flight call. Fall back to the newest
851
+ // non-error tool of this name only if none are still streaming.
852
+ const toolMsg = s.messages.find((m) => m.role === 'tool' &&
811
853
  m.toolName === msg.toolName &&
812
- !m.content.startsWith('Tool error:'));
854
+ m.isStreaming) ??
855
+ [...s.messages]
856
+ .reverse()
857
+ .find((m) => m.role === 'tool' &&
858
+ m.toolName === msg.toolName &&
859
+ !m.content.startsWith('Tool error:'));
813
860
  const endedAt = Date.now();
814
861
  if (toolMsg) {
815
- const errorPrefix = msg.isError ? 'Error: ' : '';
862
+ const errorPrefix = effectiveIsError ? 'Error: ' : '';
816
863
  return {
817
864
  ...s,
818
865
  messages: s.messages.map((m) => m.id === toolMsg.id
@@ -820,15 +867,17 @@ export class WhereverClient {
820
867
  ...m,
821
868
  content: `${errorPrefix}${m.content}\n${result}`,
822
869
  isStreaming: false,
823
- isError: msg.isError,
870
+ isError: effectiveIsError,
871
+ interrupted: aborted,
824
872
  toolOutput: result,
873
+ ...(toolImages ? { images: toolImages } : {}),
825
874
  endedAt,
826
875
  }
827
876
  : m),
828
877
  };
829
878
  }
830
879
  else {
831
- const content = msg.isError
880
+ const content = effectiveIsError
832
881
  ? `Tool error: ${msg.toolName}\n${result}`
833
882
  : `${msg.toolName}\n${result}`;
834
883
  const message = {
@@ -840,7 +889,9 @@ export class WhereverClient {
840
889
  toolName: msg.toolName,
841
890
  toolArgs: '',
842
891
  toolOutput: result,
843
- isError: msg.isError,
892
+ ...(toolImages ? { images: toolImages } : {}),
893
+ isError: effectiveIsError,
894
+ interrupted: aborted,
844
895
  endedAt,
845
896
  };
846
897
  return {
@@ -860,6 +911,11 @@ export class WhereverClient {
860
911
  ? {
861
912
  ...m,
862
913
  isStreaming: false,
914
+ // A tool still streaming when the turn is aborted was killed
915
+ // with no result: mark it interrupted (neutral), never leave
916
+ // it to fall through to a green success tick. Assistant/
917
+ // thinking messages just stop streaming.
918
+ ...(m.role === 'tool' ? { interrupted: true } : {}),
863
919
  endedAt: m.role === 'tool' && m.endedAt === undefined
864
920
  ? abortedAt
865
921
  : m.endedAt,
@@ -914,6 +970,17 @@ export class WhereverClient {
914
970
  contextUsage: msg.contextUsage ?? null,
915
971
  }));
916
972
  break;
973
+ case 'session_notice':
974
+ // A non-fatal notice for the active session (e.g. a CLI took over while
975
+ // this session was mid-turn here, discarding the in-flight tool call or
976
+ // streaming reply). Keep the session attached; surface it as a
977
+ // dismissible banner. Ignore a notice for a session we switched away from.
978
+ this.stateStore.update((s) => {
979
+ if (s.sessionId && msg.sessionId && s.sessionId !== msg.sessionId)
980
+ return s;
981
+ return { ...s, notice: { level: msg.level, message: msg.message } };
982
+ });
983
+ break;
917
984
  case 'session_destroyed':
918
985
  this.stateStore.update((s) => {
919
986
  if (s.sessionId === msg.sessionId) {
@@ -927,6 +994,7 @@ export class WhereverClient {
927
994
  activeModel: null,
928
995
  loadingSession: false,
929
996
  agentPending: false,
997
+ notice: null,
930
998
  };
931
999
  }
932
1000
  return s;
@@ -974,6 +1042,7 @@ export class WhereverClient {
974
1042
  creatingSession: false,
975
1043
  loadingSession: false,
976
1044
  agentPending: false,
1045
+ notice: null,
977
1046
  }));
978
1047
  break;
979
1048
  case 'message_history': {
@@ -1049,6 +1118,24 @@ export class WhereverClient {
1049
1118
  break;
1050
1119
  }
1051
1120
  }
1121
+ /**
1122
+ * True when an errored tool result is the product of a USER ABORT (e.g. the
1123
+ * web "abort" button killed a running tool), rather than a genuine tool
1124
+ * failure. The pi tools append a trailing status line on abort ("Command
1125
+ * aborted" for bash, "Operation aborted" for edit/write, bare "aborted" for a
1126
+ * pre-execution abort). We match that trailing status so the UI can render a
1127
+ * neutral "interrupted" state instead of a red error: you cancelling a tool is
1128
+ * not the tool failing. Only meaningful when isError is already true; matched
1129
+ * as the LAST non-empty line to avoid false positives from command output that
1130
+ * merely contains the word "aborted".
1131
+ */
1132
+ isAbortedToolResult(result) {
1133
+ if (!result)
1134
+ return false;
1135
+ const lines = result.trimEnd().split('\n');
1136
+ const last = (lines[lines.length - 1] || '').trim();
1137
+ return /^(command|operation)?\s*aborted$/i.test(last);
1138
+ }
1052
1139
  /**
1053
1140
  * Map a server `HistoryMessage[]` window into UI `ChatMessage[]`. When
1054
1141
  * `applyStreamingTail` is true, the last assistant/thinking message and any
@@ -1057,48 +1144,134 @@ export class WhereverClient {
1057
1144
  */
1058
1145
  mapHistory(rawMessages, sessionId, applyStreamingTail) {
1059
1146
  const mapped = [];
1060
- // Each pending tool_call carries its args AND its start timestamp (the ts of
1061
- // the toolCall entry). When the matching tool_result arrives, startedAt =
1062
- // the call ts and endedAt = the result ts, so a tool reconstructed from
1063
- // loaded history shows the same "Took N.Ns" as a live-streamed one.
1064
- const pendingCalls = {};
1147
+ // A tool_call is rendered IN PLACE, at its position in the stream, as a tool
1148
+ // message that is initially result-less. Its matching tool_result fills it
1149
+ // in later. We track the still-open calls per tool name as indices into
1150
+ // `mapped`, so a call that never receives a result simply stays where it was
1151
+ // issued (correctly marked interrupted below) instead of being hoisted to
1152
+ // the very end of the transcript. The end-hoisting was the bug: dangling
1153
+ // tool calls from EARLIER in the conversation (e.g. an interrupted long-
1154
+ // running bash, later superseded by a new user turn) would all pile up as a
1155
+ // "series of aborted tool calls" AFTER the latest reply, even though the CLI
1156
+ // shows them inline where they happened.
1157
+ //
1158
+ // Matching is by tool-call id when present (the server forwards it on both
1159
+ // tool_call and tool_result), which pairs a result to its EXACT call even
1160
+ // when same-named calls interleave with some left dangling. When the id is
1161
+ // absent (older sessions, or the synthesized bashExecution pair) we fall
1162
+ // back to oldest-open-first per tool name.
1163
+ const openCalls = {};
1164
+ const openById = {};
1165
+ // Drop a resolved call's index from the name-FIFO list so an id match and a
1166
+ // later name-fallback can never both consume the same call.
1167
+ const removeFromNameQueue = (tName, idx) => {
1168
+ const q = openCalls[tName];
1169
+ if (!q)
1170
+ return;
1171
+ const at = q.indexOf(idx);
1172
+ if (at !== -1)
1173
+ q.splice(at, 1);
1174
+ };
1065
1175
  for (const m of rawMessages) {
1066
1176
  if (m.role === 'tool_call') {
1067
1177
  const tName = m.toolName || 'unknown';
1068
- if (!pendingCalls[tName]) {
1069
- pendingCalls[tName] = [];
1070
- }
1071
- pendingCalls[tName].push({ args: m.content || '', startedAt: m.timestamp });
1072
- }
1073
- else if (m.role === 'tool_result') {
1074
- const tName = m.toolName || 'unknown';
1075
- const call = pendingCalls[tName] && pendingCalls[tName].length > 0
1076
- ? pendingCalls[tName].shift()
1077
- : undefined;
1078
- const tArgs = call?.args ?? '';
1178
+ const args = m.content || '';
1179
+ const idx = mapped.length;
1079
1180
  mapped.push({
1080
1181
  id: this.generateId(),
1081
1182
  role: 'tool',
1082
- content: tArgs
1083
- ? `$ ${tName} ${tArgs}\n${m.content}`
1084
- : `$ ${tName}\n${m.content}`,
1183
+ content: args ? `$ ${tName} ${args}` : `$ ${tName}`,
1085
1184
  timestamp: m.timestamp,
1185
+ // No result yet. Marked as interrupted below if it stays unmatched;
1186
+ // the streaming tail promotes the last one back to streaming.
1086
1187
  isStreaming: false,
1087
1188
  toolName: tName,
1088
- toolArgs: tArgs,
1089
- toolOutput: m.content,
1090
- isError: m.isError,
1189
+ toolArgs: args,
1190
+ toolOutput: '',
1091
1191
  sessionId,
1092
- // Duration from the matched call. Only when both timestamps are
1093
- // finite and coherent (end >= start); otherwise leave unset so the UI
1094
- // simply shows no duration rather than a bogus one.
1095
- ...(call &&
1096
- Number.isFinite(call.startedAt) &&
1097
- Number.isFinite(m.timestamp) &&
1098
- m.timestamp >= call.startedAt
1099
- ? { startedAt: call.startedAt, endedAt: m.timestamp }
1100
- : {}),
1192
+ // Keep the start so a matched result (or a still-running streaming
1193
+ // tail) can show a coherent duration / "Elapsed".
1194
+ ...(Number.isFinite(m.timestamp) ? { startedAt: m.timestamp } : {}),
1101
1195
  });
1196
+ if (!openCalls[tName])
1197
+ openCalls[tName] = [];
1198
+ openCalls[tName].push(idx);
1199
+ if (typeof m.toolCallId === 'string' && m.toolCallId) {
1200
+ openById[m.toolCallId] = idx;
1201
+ }
1202
+ }
1203
+ else if (m.role === 'tool_result') {
1204
+ const tName = m.toolName || 'unknown';
1205
+ // Prefer an exact id match; else fill the OLDEST still-open call of this
1206
+ // name (FIFO), mirroring how parallel same-named calls resolve in order.
1207
+ let callIdx;
1208
+ if (typeof m.toolCallId === 'string' &&
1209
+ m.toolCallId &&
1210
+ openById[m.toolCallId] !== undefined) {
1211
+ callIdx = openById[m.toolCallId];
1212
+ delete openById[m.toolCallId];
1213
+ removeFromNameQueue(tName, callIdx);
1214
+ }
1215
+ else if (openCalls[tName] && openCalls[tName].length > 0) {
1216
+ callIdx = openCalls[tName].shift();
1217
+ // Keep openById consistent if this call had also registered an id.
1218
+ for (const [id, i] of Object.entries(openById)) {
1219
+ if (i === callIdx)
1220
+ delete openById[id];
1221
+ }
1222
+ }
1223
+ const isError = m.isError && !this.isAbortedToolResult(m.content);
1224
+ const interrupted = !!m.isError && this.isAbortedToolResult(m.content);
1225
+ if (callIdx !== undefined) {
1226
+ const call = mapped[callIdx];
1227
+ const tArgs = call.toolArgs || '';
1228
+ const startedAt = call.startedAt;
1229
+ mapped[callIdx] = {
1230
+ ...call,
1231
+ content: tArgs
1232
+ ? `$ ${tName} ${tArgs}\n${m.content}`
1233
+ : `$ ${tName}\n${m.content}`,
1234
+ isStreaming: false,
1235
+ toolOutput: m.content,
1236
+ ...(Array.isArray(m.images) && m.images.length > 0
1237
+ ? { images: m.images }
1238
+ : {}),
1239
+ // A user abort surfaces as an errored result with a trailing
1240
+ // "...aborted" status. Render it as interrupted (neutral), not a red
1241
+ // error: aborting a tool is not the tool failing.
1242
+ isError,
1243
+ interrupted,
1244
+ timestamp: m.timestamp,
1245
+ // Duration only when both timestamps are finite and coherent
1246
+ // (end >= start); otherwise leave unset rather than show a bogus one.
1247
+ ...(startedAt !== undefined &&
1248
+ Number.isFinite(startedAt) &&
1249
+ Number.isFinite(m.timestamp) &&
1250
+ m.timestamp >= startedAt
1251
+ ? { endedAt: m.timestamp }
1252
+ : {}),
1253
+ };
1254
+ }
1255
+ else {
1256
+ // A result with no preceding open call (shouldn't normally happen).
1257
+ // Render it in place as a standalone tool message so nothing is lost.
1258
+ mapped.push({
1259
+ id: this.generateId(),
1260
+ role: 'tool',
1261
+ content: `$ ${tName}\n${m.content}`,
1262
+ timestamp: m.timestamp,
1263
+ isStreaming: false,
1264
+ toolName: tName,
1265
+ toolArgs: '',
1266
+ toolOutput: m.content,
1267
+ ...(Array.isArray(m.images) && m.images.length > 0
1268
+ ? { images: m.images }
1269
+ : {}),
1270
+ isError,
1271
+ interrupted,
1272
+ sessionId,
1273
+ });
1274
+ }
1102
1275
  }
1103
1276
  else {
1104
1277
  mapped.push({
@@ -1112,26 +1285,28 @@ export class WhereverClient {
1112
1285
  });
1113
1286
  }
1114
1287
  }
1115
- for (const [tName, calls] of Object.entries(pendingCalls)) {
1116
- for (const call of calls) {
1117
- mapped.push({
1118
- id: this.generateId(),
1119
- role: 'tool',
1120
- content: call.args ? `$ ${tName} ${call.args}` : `$ ${tName}`,
1121
- timestamp: mapped.length > 0
1122
- ? mapped[mapped.length - 1].timestamp + 1
1123
- : Date.now(),
1124
- isStreaming: applyStreamingTail,
1125
- toolName: tName,
1126
- toolArgs: call.args,
1127
- toolOutput: '',
1128
- sessionId,
1129
- // An unmatched call (no result yet). Keep its start so a still-running
1130
- // tool in the streaming tail can tick "Elapsed"; leave endedAt unset.
1131
- ...(Number.isFinite(call.startedAt)
1132
- ? { startedAt: call.startedAt }
1133
- : {}),
1134
- });
1288
+ // Any call still open (issued a toolCall, never got a tool_result) is FROZEN
1289
+ // in place with no result. Meaning depends on context:
1290
+ // - streaming tail (applyStreamingTail): only the MOST RECENT open call is
1291
+ // plausibly still running; keep it streaming so the UI ticks "Elapsed".
1292
+ // Earlier open calls in the same window are already superseded and are
1293
+ // interrupted.
1294
+ // - otherwise: its outcome is unknown (e.g. a CLI takeover / interruption
1295
+ // killed it mid-run), so mark it `interrupted` for a neutral "no result"
1296
+ // state instead of a bogus green success tick.
1297
+ const allOpen = [];
1298
+ for (const idxs of Object.values(openCalls))
1299
+ allOpen.push(...idxs);
1300
+ allOpen.sort((a, b) => a - b);
1301
+ const lastOpenIdx = applyStreamingTail && allOpen.length > 0
1302
+ ? allOpen[allOpen.length - 1]
1303
+ : -1;
1304
+ for (const idx of allOpen) {
1305
+ if (idx === lastOpenIdx) {
1306
+ mapped[idx] = { ...mapped[idx], isStreaming: true };
1307
+ }
1308
+ else {
1309
+ mapped[idx] = { ...mapped[idx], interrupted: true };
1135
1310
  }
1136
1311
  }
1137
1312
  if (applyStreamingTail && mapped.length > 0) {
@@ -1466,6 +1641,7 @@ export class WhereverClient {
1466
1641
  readOnly: false,
1467
1642
  conflict: null,
1468
1643
  sessionError: null,
1644
+ notice: null,
1469
1645
  creatingSession: false,
1470
1646
  resyncing: false,
1471
1647
  agentPending: false,
@@ -1525,6 +1701,7 @@ export class WhereverClient {
1525
1701
  activeCwd: null,
1526
1702
  activeModel: null,
1527
1703
  readOnly: false,
1704
+ notice: null,
1528
1705
  creatingSession: false,
1529
1706
  loadingSession: false,
1530
1707
  resyncing: false,
@@ -1561,6 +1738,9 @@ export class WhereverClient {
1561
1738
  dismissSessionError() {
1562
1739
  this.stateStore.update((s) => ({ ...s, sessionError: null }));
1563
1740
  }
1741
+ dismissNotice() {
1742
+ this.stateStore.update((s) => ({ ...s, notice: null }));
1743
+ }
1564
1744
  changeModel(model) {
1565
1745
  this.send({ type: 'model_change', model });
1566
1746
  }