@wherever-dev/client 0.3.0 → 0.3.2

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/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,44 @@ 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;
29
+ // Wall-clock start of a tool call (ms epoch), set when the tool_start frame
30
+ // arrives. `timestamp` also carries this, but startedAt is kept explicit so
31
+ // the elapsed/took duration is unambiguous and survives content rewrites.
32
+ startedAt?: number;
33
+ // Wall-clock end of a tool call (ms epoch), set when tool_end arrives. While a
34
+ // tool is running this is undefined and the UI ticks a live "Elapsed N.Ns";
35
+ // once set the UI freezes it as "Took N.Ns" (mirrors the pi CLI).
36
+ endedAt?: number;
37
+ // Delivery state for an OUTBOUND user message. A frame handed to a socket that
38
+ // reports OPEN can still never reach the server (a half-open TCP connection:
39
+ // send() buffers locally, no throw, but the bytes never land). So an optimistic
40
+ // echo is NOT proof of delivery. `delivery` tracks that:
41
+ // 'sending' -> handed to the socket, awaiting the server's echo.
42
+ // 'failed' -> no echo within the confirmation window; delivery is
43
+ // uncertain, so the UI surfaces a retry affordance rather than
44
+ // a normal-looking sent message.
45
+ // Undefined = confirmed/delivered (or a message that never needed tracking,
46
+ // e.g. one loaded from server history). Confirmed on the server's user echo
47
+ // (message_end role:user) or when it reappears in loaded history.
48
+ delivery?: 'sending' | 'failed';
49
+ }
50
+
51
+ export interface SessionNotice {
52
+ level: 'info' | 'warning';
53
+ message: string;
12
54
  }
13
55
 
14
56
  export interface ConflictInfo {
@@ -46,6 +88,12 @@ export interface WhereverState {
46
88
  clientId: string | null;
47
89
  conflict: ConflictInfo | null;
48
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;
49
97
  sessionError: string | null;
50
98
  readOnly: boolean;
51
99
  activeSessionFile: string | null;
@@ -0,0 +1,194 @@
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
+ // The half-open loss: the socket reports OPEN, ws.send() succeeds (buffers, no
8
+ // throw), but the frame never reaches the server. The optimistic user echo must
9
+ // NOT be treated as delivered: it stays unconfirmed, is recoverable on reload,
10
+ // and flips to a "failed / needs retry" state instead of vanishing.
11
+
12
+ // A localStorage shim so persistence works under the node test env.
13
+ function installLocalStorage() {
14
+ const store = new Map<string, string>();
15
+ (globalThis as any).localStorage = {
16
+ getItem: (k: string) => (store.has(k) ? store.get(k)! : null),
17
+ setItem: (k: string, v: string) => void store.set(k, v),
18
+ removeItem: (k: string) => void store.delete(k),
19
+ clear: () => store.clear(),
20
+ };
21
+ return store;
22
+ }
23
+
24
+ function createAndLoad(
25
+ ws: ReturnType<typeof makeWSFactory>,
26
+ client: WhereverClient,
27
+ messages: any[] = [],
28
+ ) {
29
+ client.joinSession('/tmp/project/session.jsonl');
30
+ ws.last().receive({
31
+ type: 'session_created',
32
+ sessionId: 'sid-1',
33
+ sessionFile: '/tmp/project/session.jsonl',
34
+ cwd: '/tmp/project',
35
+ model: 'fake:model',
36
+ isStreaming: false,
37
+ });
38
+ ws.last().receive({
39
+ type: 'message_history',
40
+ sessionId: 'sid-1',
41
+ messages,
42
+ totalCount: messages.length,
43
+ offset: 0,
44
+ });
45
+ }
46
+
47
+ describe('outbound message delivery confirmation', () => {
48
+ let ws: ReturnType<typeof makeWSFactory>;
49
+ let client: WhereverClient;
50
+ const state = () => get<WhereverState>(client.stateStore);
51
+
52
+ beforeEach(() => {
53
+ vi.useFakeTimers();
54
+ installLocalStorage();
55
+ (globalThis as any).localStorage.clear();
56
+ ws = makeWSFactory();
57
+ client = new WhereverClient({
58
+ host: 'localhost',
59
+ port: 1234,
60
+ secure: false,
61
+ WebSocketCtor: ws.ctor,
62
+ });
63
+ client.connect();
64
+ ws.last().open();
65
+ createAndLoad(ws, client);
66
+ });
67
+
68
+ afterEach(() => {
69
+ client.disconnect(true);
70
+ vi.useRealTimers();
71
+ });
72
+
73
+ it('marks a sent message as unconfirmed (sending), not delivered', () => {
74
+ const ok = client.sendMessage('hello there');
75
+ expect(ok).toBe(true);
76
+ const m = state().messages.find((x) => x.content === 'hello there')!;
77
+ expect(m.delivery).toBe('sending');
78
+ });
79
+
80
+ it('confirms the message when the server echoes it back', () => {
81
+ client.sendMessage('confirm me');
82
+ ws.last().receive({
83
+ type: 'message_end',
84
+ sessionId: 'sid-1',
85
+ role: 'user',
86
+ content: 'confirm me',
87
+ });
88
+ const m = state().messages.find((x) => x.content === 'confirm me')!;
89
+ expect(m.delivery).toBeUndefined();
90
+ // No duplicate echo added.
91
+ expect(
92
+ state().messages.filter((x) => x.content === 'confirm me').length,
93
+ ).toBe(1);
94
+ });
95
+
96
+ it('flips to failed when no echo arrives within the window (half-open loss)', () => {
97
+ // Half-open: send() reports success but the server never processes it, so
98
+ // no echo is ever received.
99
+ client.sendMessage('lost message');
100
+ expect(
101
+ state().messages.find((x) => x.content === 'lost message')!.delivery,
102
+ ).toBe('sending');
103
+
104
+ vi.advanceTimersByTime(12_000);
105
+ const m = state().messages.find((x) => x.content === 'lost message')!;
106
+ expect(m.delivery).toBe('failed');
107
+ });
108
+
109
+ it('persists an unconfirmed message so a reload can recover it', () => {
110
+ client.sendMessage('recover me on reload');
111
+ // Simulate a reload: a fresh client instance against the same localStorage.
112
+ const ws2 = makeWSFactory();
113
+ const client2 = new WhereverClient({
114
+ host: 'localhost',
115
+ port: 1234,
116
+ secure: false,
117
+ WebSocketCtor: ws2.ctor,
118
+ });
119
+ client2.connect();
120
+ ws2.last().open();
121
+ // History comes back WITHOUT the message (the server never got it).
122
+ createAndLoad(ws2, client2, []);
123
+
124
+ const recovered = get<WhereverState>(client2.stateStore).messages.find(
125
+ (x) => x.content === 'recover me on reload',
126
+ );
127
+ expect(recovered).toBeTruthy();
128
+ expect(recovered!.delivery).toBe('failed');
129
+ client2.disconnect(true);
130
+ });
131
+
132
+ it('does NOT re-surface a message that history confirms was delivered', () => {
133
+ client.sendMessage('this one landed');
134
+ // Reload; history DOES contain it (it was delivered before the drop).
135
+ const ws2 = makeWSFactory();
136
+ const client2 = new WhereverClient({
137
+ host: 'localhost',
138
+ port: 1234,
139
+ secure: false,
140
+ WebSocketCtor: ws2.ctor,
141
+ });
142
+ client2.connect();
143
+ ws2.last().open();
144
+ createAndLoad(ws2, client2, [
145
+ {role: 'user', content: 'this one landed', timestamp: 1_000},
146
+ ]);
147
+
148
+ const msgs = get<WhereverState>(client2.stateStore).messages.filter(
149
+ (x) => x.content === 'this one landed',
150
+ );
151
+ // Exactly one, and delivered (no failed duplicate).
152
+ expect(msgs.length).toBe(1);
153
+ expect(msgs[0].delivery).toBeUndefined();
154
+ client2.disconnect(true);
155
+ });
156
+
157
+ it('resendMessage re-sends a failed message and re-arms confirmation', () => {
158
+ client.sendMessage('retry me');
159
+ vi.advanceTimersByTime(12_000);
160
+ const failed = state().messages.find((x) => x.content === 'retry me')!;
161
+ expect(failed.delivery).toBe('failed');
162
+
163
+ const sock = ws.last();
164
+ const before = sock.sent.filter((f) => f.type === 'message').length;
165
+ const ok = client.resendMessage(failed.id);
166
+ expect(ok).toBe(true);
167
+ expect(sock.sent.filter((f) => f.type === 'message').length).toBe(before + 1);
168
+ expect(
169
+ state().messages.find((x) => x.id === failed.id)!.delivery,
170
+ ).toBe('sending');
171
+
172
+ // The echo now confirms it.
173
+ sock.receive({
174
+ type: 'message_end',
175
+ sessionId: 'sid-1',
176
+ role: 'user',
177
+ content: 'retry me',
178
+ });
179
+ expect(
180
+ state().messages.find((x) => x.id === failed.id)!.delivery,
181
+ ).toBeUndefined();
182
+ });
183
+
184
+ it('discardMessage removes a failed message and clears it from persistence', () => {
185
+ client.sendMessage('drop me');
186
+ vi.advanceTimersByTime(12_000);
187
+ const failed = state().messages.find((x) => x.content === 'drop me')!;
188
+ client.discardMessage(failed.id);
189
+ expect(state().messages.find((x) => x.content === 'drop me')).toBeUndefined();
190
+ expect(
191
+ (globalThis as any).localStorage.getItem('wherever-pending:sid-1'),
192
+ ).toBeNull();
193
+ });
194
+ });
@@ -0,0 +1,91 @@
1
+ import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
2
+ import {get} from 'sveltore';
3
+ import {WhereverClient} from '../src/client.js';
4
+ import {makeWSFactory} from './harness.js';
5
+
6
+ // A message submitted WHILE the agent is streaming must be sent to the relay
7
+ // IMMEDIATELY (the server turns a mid-stream `message` into a steer, injected at
8
+ // the next tool/step boundary). This is the pi-CLI default (Enter -> steer). It
9
+ // must NOT be held locally waiting for the turn to finish -- the old behaviour
10
+ // that also mis-fired mid-turn on the flaky isStreaming debounce (docs/adr/0003).
11
+
12
+ function createAndLoad(
13
+ ws: ReturnType<typeof makeWSFactory>,
14
+ client: WhereverClient,
15
+ {streaming = false}: {streaming?: boolean} = {},
16
+ ) {
17
+ client.joinSession('/tmp/project/session.jsonl');
18
+ ws.last().receive({
19
+ type: 'session_created',
20
+ sessionId: 'sid-1',
21
+ sessionFile: '/tmp/project/session.jsonl',
22
+ cwd: '/tmp/project',
23
+ model: 'fake:model',
24
+ isStreaming: streaming,
25
+ });
26
+ ws.last().receive({
27
+ type: 'message_history',
28
+ sessionId: 'sid-1',
29
+ messages: [{role: 'user', content: 'go build it', timestamp: 1}],
30
+ totalCount: 1,
31
+ offset: 0,
32
+ });
33
+ }
34
+
35
+ describe('mid-stream submit steers immediately', () => {
36
+ let ws: ReturnType<typeof makeWSFactory>;
37
+ let client: WhereverClient;
38
+
39
+ beforeEach(() => {
40
+ vi.useFakeTimers();
41
+ ws = makeWSFactory();
42
+ client = new WhereverClient({
43
+ host: 'localhost',
44
+ port: 1234,
45
+ secure: false,
46
+ WebSocketCtor: ws.ctor,
47
+ });
48
+ client.connect();
49
+ ws.last().open();
50
+ });
51
+
52
+ afterEach(() => {
53
+ client.disconnect(true);
54
+ vi.useRealTimers();
55
+ });
56
+
57
+ it('sends the message frame NOW while the agent is mid-turn', () => {
58
+ createAndLoad(ws, client, {streaming: true});
59
+ const sock = ws.last();
60
+ expect(get(client.stateStore).isStreaming).toBe(true);
61
+
62
+ // User submits mid-stream. sendMessage must hand a `message` frame to the
63
+ // OPEN socket right away, not park it.
64
+ const ok = client.sendMessage('actually, do X instead');
65
+ expect(ok).toBe(true);
66
+
67
+ const frame = sock.lastSentOfType('message');
68
+ expect(frame).toBeTruthy();
69
+ expect(frame.message).toBe('actually, do X instead');
70
+
71
+ // The optimistic user echo is committed immediately (not withheld pending
72
+ // a later drain), and the turn is still in flight.
73
+ const s = get(client.stateStore);
74
+ expect(s.messages.some((m) => m.role === 'user' && m.content === 'actually, do X instead')).toBe(true);
75
+ expect(s.isStreaming).toBe(true);
76
+ });
77
+
78
+ it('returns false and keeps no phantom echo when disconnected mid-stream', () => {
79
+ createAndLoad(ws, client, {streaming: true});
80
+ const sock = ws.last();
81
+ // Socket drops just as the user submits.
82
+ sock.close();
83
+
84
+ const before = get(client.stateStore).messages.length;
85
+ const ok = client.sendMessage('do X instead');
86
+ expect(ok).toBe(false);
87
+ // No optimistic echo for a send that never left; caller keeps the text.
88
+ expect(get(client.stateStore).messages.length).toBe(before);
89
+ expect(get(client.stateStore).sessionError).toBeTruthy();
90
+ });
91
+ });
@@ -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
+ });
@@ -0,0 +1,93 @@
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
+ // A tool call reconstructed from LOADED history must carry the same duration as
8
+ // a live-streamed one, so "Took N.Ns" survives a reload. The server sends the
9
+ // tool_call and tool_result as separate HistoryMessages, each with its own
10
+ // timestamp; the client pairs them and computes startedAt/endedAt.
11
+
12
+ describe('tool duration from loaded history', () => {
13
+ let ws: ReturnType<typeof makeWSFactory>;
14
+ let client: WhereverClient;
15
+ const state = () => get<WhereverState>(client.stateStore);
16
+
17
+ beforeEach(() => {
18
+ vi.useFakeTimers();
19
+ ws = makeWSFactory();
20
+ client = new WhereverClient({
21
+ host: 'localhost',
22
+ port: 1234,
23
+ secure: false,
24
+ WebSocketCtor: ws.ctor,
25
+ });
26
+ client.connect();
27
+ ws.last().open();
28
+ client.joinSession('/tmp/project/session.jsonl');
29
+ ws.last().receive({
30
+ type: 'session_created',
31
+ sessionId: 'sid-1',
32
+ sessionFile: '/tmp/project/session.jsonl',
33
+ cwd: '/tmp/project',
34
+ model: 'fake:model',
35
+ isStreaming: false,
36
+ });
37
+ });
38
+
39
+ afterEach(() => {
40
+ client.disconnect(true);
41
+ vi.useRealTimers();
42
+ });
43
+
44
+ it('pairs a tool_call + tool_result into a duration', () => {
45
+ ws.last().receive({
46
+ type: 'message_history',
47
+ sessionId: 'sid-1',
48
+ messages: [
49
+ {role: 'user', content: 'go', timestamp: 1_000},
50
+ {
51
+ role: 'tool_call',
52
+ content: '{"command":"ls"}',
53
+ timestamp: 10_000,
54
+ toolName: 'bash',
55
+ },
56
+ {
57
+ role: 'tool_result',
58
+ content: 'a\nb',
59
+ timestamp: 13_400,
60
+ toolName: 'bash',
61
+ isError: false,
62
+ },
63
+ ],
64
+ totalCount: 3,
65
+ offset: 0,
66
+ });
67
+
68
+ const tool = state().messages.find((m) => m.role === 'tool')!;
69
+ expect(tool.startedAt).toBe(10_000);
70
+ expect(tool.endedAt).toBe(13_400);
71
+ expect(((tool.endedAt! - tool.startedAt!) / 1000).toFixed(1)).toBe('3.4');
72
+ });
73
+
74
+ it('leaves duration unset for an unmatched (result-less) tool_call', () => {
75
+ ws.last().receive({
76
+ type: 'message_history',
77
+ sessionId: 'sid-1',
78
+ messages: [
79
+ {
80
+ role: 'tool_call',
81
+ content: '{}',
82
+ timestamp: 10_000,
83
+ toolName: 'bash',
84
+ },
85
+ ],
86
+ totalCount: 1,
87
+ offset: 0,
88
+ });
89
+ const tool = state().messages.find((m) => m.role === 'tool')!;
90
+ expect(tool.startedAt).toBe(10_000);
91
+ expect(tool.endedAt).toBeUndefined();
92
+ });
93
+ });