@wherever-dev/client 0.2.2 → 0.3.1

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.
@@ -0,0 +1,136 @@
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
+ // Bug: after an UNSOLICITED reconnect (the socket dropped on its own -- tab
7
+ // switch, network blip, laptop sleep, half-open reap -- NOT via suspend()), the
8
+ // client reconnected to the relay but did NOT re-issue session_load, so the new
9
+ // socket was attached to NO session server-side. The frontend kept showing the
10
+ // stale conversation (a frozen tool call as the last message, "Abort" disabled)
11
+ // and followed nothing, with no "connecting"/"loading" affordance, while the
12
+ // agent kept running behind the scenes. Only a full reload recovered it.
13
+ //
14
+ // The server is stateless per-connection: every new socket gets a fresh clientId
15
+ // with sessionId=null and the old socket's close removes the client from the
16
+ // pool. So the CLIENT must re-attach by re-issuing session_load on ANY reconnect
17
+ // that still holds an active session -- not only on the suspend/resume path.
18
+
19
+ function createAndLoad(
20
+ ws: ReturnType<typeof makeWSFactory>,
21
+ client: WhereverClient,
22
+ {streaming = false}: {streaming?: boolean} = {},
23
+ ) {
24
+ client.joinSession('/tmp/project/session.jsonl');
25
+ ws.last().receive({
26
+ type: 'session_created',
27
+ sessionId: 'sid-1',
28
+ sessionFile: '/tmp/project/session.jsonl',
29
+ cwd: '/tmp/project',
30
+ model: 'fake:model',
31
+ isStreaming: streaming,
32
+ });
33
+ ws.last().receive({
34
+ type: 'message_history',
35
+ sessionId: 'sid-1',
36
+ messages: [{role: 'user', content: 'go build it', timestamp: 1}],
37
+ totalCount: 1,
38
+ offset: 0,
39
+ });
40
+ }
41
+
42
+ describe('unsolicited reconnect re-attaches to the active session', () => {
43
+ let ws: ReturnType<typeof makeWSFactory>;
44
+ let client: WhereverClient;
45
+
46
+ beforeEach(() => {
47
+ vi.useFakeTimers();
48
+ ws = makeWSFactory();
49
+ client = new WhereverClient({
50
+ host: 'localhost',
51
+ port: 1234,
52
+ secure: false,
53
+ WebSocketCtor: ws.ctor,
54
+ });
55
+ client.connect();
56
+ ws.last().open();
57
+ createAndLoad(ws, client, {streaming: true});
58
+ });
59
+
60
+ afterEach(() => {
61
+ client.disconnect(true);
62
+ vi.useRealTimers();
63
+ });
64
+
65
+ it('re-issues session_load after the socket drops and reconnects', () => {
66
+ const firstWs = ws.last();
67
+ // The socket dies on its own (no suspend). onClose schedules a reconnect.
68
+ firstWs.close();
69
+
70
+ // The reconnect backoff timer fires and opens a brand-new socket.
71
+ vi.advanceTimersByTime(5000);
72
+ const secondWs = ws.last();
73
+ expect(secondWs).not.toBe(firstWs);
74
+ secondWs.open();
75
+
76
+ // The client MUST re-attach to the previously-active session so the live
77
+ // stream resumes; otherwise it is silently detached and frozen.
78
+ const load = secondWs.lastSentOfType('session_load');
79
+ expect(load).toBeTruthy();
80
+ expect(load.sessionFile).toBe('/tmp/project/session.jsonl');
81
+ });
82
+
83
+ it('shows a resyncing affordance during the reconnect, not a silent frozen view', () => {
84
+ const firstWs = ws.last();
85
+ firstWs.close();
86
+ vi.advanceTimersByTime(5000);
87
+ const secondWs = ws.last();
88
+ secondWs.open();
89
+
90
+ // While re-attaching, resyncing is true (drives the "Reconnecting and
91
+ // syncing session..." banner + blocks sending) and the cached conversation
92
+ // stays visible.
93
+ const s = get(client.stateStore);
94
+ expect(s.resyncing).toBe(true);
95
+ expect(s.activeSessionFile).toBe('/tmp/project/session.jsonl');
96
+ expect(s.messages.length).toBeGreaterThan(0);
97
+ });
98
+
99
+ it('clears resyncing and resumes the stream once fresh history arrives', () => {
100
+ ws.last().close();
101
+ vi.advanceTimersByTime(5000);
102
+ const secondWs = ws.last();
103
+ secondWs.open();
104
+
105
+ secondWs.receive({
106
+ type: 'session_created',
107
+ sessionId: 'sid-1',
108
+ sessionFile: '/tmp/project/session.jsonl',
109
+ cwd: '/tmp/project',
110
+ model: 'fake:model',
111
+ isStreaming: true,
112
+ });
113
+ secondWs.receive({
114
+ type: 'message_history',
115
+ sessionId: 'sid-1',
116
+ messages: [
117
+ {role: 'user', content: 'go build it', timestamp: 1},
118
+ {role: 'assistant', content: 'on it', timestamp: 2},
119
+ ],
120
+ totalCount: 2,
121
+ offset: 0,
122
+ });
123
+
124
+ const s = get(client.stateStore);
125
+ expect(s.resyncing).toBe(false);
126
+ expect(s.connected).toBe(true);
127
+ // Re-attach restores the true streaming state from the server, so "Abort"
128
+ // re-enables if the agent is still working (the reported symptom: Abort
129
+ // disabled with a stale tool call as last message).
130
+ expect(s.isStreaming).toBe(true);
131
+ // Live stream is following again: a new event after resync lands.
132
+ secondWs.receive({type: 'agent_end'});
133
+ vi.advanceTimersByTime(400);
134
+ expect(get(client.stateStore).isStreaming).toBe(false);
135
+ });
136
+ });
@@ -0,0 +1,118 @@
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
+ // Bug 2 (client-level invariant): on tab-background suspend() and return
7
+ // resume(), the client must KEEP the cached session (activeSessionFile +
8
+ // messages) and mark it resyncing, NOT drop to a no-session state. The UI keys
9
+ // the "new session / search box" empty-state on activeSessionFile being null; if
10
+ // suspend/resume nulled it, the search box would flash on every resume. These
11
+ // tests pin the client contract the UI relies on.
12
+
13
+ function createAndLoad(ws: ReturnType<typeof makeWSFactory>, client: WhereverClient) {
14
+ client.joinSession('/tmp/project/session.jsonl');
15
+ ws.last().receive({
16
+ type: 'session_created',
17
+ sessionId: 'sid-1',
18
+ sessionFile: '/tmp/project/session.jsonl',
19
+ cwd: '/tmp/project',
20
+ model: 'fake:model',
21
+ isStreaming: false,
22
+ });
23
+ ws.last().receive({
24
+ type: 'message_history',
25
+ sessionId: 'sid-1',
26
+ messages: [
27
+ {role: 'user', content: 'hello', timestamp: 1},
28
+ {role: 'assistant', content: 'hi there', timestamp: 2},
29
+ ],
30
+ totalCount: 2,
31
+ offset: 0,
32
+ });
33
+ }
34
+
35
+ describe('suspend/resume keeps the session visible', () => {
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
+ createAndLoad(ws, client);
51
+ });
52
+
53
+ afterEach(() => {
54
+ client.disconnect(true);
55
+ vi.useRealTimers();
56
+ });
57
+
58
+ it('starts with an active session and messages', () => {
59
+ const s = get(client.stateStore);
60
+ expect(s.activeSessionFile).toBe('/tmp/project/session.jsonl');
61
+ expect(s.messages.length).toBe(2);
62
+ });
63
+
64
+ it('suspend() preserves activeSessionFile and messages (does not drop to no-session)', () => {
65
+ client.suspend();
66
+ const s = get(client.stateStore);
67
+ expect(s.connected).toBe(false);
68
+ // The cached session and its messages must survive the suspend so the UI
69
+ // keeps showing the conversation, not the search/new-session empty-state.
70
+ expect(s.activeSessionFile).toBe('/tmp/project/session.jsonl');
71
+ expect(s.messages.length).toBe(2);
72
+ expect(client.hasSuspendedSession()).toBe(true);
73
+ });
74
+
75
+ it('resume() marks the session resyncing while keeping it visible', () => {
76
+ client.suspend();
77
+ client.resume();
78
+ const s = get(client.stateStore);
79
+ // resyncing drives the "Reconnecting and syncing session..." banner; the
80
+ // session must still be present so no search box flashes.
81
+ expect(s.resyncing).toBe(true);
82
+ expect(s.activeSessionFile).toBe('/tmp/project/session.jsonl');
83
+ expect(s.messages.length).toBe(2);
84
+ });
85
+
86
+ it('resume() rejoins in place and clears resyncing on the fresh history', () => {
87
+ client.suspend();
88
+ client.resume();
89
+ // A brand-new socket was created by resume(); open it.
90
+ ws.last().open();
91
+ // The client should have re-issued session_load for the cached session.
92
+ expect(ws.last().lastSentOfType('session_load')?.sessionFile).toBe(
93
+ '/tmp/project/session.jsonl',
94
+ );
95
+ ws.last().receive({
96
+ type: 'session_created',
97
+ sessionId: 'sid-1',
98
+ sessionFile: '/tmp/project/session.jsonl',
99
+ cwd: '/tmp/project',
100
+ model: 'fake:model',
101
+ isStreaming: false,
102
+ });
103
+ ws.last().receive({
104
+ type: 'message_history',
105
+ sessionId: 'sid-1',
106
+ messages: [
107
+ {role: 'user', content: 'hello', timestamp: 1},
108
+ {role: 'assistant', content: 'hi there', timestamp: 2},
109
+ ],
110
+ totalCount: 2,
111
+ offset: 0,
112
+ });
113
+ const s = get(client.stateStore);
114
+ expect(s.resyncing).toBe(false);
115
+ expect(s.connected).toBe(true);
116
+ expect(s.activeSessionFile).toBe('/tmp/project/session.jsonl');
117
+ });
118
+ });
@@ -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
+ });
@@ -0,0 +1,86 @@
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
+
6
+ // The tool-call timing the UI needs to show "Elapsed N.Ns" (running) and
7
+ // "Took N.Ns" (done), like the pi CLI: tool_start stamps startedAt, tool_end
8
+ // stamps endedAt, and a turn that ends without a tool_end freezes the running
9
+ // tool's endedAt so its duration stops ticking.
10
+
11
+ function makeClient() {
12
+ const c = new WhereverClient({host: 'x', port: 1, secure: false});
13
+ const feed = (msg: unknown) =>
14
+ (c as unknown as {handleMessage(m: unknown): void}).handleMessage(msg);
15
+ const state = () => get<WhereverState>(c.stateStore);
16
+ const lastTool = () =>
17
+ [...state().messages].reverse().find((m) => m.role === 'tool');
18
+ return {feed, state, lastTool};
19
+ }
20
+
21
+ const SESSION = 'sess-1';
22
+
23
+ beforeEach(() => vi.useFakeTimers());
24
+ afterEach(() => {
25
+ vi.clearAllTimers();
26
+ vi.useRealTimers();
27
+ });
28
+
29
+ describe('tool call timing', () => {
30
+ it('stamps startedAt on tool_start and endedAt on tool_end', () => {
31
+ const {feed, lastTool} = makeClient();
32
+ feed({type: 'agent_start', sessionId: SESSION});
33
+
34
+ vi.setSystemTime(1_000);
35
+ feed({
36
+ type: 'tool_start',
37
+ sessionId: SESSION,
38
+ toolName: 'bash',
39
+ args: {command: 'ls'},
40
+ });
41
+ const running = lastTool()!;
42
+ expect(running.startedAt).toBe(1_000);
43
+ expect(running.endedAt).toBeUndefined();
44
+ expect(running.isStreaming).toBe(true);
45
+
46
+ vi.setSystemTime(3_500);
47
+ feed({type: 'tool_end', sessionId: SESSION, toolName: 'bash', result: 'a\nb'});
48
+ const done = lastTool()!;
49
+ expect(done.startedAt).toBe(1_000);
50
+ expect(done.endedAt).toBe(3_500);
51
+ expect(done.isStreaming).toBe(false);
52
+ // 2.5s took.
53
+ expect(((done.endedAt! - done.startedAt!) / 1000).toFixed(1)).toBe('2.5');
54
+ });
55
+
56
+ it('freezes a running tool endedAt when the turn ends without tool_end', () => {
57
+ const {feed, lastTool} = makeClient();
58
+ feed({type: 'agent_start', sessionId: SESSION});
59
+ vi.setSystemTime(1_000);
60
+ feed({type: 'tool_start', sessionId: SESSION, toolName: 'bash', args: {}});
61
+ expect(lastTool()!.endedAt).toBeUndefined();
62
+
63
+ // Turn ends between steps with no tool_end for the running tool.
64
+ vi.setSystemTime(2_000);
65
+ feed({type: 'agent_end', sessionId: SESSION});
66
+ // The 300ms agent_end debounce fires; fake time advances to 2_300 and the
67
+ // callback stamps endedAt = Date.now() at that point.
68
+ vi.advanceTimersByTime(300);
69
+
70
+ const frozen = lastTool()!;
71
+ expect(frozen.isStreaming).toBe(false);
72
+ expect(frozen.endedAt).toBe(2_300);
73
+ });
74
+
75
+ it('freezes a running tool endedAt on abort', () => {
76
+ const {feed, lastTool} = makeClient();
77
+ feed({type: 'agent_start', sessionId: SESSION});
78
+ vi.setSystemTime(1_000);
79
+ feed({type: 'tool_start', sessionId: SESSION, toolName: 'bash', args: {}});
80
+ vi.setSystemTime(5_000);
81
+ feed({type: 'aborted', sessionId: SESSION});
82
+ const frozen = lastTool()!;
83
+ expect(frozen.isStreaming).toBe(false);
84
+ expect(frozen.endedAt).toBe(5_000);
85
+ });
86
+ });