@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/src/client.ts CHANGED
@@ -26,6 +26,7 @@ const defaultState: WhereverState = {
26
26
  clientId: null,
27
27
  conflict: null,
28
28
  isInterrupted: false,
29
+ notice: null,
29
30
  sessionError: null,
30
31
  readOnly: false,
31
32
  activeSessionFile: null,
@@ -308,11 +309,28 @@ export class WhereverClient {
308
309
  this.clearCreateWatchdog();
309
310
 
310
311
  if (this.ws) {
312
+ const dyingWs = this.ws as any;
311
313
  try {
312
- if (typeof this.ws.removeAllListeners === 'function') {
313
- this.ws.removeAllListeners();
314
+ if (typeof dyingWs.removeAllListeners === 'function') {
315
+ dyingWs.removeAllListeners();
314
316
  }
315
- this.ws.close();
317
+ // Closing a socket that is still CONNECTING (e.g. the wherever server is
318
+ // not running so the handshake never completed) makes `ws` abort the
319
+ // handshake and emit an 'error' asynchronously on the next tick. With
320
+ // every listener removed, that 'error' would be an unhandled
321
+ // EventEmitter error and crash the whole process as an
322
+ // uncaughtException. Keep a no-op error sink on the socket we are
323
+ // tearing down so the late error is swallowed, in both the node (`ws`)
324
+ // and browser (`WebSocket`) environments.
325
+ const swallow = () => {};
326
+ if (typeof dyingWs.on === 'function') {
327
+ dyingWs.on('error', swallow);
328
+ } else if (typeof dyingWs.addEventListener === 'function') {
329
+ dyingWs.addEventListener('error', swallow);
330
+ } else {
331
+ dyingWs.onerror = swallow;
332
+ }
333
+ dyingWs.close();
316
334
  } catch (err) {}
317
335
  this.ws = null;
318
336
  }
@@ -790,6 +808,13 @@ export class WhereverClient {
790
808
  ? {
791
809
  ...m,
792
810
  isStreaming: false,
811
+ // A tool still streaming when the turn ends never got a
812
+ // tool_end (e.g. the turn was aborted, or its result frame
813
+ // was lost): its outcome is unknown. Mark it interrupted
814
+ // (neutral), never let it fall through to a green success
815
+ // tick, which would falsely claim it succeeded. Assistant/
816
+ // thinking messages just stop streaming.
817
+ ...(m.role === 'tool' ? {interrupted: true} : {}),
793
818
  // Freeze a still-running tool's duration if it never got a
794
819
  // tool_end (turn ended between steps), so "Elapsed" stops
795
820
  // ticking and shows the final "Took".
@@ -876,18 +901,43 @@ export class WhereverClient {
876
901
 
877
902
  case 'tool_end': {
878
903
  const result = msg.result ? `${msg.result}` : '';
904
+ // An abort (e.g. the web "abort" button killed the tool mid-run) surfaces
905
+ // as isError with a trailing "...aborted" status. That is not a tool
906
+ // FAILURE, so render it as the neutral interrupted state, not a red
907
+ // error.
908
+ const aborted = !!msg.isError && this.isAbortedToolResult(result);
909
+ const effectiveIsError = !!msg.isError && !aborted;
910
+ const toolImages =
911
+ Array.isArray(msg.images) && msg.images.length > 0
912
+ ? msg.images
913
+ : undefined;
879
914
  this.stateStore.update((s: WhereverState) => {
880
- const toolMsg = [...s.messages]
881
- .reverse()
882
- .find(
915
+ // Claim the OLDEST still-streaming tool of this name (FIFO). Parallel
916
+ // tool calls share a name, so matching the LAST one (or any already
917
+ // finalized one) would let two tool_end frames land on the SAME
918
+ // message and leave the other tool stuck streaming: it would then be
919
+ // finalized by the 'aborted'/agent_end sweep with no result and render
920
+ // as a bogus green success. Preferring a streaming message means each
921
+ // tool_end settles a distinct in-flight call. Fall back to the newest
922
+ // non-error tool of this name only if none are still streaming.
923
+ const toolMsg =
924
+ s.messages.find(
883
925
  (m: ChatMessage) =>
884
926
  m.role === 'tool' &&
885
927
  m.toolName === msg.toolName &&
886
- !m.content.startsWith('Tool error:'),
887
- );
928
+ m.isStreaming,
929
+ ) ??
930
+ [...s.messages]
931
+ .reverse()
932
+ .find(
933
+ (m: ChatMessage) =>
934
+ m.role === 'tool' &&
935
+ m.toolName === msg.toolName &&
936
+ !m.content.startsWith('Tool error:'),
937
+ );
888
938
  const endedAt = Date.now();
889
939
  if (toolMsg) {
890
- const errorPrefix = msg.isError ? 'Error: ' : '';
940
+ const errorPrefix = effectiveIsError ? 'Error: ' : '';
891
941
  return {
892
942
  ...s,
893
943
  messages: s.messages.map((m: ChatMessage) =>
@@ -896,15 +946,17 @@ export class WhereverClient {
896
946
  ...m,
897
947
  content: `${errorPrefix}${m.content}\n${result}`,
898
948
  isStreaming: false,
899
- isError: msg.isError,
949
+ isError: effectiveIsError,
950
+ interrupted: aborted,
900
951
  toolOutput: result,
952
+ ...(toolImages ? {images: toolImages} : {}),
901
953
  endedAt,
902
954
  }
903
955
  : m,
904
956
  ),
905
957
  };
906
958
  } else {
907
- const content = msg.isError
959
+ const content = effectiveIsError
908
960
  ? `Tool error: ${msg.toolName}\n${result}`
909
961
  : `${msg.toolName}\n${result}`;
910
962
  const message: ChatMessage = {
@@ -916,7 +968,9 @@ export class WhereverClient {
916
968
  toolName: msg.toolName,
917
969
  toolArgs: '',
918
970
  toolOutput: result,
919
- isError: msg.isError,
971
+ ...(toolImages ? {images: toolImages} : {}),
972
+ isError: effectiveIsError,
973
+ interrupted: aborted,
920
974
  endedAt,
921
975
  };
922
976
  return {
@@ -938,6 +992,11 @@ export class WhereverClient {
938
992
  ? {
939
993
  ...m,
940
994
  isStreaming: false,
995
+ // A tool still streaming when the turn is aborted was killed
996
+ // with no result: mark it interrupted (neutral), never leave
997
+ // it to fall through to a green success tick. Assistant/
998
+ // thinking messages just stop streaming.
999
+ ...(m.role === 'tool' ? {interrupted: true} : {}),
941
1000
  endedAt:
942
1001
  m.role === 'tool' && m.endedAt === undefined
943
1002
  ? abortedAt
@@ -998,6 +1057,17 @@ export class WhereverClient {
998
1057
  }));
999
1058
  break;
1000
1059
 
1060
+ case 'session_notice':
1061
+ // A non-fatal notice for the active session (e.g. a CLI took over while
1062
+ // this session was mid-turn here, discarding the in-flight tool call or
1063
+ // streaming reply). Keep the session attached; surface it as a
1064
+ // dismissible banner. Ignore a notice for a session we switched away from.
1065
+ this.stateStore.update((s: WhereverState) => {
1066
+ if (s.sessionId && msg.sessionId && s.sessionId !== msg.sessionId) return s;
1067
+ return { ...s, notice: { level: msg.level, message: msg.message } };
1068
+ });
1069
+ break;
1070
+
1001
1071
  case 'session_destroyed':
1002
1072
  this.stateStore.update((s: WhereverState) => {
1003
1073
  if (s.sessionId === msg.sessionId) {
@@ -1011,6 +1081,7 @@ export class WhereverClient {
1011
1081
  activeModel: null,
1012
1082
  loadingSession: false,
1013
1083
  agentPending: false,
1084
+ notice: null,
1014
1085
  };
1015
1086
  }
1016
1087
  return s;
@@ -1061,6 +1132,7 @@ export class WhereverClient {
1061
1132
  creatingSession: false,
1062
1133
  loadingSession: false,
1063
1134
  agentPending: false,
1135
+ notice: null,
1064
1136
  }));
1065
1137
  break;
1066
1138
 
@@ -1142,6 +1214,24 @@ export class WhereverClient {
1142
1214
  }
1143
1215
  }
1144
1216
 
1217
+ /**
1218
+ * True when an errored tool result is the product of a USER ABORT (e.g. the
1219
+ * web "abort" button killed a running tool), rather than a genuine tool
1220
+ * failure. The pi tools append a trailing status line on abort ("Command
1221
+ * aborted" for bash, "Operation aborted" for edit/write, bare "aborted" for a
1222
+ * pre-execution abort). We match that trailing status so the UI can render a
1223
+ * neutral "interrupted" state instead of a red error: you cancelling a tool is
1224
+ * not the tool failing. Only meaningful when isError is already true; matched
1225
+ * as the LAST non-empty line to avoid false positives from command output that
1226
+ * merely contains the word "aborted".
1227
+ */
1228
+ private isAbortedToolResult(result: string | undefined): boolean {
1229
+ if (!result) return false;
1230
+ const lines = result.trimEnd().split('\n');
1231
+ const last = (lines[lines.length - 1] || '').trim();
1232
+ return /^(command|operation)?\s*aborted$/i.test(last);
1233
+ }
1234
+
1145
1235
  /**
1146
1236
  * Map a server `HistoryMessage[]` window into UI `ChatMessage[]`. When
1147
1237
  * `applyStreamingTail` is true, the last assistant/thinking message and any
@@ -1154,49 +1244,131 @@ export class WhereverClient {
1154
1244
  applyStreamingTail: boolean,
1155
1245
  ): ChatMessage[] {
1156
1246
  const mapped: ChatMessage[] = [];
1157
- // Each pending tool_call carries its args AND its start timestamp (the ts of
1158
- // the toolCall entry). When the matching tool_result arrives, startedAt =
1159
- // the call ts and endedAt = the result ts, so a tool reconstructed from
1160
- // loaded history shows the same "Took N.Ns" as a live-streamed one.
1161
- const pendingCalls: Record<string, {args: string; startedAt: number}[]> = {};
1247
+ // A tool_call is rendered IN PLACE, at its position in the stream, as a tool
1248
+ // message that is initially result-less. Its matching tool_result fills it
1249
+ // in later. We track the still-open calls per tool name as indices into
1250
+ // `mapped`, so a call that never receives a result simply stays where it was
1251
+ // issued (correctly marked interrupted below) instead of being hoisted to
1252
+ // the very end of the transcript. The end-hoisting was the bug: dangling
1253
+ // tool calls from EARLIER in the conversation (e.g. an interrupted long-
1254
+ // running bash, later superseded by a new user turn) would all pile up as a
1255
+ // "series of aborted tool calls" AFTER the latest reply, even though the CLI
1256
+ // shows them inline where they happened.
1257
+ //
1258
+ // Matching is by tool-call id when present (the server forwards it on both
1259
+ // tool_call and tool_result), which pairs a result to its EXACT call even
1260
+ // when same-named calls interleave with some left dangling. When the id is
1261
+ // absent (older sessions, or the synthesized bashExecution pair) we fall
1262
+ // back to oldest-open-first per tool name.
1263
+ const openCalls: Record<string, number[]> = {};
1264
+ const openById: Record<string, number> = {};
1265
+
1266
+ // Drop a resolved call's index from the name-FIFO list so an id match and a
1267
+ // later name-fallback can never both consume the same call.
1268
+ const removeFromNameQueue = (tName: string, idx: number) => {
1269
+ const q = openCalls[tName];
1270
+ if (!q) return;
1271
+ const at = q.indexOf(idx);
1272
+ if (at !== -1) q.splice(at, 1);
1273
+ };
1162
1274
 
1163
1275
  for (const m of rawMessages) {
1164
1276
  if (m.role === 'tool_call') {
1165
1277
  const tName = m.toolName || 'unknown';
1166
- if (!pendingCalls[tName]) {
1167
- pendingCalls[tName] = [];
1168
- }
1169
- pendingCalls[tName].push({args: m.content || '', startedAt: m.timestamp});
1170
- } else if (m.role === 'tool_result') {
1171
- const tName = m.toolName || 'unknown';
1172
- const call =
1173
- pendingCalls[tName] && pendingCalls[tName].length > 0
1174
- ? pendingCalls[tName].shift()!
1175
- : undefined;
1176
- const tArgs = call?.args ?? '';
1278
+ const args = m.content || '';
1279
+ const idx = mapped.length;
1177
1280
  mapped.push({
1178
1281
  id: this.generateId(),
1179
1282
  role: 'tool',
1180
- content: tArgs
1181
- ? `$ ${tName} ${tArgs}\n${m.content}`
1182
- : `$ ${tName}\n${m.content}`,
1283
+ content: args ? `$ ${tName} ${args}` : `$ ${tName}`,
1183
1284
  timestamp: m.timestamp,
1285
+ // No result yet. Marked as interrupted below if it stays unmatched;
1286
+ // the streaming tail promotes the last one back to streaming.
1184
1287
  isStreaming: false,
1185
1288
  toolName: tName,
1186
- toolArgs: tArgs,
1187
- toolOutput: m.content,
1188
- isError: m.isError,
1289
+ toolArgs: args,
1290
+ toolOutput: '',
1189
1291
  sessionId,
1190
- // Duration from the matched call. Only when both timestamps are
1191
- // finite and coherent (end >= start); otherwise leave unset so the UI
1192
- // simply shows no duration rather than a bogus one.
1193
- ...(call &&
1194
- Number.isFinite(call.startedAt) &&
1195
- Number.isFinite(m.timestamp) &&
1196
- m.timestamp >= call.startedAt
1197
- ? {startedAt: call.startedAt, endedAt: m.timestamp}
1198
- : {}),
1292
+ // Keep the start so a matched result (or a still-running streaming
1293
+ // tail) can show a coherent duration / "Elapsed".
1294
+ ...(Number.isFinite(m.timestamp) ? {startedAt: m.timestamp} : {}),
1199
1295
  });
1296
+ if (!openCalls[tName]) openCalls[tName] = [];
1297
+ openCalls[tName].push(idx);
1298
+ if (typeof m.toolCallId === 'string' && m.toolCallId) {
1299
+ openById[m.toolCallId] = idx;
1300
+ }
1301
+ } else if (m.role === 'tool_result') {
1302
+ const tName = m.toolName || 'unknown';
1303
+ // Prefer an exact id match; else fill the OLDEST still-open call of this
1304
+ // name (FIFO), mirroring how parallel same-named calls resolve in order.
1305
+ let callIdx: number | undefined;
1306
+ if (
1307
+ typeof m.toolCallId === 'string' &&
1308
+ m.toolCallId &&
1309
+ openById[m.toolCallId] !== undefined
1310
+ ) {
1311
+ callIdx = openById[m.toolCallId];
1312
+ delete openById[m.toolCallId];
1313
+ removeFromNameQueue(tName, callIdx);
1314
+ } else if (openCalls[tName] && openCalls[tName].length > 0) {
1315
+ callIdx = openCalls[tName].shift()!;
1316
+ // Keep openById consistent if this call had also registered an id.
1317
+ for (const [id, i] of Object.entries(openById)) {
1318
+ if (i === callIdx) delete openById[id];
1319
+ }
1320
+ }
1321
+ const isError = m.isError && !this.isAbortedToolResult(m.content);
1322
+ const interrupted = !!m.isError && this.isAbortedToolResult(m.content);
1323
+ if (callIdx !== undefined) {
1324
+ const call = mapped[callIdx];
1325
+ const tArgs = call.toolArgs || '';
1326
+ const startedAt = call.startedAt;
1327
+ mapped[callIdx] = {
1328
+ ...call,
1329
+ content: tArgs
1330
+ ? `$ ${tName} ${tArgs}\n${m.content}`
1331
+ : `$ ${tName}\n${m.content}`,
1332
+ isStreaming: false,
1333
+ toolOutput: m.content,
1334
+ ...(Array.isArray(m.images) && m.images.length > 0
1335
+ ? {images: m.images}
1336
+ : {}),
1337
+ // A user abort surfaces as an errored result with a trailing
1338
+ // "...aborted" status. Render it as interrupted (neutral), not a red
1339
+ // error: aborting a tool is not the tool failing.
1340
+ isError,
1341
+ interrupted,
1342
+ timestamp: m.timestamp,
1343
+ // Duration only when both timestamps are finite and coherent
1344
+ // (end >= start); otherwise leave unset rather than show a bogus one.
1345
+ ...(startedAt !== undefined &&
1346
+ Number.isFinite(startedAt) &&
1347
+ Number.isFinite(m.timestamp) &&
1348
+ m.timestamp >= startedAt
1349
+ ? {endedAt: m.timestamp}
1350
+ : {}),
1351
+ };
1352
+ } else {
1353
+ // A result with no preceding open call (shouldn't normally happen).
1354
+ // Render it in place as a standalone tool message so nothing is lost.
1355
+ mapped.push({
1356
+ id: this.generateId(),
1357
+ role: 'tool',
1358
+ content: `$ ${tName}\n${m.content}`,
1359
+ timestamp: m.timestamp,
1360
+ isStreaming: false,
1361
+ toolName: tName,
1362
+ toolArgs: '',
1363
+ toolOutput: m.content,
1364
+ ...(Array.isArray(m.images) && m.images.length > 0
1365
+ ? {images: m.images}
1366
+ : {}),
1367
+ isError,
1368
+ interrupted,
1369
+ sessionId,
1370
+ });
1371
+ }
1200
1372
  } else {
1201
1373
  mapped.push({
1202
1374
  id: this.generateId(),
@@ -1210,27 +1382,27 @@ export class WhereverClient {
1210
1382
  }
1211
1383
  }
1212
1384
 
1213
- for (const [tName, calls] of Object.entries(pendingCalls)) {
1214
- for (const call of calls) {
1215
- mapped.push({
1216
- id: this.generateId(),
1217
- role: 'tool',
1218
- content: call.args ? `$ ${tName} ${call.args}` : `$ ${tName}`,
1219
- timestamp:
1220
- mapped.length > 0
1221
- ? mapped[mapped.length - 1].timestamp + 1
1222
- : Date.now(),
1223
- isStreaming: applyStreamingTail,
1224
- toolName: tName,
1225
- toolArgs: call.args,
1226
- toolOutput: '',
1227
- sessionId,
1228
- // An unmatched call (no result yet). Keep its start so a still-running
1229
- // tool in the streaming tail can tick "Elapsed"; leave endedAt unset.
1230
- ...(Number.isFinite(call.startedAt)
1231
- ? {startedAt: call.startedAt}
1232
- : {}),
1233
- });
1385
+ // Any call still open (issued a toolCall, never got a tool_result) is FROZEN
1386
+ // in place with no result. Meaning depends on context:
1387
+ // - streaming tail (applyStreamingTail): only the MOST RECENT open call is
1388
+ // plausibly still running; keep it streaming so the UI ticks "Elapsed".
1389
+ // Earlier open calls in the same window are already superseded and are
1390
+ // interrupted.
1391
+ // - otherwise: its outcome is unknown (e.g. a CLI takeover / interruption
1392
+ // killed it mid-run), so mark it `interrupted` for a neutral "no result"
1393
+ // state instead of a bogus green success tick.
1394
+ const allOpen: number[] = [];
1395
+ for (const idxs of Object.values(openCalls)) allOpen.push(...idxs);
1396
+ allOpen.sort((a, b) => a - b);
1397
+ const lastOpenIdx =
1398
+ applyStreamingTail && allOpen.length > 0
1399
+ ? allOpen[allOpen.length - 1]
1400
+ : -1;
1401
+ for (const idx of allOpen) {
1402
+ if (idx === lastOpenIdx) {
1403
+ mapped[idx] = {...mapped[idx], isStreaming: true};
1404
+ } else {
1405
+ mapped[idx] = {...mapped[idx], interrupted: true};
1234
1406
  }
1235
1407
  }
1236
1408
 
@@ -1583,6 +1755,7 @@ export class WhereverClient {
1583
1755
  readOnly: false,
1584
1756
  conflict: null,
1585
1757
  sessionError: null,
1758
+ notice: null,
1586
1759
  creatingSession: false,
1587
1760
  resyncing: false,
1588
1761
  agentPending: false,
@@ -1650,6 +1823,7 @@ export class WhereverClient {
1650
1823
  activeCwd: null,
1651
1824
  activeModel: null,
1652
1825
  readOnly: false,
1826
+ notice: null,
1653
1827
  creatingSession: false,
1654
1828
  loadingSession: false,
1655
1829
  resyncing: false,
@@ -1692,6 +1866,10 @@ export class WhereverClient {
1692
1866
  this.stateStore.update((s: WhereverState) => ({...s, sessionError: null}));
1693
1867
  }
1694
1868
 
1869
+ public dismissNotice() {
1870
+ this.stateStore.update((s: WhereverState) => ({...s, notice: null}));
1871
+ }
1872
+
1695
1873
  public changeModel(model: string) {
1696
1874
  this.send({type: 'model_change', model});
1697
1875
  }
package/src/types.ts CHANGED
@@ -1,3 +1,8 @@
1
+ export interface ToolImage {
2
+ mimeType: string;
3
+ data: string;
4
+ }
5
+
1
6
  export interface ChatMessage {
2
7
  id: string;
3
8
  role: 'user' | 'assistant' | 'thinking' | 'tool';
@@ -8,7 +13,19 @@ export interface ChatMessage {
8
13
  toolName?: string;
9
14
  toolArgs?: string;
10
15
  toolOutput?: string;
16
+ // Image attachments extracted from a tool result (e.g. `read` on an image
17
+ // file). `data` is base64 (no data-URI prefix); rendered inline in the tool
18
+ // output, mirroring the CLI's inline image display.
19
+ images?: ToolImage[];
11
20
  isError?: boolean;
21
+ // A tool call that ended WITHOUT a result: the assistant issued the toolCall
22
+ // but no toolResult was ever persisted (e.g. a CLI took over the session and
23
+ // the running tool was killed mid-execution). Its outcome is unknown, so the
24
+ // UI must show a distinct "interrupted / no result" state, NOT the green
25
+ // success tick (we do not know if it succeeded or failed) and NOT the red
26
+ // error tick (it was not an error, it just never finished). Only meaningful
27
+ // for role: 'tool'; mutually exclusive with a live isStreaming tool.
28
+ interrupted?: boolean;
12
29
  // Wall-clock start of a tool call (ms epoch), set when the tool_start frame
13
30
  // arrives. `timestamp` also carries this, but startedAt is kept explicit so
14
31
  // the elapsed/took duration is unambiguous and survives content rewrites.
@@ -31,6 +48,11 @@ export interface ChatMessage {
31
48
  delivery?: 'sending' | 'failed';
32
49
  }
33
50
 
51
+ export interface SessionNotice {
52
+ level: 'info' | 'warning';
53
+ message: string;
54
+ }
55
+
34
56
  export interface ConflictInfo {
35
57
  targetSessionId: string;
36
58
  conflictingSessionId: string;
@@ -66,6 +88,12 @@ export interface WhereverState {
66
88
  clientId: string | null;
67
89
  conflict: ConflictInfo | null;
68
90
  isInterrupted: boolean;
91
+ // A dismissible, non-fatal notice about the active session (e.g. a CLI bridge
92
+ // took over while this session was mid-turn here, discarding the in-flight
93
+ // tool call or streaming reply). Rendered as a banner and cleared on dismiss,
94
+ // on leaving the session, or when a fresh notice replaces it. null when there
95
+ // is nothing to show.
96
+ notice: SessionNotice | null;
69
97
  sessionError: string | null;
70
98
  readOnly: boolean;
71
99
  activeSessionFile: string | null;
@@ -0,0 +1,170 @@
1
+ import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
2
+ import {get} from 'sveltore';
3
+ import {WhereverClient} from '../src/client.js';
4
+ import type {WhereverState} from '../src/types.js';
5
+ import {makeWSFactory} from './harness.js';
6
+
7
+ // When a running tool is ABORTED (e.g. the web "abort" button kills it mid-run),
8
+ // pi surfaces it as an errored result with a trailing "...aborted" status. That
9
+ // is NOT a tool failure, so the UI must render a neutral "interrupted" state,
10
+ // not a red error. A tool that genuinely completed (or genuinely failed) before
11
+ // the abort keeps its real success/error state.
12
+
13
+ function setup(ws: ReturnType<typeof makeWSFactory>, isStreaming = true) {
14
+ const client = new WhereverClient({
15
+ host: 'localhost',
16
+ port: 1234,
17
+ secure: false,
18
+ WebSocketCtor: ws.ctor,
19
+ });
20
+ client.connect();
21
+ ws.last().open();
22
+ client.joinSession('/tmp/project/session.jsonl');
23
+ ws.last().receive({
24
+ type: 'session_created',
25
+ sessionId: 'sid-1',
26
+ sessionFile: '/tmp/project/session.jsonl',
27
+ cwd: '/tmp/project',
28
+ model: 'fake:model',
29
+ isStreaming,
30
+ });
31
+ return client;
32
+ }
33
+
34
+ describe('aborted tool call rendering', () => {
35
+ let ws: ReturnType<typeof makeWSFactory>;
36
+ let client: WhereverClient;
37
+ const state = () => get<WhereverState>(client.stateStore);
38
+
39
+ beforeEach(() => {
40
+ vi.useFakeTimers();
41
+ ws = makeWSFactory();
42
+ });
43
+
44
+ afterEach(() => {
45
+ client.disconnect(true);
46
+ vi.useRealTimers();
47
+ });
48
+
49
+ it('live tool_end: an aborted result is interrupted, not an error', () => {
50
+ client = setup(ws);
51
+ ws.last().receive({type: 'tool_start', sessionId: 'sid-1', toolName: 'bash', args: {command: 'sleep 8'}});
52
+ ws.last().receive({
53
+ type: 'tool_end',
54
+ sessionId: 'sid-1',
55
+ toolName: 'bash',
56
+ isError: true,
57
+ result: 'Command aborted',
58
+ });
59
+ const tool = state().messages.find((m) => m.role === 'tool')!;
60
+ expect(tool.interrupted).toBe(true);
61
+ expect(tool.isError).toBe(false);
62
+ });
63
+
64
+ it('live tool_end: a genuine error stays an error', () => {
65
+ client = setup(ws);
66
+ ws.last().receive({type: 'tool_start', sessionId: 'sid-1', toolName: 'bash', args: {command: 'false'}});
67
+ ws.last().receive({
68
+ type: 'tool_end',
69
+ sessionId: 'sid-1',
70
+ toolName: 'bash',
71
+ isError: true,
72
+ result: 'boom\n\nCommand exited with code 1',
73
+ });
74
+ const tool = state().messages.find((m) => m.role === 'tool')!;
75
+ expect(tool.isError).toBe(true);
76
+ expect(tool.interrupted).toBeFalsy();
77
+ });
78
+
79
+ it('live tool_end: a genuine success stays a success', () => {
80
+ client = setup(ws);
81
+ ws.last().receive({type: 'tool_start', sessionId: 'sid-1', toolName: 'bash', args: {command: 'echo quick'}});
82
+ ws.last().receive({
83
+ type: 'tool_end',
84
+ sessionId: 'sid-1',
85
+ toolName: 'bash',
86
+ isError: false,
87
+ result: 'quick',
88
+ });
89
+ const tool = state().messages.find((m) => m.role === 'tool')!;
90
+ expect(tool.isError).toBe(false);
91
+ expect(tool.interrupted).toBeFalsy();
92
+ });
93
+
94
+ it('history: two parallel tools, one completed (green) and one aborted (interrupted)', () => {
95
+ client = setup(ws, false);
96
+ ws.last().receive({
97
+ type: 'message_history',
98
+ sessionId: 'sid-1',
99
+ messages: [
100
+ {role: 'user', content: 'go', timestamp: 1_000},
101
+ {role: 'tool_call', content: '{"command":"echo quick"}', timestamp: 2_000, toolName: 'bash'},
102
+ {role: 'tool_call', content: '{"command":"sleep 8"}', timestamp: 2_001, toolName: 'bash'},
103
+ {role: 'tool_result', content: 'quick', timestamp: 3_000, toolName: 'bash', isError: false},
104
+ {role: 'tool_result', content: 'Command aborted', timestamp: 3_100, toolName: 'bash', isError: true},
105
+ ],
106
+ totalCount: 5,
107
+ offset: 0,
108
+ });
109
+ const tools = state().messages.filter((m) => m.role === 'tool');
110
+ expect(tools.length).toBe(2);
111
+ // FIFO pairing by tool name: first result -> first call (echo, success),
112
+ // second result -> second call (sleep, aborted -> interrupted).
113
+ const succeeded = tools.find((t) => t.toolOutput === 'quick')!;
114
+ const aborted = tools.find((t) => (t.toolOutput || '').includes('aborted'))!;
115
+ expect(succeeded.isError).toBeFalsy();
116
+ expect(succeeded.interrupted).toBeFalsy();
117
+ expect(aborted.isError).toBe(false);
118
+ expect(aborted.interrupted).toBe(true);
119
+ });
120
+
121
+ it('two parallel same-named tools both aborted: BOTH interrupted (no stray green)', () => {
122
+ client = setup(ws);
123
+ // Two parallel bash calls start (same tool name).
124
+ ws.last().receive({type: 'tool_start', sessionId: 'sid-1', toolName: 'bash', args: {command: 'sleep 8'}});
125
+ ws.last().receive({type: 'tool_start', sessionId: 'sid-1', toolName: 'bash', args: {command: 'sleep 8'}});
126
+ // Both settle as aborted. FIFO matching must route each tool_end to a
127
+ // DISTINCT streaming message, so neither is left to be finalized green.
128
+ ws.last().receive({type: 'tool_end', sessionId: 'sid-1', toolName: 'bash', isError: true, result: 'Command aborted'});
129
+ ws.last().receive({type: 'tool_end', sessionId: 'sid-1', toolName: 'bash', isError: true, result: 'Command aborted'});
130
+
131
+ const tools = state().messages.filter((m) => m.role === 'tool');
132
+ expect(tools.length).toBe(2);
133
+ for (const t of tools) {
134
+ expect(t.isStreaming).toBe(false);
135
+ expect(t.interrupted).toBe(true);
136
+ expect(t.isError).toBe(false);
137
+ }
138
+ });
139
+
140
+ it('a tool still streaming at agent_end is interrupted, not a green success', () => {
141
+ client = setup(ws);
142
+ vi.useFakeTimers();
143
+ ws.last().receive({type: 'tool_start', sessionId: 'sid-1', toolName: 'bash', args: {command: 'sleep 8'}});
144
+ // The turn ends WITHOUT a tool_end for this tool (e.g. aborted, or the
145
+ // result frame was lost). agent_end finalizes after a 300ms debounce.
146
+ ws.last().receive({type: 'agent_end', sessionId: 'sid-1'});
147
+ vi.advanceTimersByTime(350);
148
+
149
+ const tool = state().messages.find((m) => m.role === 'tool')!;
150
+ expect(tool.isStreaming).toBe(false);
151
+ expect(tool.interrupted).toBe(true);
152
+ expect(tool.isError).toBeFalsy();
153
+ });
154
+
155
+ it('an "aborted" substring in normal output is NOT treated as an abort', () => {
156
+ client = setup(ws);
157
+ ws.last().receive({type: 'tool_start', sessionId: 'sid-1', toolName: 'bash', args: {command: 'echo'}});
158
+ ws.last().receive({
159
+ type: 'tool_end',
160
+ sessionId: 'sid-1',
161
+ toolName: 'bash',
162
+ isError: true,
163
+ result: 'the build was aborted by the linter\n\nCommand exited with code 2',
164
+ });
165
+ const tool = state().messages.find((m) => m.role === 'tool')!;
166
+ // Trailing status line is "Command exited with code 2", so it is a real error.
167
+ expect(tool.isError).toBe(true);
168
+ expect(tool.interrupted).toBeFalsy();
169
+ });
170
+ });