@wherever-dev/client 0.2.1 → 0.3.0

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
@@ -21,6 +21,23 @@ export interface WhereverState {
21
21
  connected: boolean;
22
22
  connecting: boolean;
23
23
  creatingSession: boolean;
24
+ // True from the moment a session_load is requested until its message_history
25
+ // (or an error/conflict) arrives. Distinguishes "opening an existing session"
26
+ // from "a brand new empty session" so the UI can show a loading state instead
27
+ // of the "New Session Started" empty state.
28
+ loadingSession: boolean;
29
+ // True while the connection was suspended (e.g. the tab was backgrounded) and
30
+ // is now reconnecting + rejoining the previously-active session. The cached
31
+ // messages remain visible; the UI shows a "reconnecting/syncing" affordance
32
+ // and blocks input until the resync completes.
33
+ resyncing: boolean;
34
+ // True after a `pending` session_created (history painted from a cheap read)
35
+ // until session_ready arrives (the live agent finished building). The
36
+ // conversation is READABLE during this window, but SENDING must be blocked:
37
+ // reading only needs the transcript, sending needs the live agent. Distinct
38
+ // from loadingSession/resyncing, which gate the whole view; agentPending gates
39
+ // only the composer so opening a cold session to read is instant.
40
+ agentPending: boolean;
24
41
  error: string | null;
25
42
  session: string | null;
26
43
  sessionId: string | null;
@@ -43,4 +60,13 @@ export interface WhereverState {
43
60
  historyTotalCount: number;
44
61
  historyOffset: number;
45
62
  loadingMoreHistory: boolean;
63
+ // Context-window usage for the active session (drives the "11.3% / 1.0M"
64
+ // indicator). null when unknown (no model, no usage yet, or just compacted).
65
+ contextUsage: ContextUsage | null;
66
+ }
67
+
68
+ export interface ContextUsage {
69
+ tokens: number | null;
70
+ contextWindow: number;
71
+ percent: number | null;
46
72
  }
@@ -0,0 +1,107 @@
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
+ // Fast-first load reducer contract: a `pending` session_created paints history
7
+ // but keeps the composer blocked (agentPending) until session_ready; a
8
+ // non-pending create is immediately sendable; a session_error while pending
9
+ // degrades to readable-but-not-sendable.
10
+
11
+ describe('agentPending (fast-first load)', () => {
12
+ let ws: ReturnType<typeof makeWSFactory>;
13
+ let client: WhereverClient;
14
+
15
+ beforeEach(() => {
16
+ vi.useFakeTimers();
17
+ ws = makeWSFactory();
18
+ client = new WhereverClient({
19
+ host: 'localhost',
20
+ port: 1234,
21
+ secure: false,
22
+ WebSocketCtor: ws.ctor,
23
+ });
24
+ client.connect();
25
+ ws.last().open();
26
+ });
27
+
28
+ afterEach(() => {
29
+ client.disconnect(true);
30
+ vi.useRealTimers();
31
+ });
32
+
33
+ function loadPending() {
34
+ client.joinSession('/tmp/p/session.jsonl');
35
+ ws.last().receive({
36
+ type: 'session_created',
37
+ sessionId: 'sid-1',
38
+ sessionFile: '/tmp/p/session.jsonl',
39
+ cwd: '/tmp/p',
40
+ model: '',
41
+ isStreaming: false,
42
+ pending: true,
43
+ });
44
+ ws.last().receive({
45
+ type: 'message_history',
46
+ sessionId: 'sid-1',
47
+ messages: [
48
+ {role: 'user', content: 'hi', timestamp: 1},
49
+ {role: 'assistant', content: 'hello', timestamp: 2},
50
+ ],
51
+ totalCount: 2,
52
+ offset: 0,
53
+ });
54
+ }
55
+
56
+ it('paints history but stays agentPending until session_ready', () => {
57
+ loadPending();
58
+ let s = get(client.stateStore);
59
+ // History is readable now.
60
+ expect(s.messages.length).toBe(2);
61
+ expect(s.loadingSession).toBe(false);
62
+ // But sending is blocked until the agent is ready.
63
+ expect(s.agentPending).toBe(true);
64
+ expect(client.sendMessage('nope')).toBe(false);
65
+
66
+ ws.last().receive({
67
+ type: 'session_ready',
68
+ sessionId: 'sid-1',
69
+ sessionFile: '/tmp/p/session.jsonl',
70
+ model: 'fake:model',
71
+ isStreaming: false,
72
+ });
73
+ s = get(client.stateStore);
74
+ expect(s.agentPending).toBe(false);
75
+ expect(s.activeModel).toBe('fake:model');
76
+ // Now a send goes out over the open socket.
77
+ expect(client.sendMessage('now it works')).toBe(true);
78
+ expect(ws.last().lastSentOfType('message')?.message).toBe('now it works');
79
+ });
80
+
81
+ it('a non-pending create is immediately sendable', () => {
82
+ client.createSession('/tmp/new');
83
+ ws.last().receive({
84
+ type: 'session_created',
85
+ sessionId: 'sid-2',
86
+ sessionFile: '/tmp/new/session.jsonl',
87
+ cwd: '/tmp/new',
88
+ model: 'fake:model',
89
+ isStreaming: false,
90
+ // no pending flag
91
+ });
92
+ const s = get(client.stateStore);
93
+ expect(s.agentPending).toBe(false);
94
+ expect(client.sendMessage('hi')).toBe(true);
95
+ });
96
+
97
+ it('session_error while pending degrades to readable-but-not-sendable', () => {
98
+ loadPending();
99
+ expect(get(client.stateStore).agentPending).toBe(true);
100
+ ws.last().receive({type: 'session_error', sessionId: 'sid-1', error: 'agent build failed'});
101
+ const s = get(client.stateStore);
102
+ expect(s.agentPending).toBe(false);
103
+ expect(s.sessionError).toBe('agent build failed');
104
+ // History is still there to read.
105
+ expect(s.messages.length).toBe(2);
106
+ });
107
+ });
@@ -0,0 +1,82 @@
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 1: creating a new session shows the full-screen "Creating session..."
7
+ // spinner (state.creatingSession) forever when the server never replies with
8
+ // session_created / session_error (a slow git init or remote-repo creation, an
9
+ // error thrown before the reply is sent, or a half-open socket the liveness
10
+ // watchdog has not reaped yet). Every OTHER load flag (loadingSession,
11
+ // resyncing) is guarded by a watchdog; creatingSession was not. These tests pin
12
+ // the contract: creatingSession must always resolve.
13
+
14
+ describe('creating-session watchdog', () => {
15
+ let ws: ReturnType<typeof makeWSFactory>;
16
+ let client: WhereverClient;
17
+
18
+ beforeEach(() => {
19
+ vi.useFakeTimers();
20
+ ws = makeWSFactory();
21
+ client = new WhereverClient({
22
+ host: 'localhost',
23
+ port: 1234,
24
+ secure: false,
25
+ WebSocketCtor: ws.ctor,
26
+ });
27
+ client.connect();
28
+ ws.last().open();
29
+ });
30
+
31
+ afterEach(() => {
32
+ client.disconnect(true);
33
+ vi.useRealTimers();
34
+ });
35
+
36
+ it('sets creatingSession true when a create is requested', () => {
37
+ client.createSession('/tmp/project');
38
+ expect(get(client.stateStore).creatingSession).toBe(true);
39
+ });
40
+
41
+ it('clears creatingSession and surfaces a recoverable error if no reply ever arrives', () => {
42
+ client.createSession('/tmp/project');
43
+ expect(get(client.stateStore).creatingSession).toBe(true);
44
+
45
+ // No session_created / session_error comes back. Advance past the watchdog.
46
+ vi.advanceTimersByTime(30_000);
47
+
48
+ const s = get(client.stateStore);
49
+ expect(s.creatingSession).toBe(false);
50
+ expect(s.sessionError).toBeTruthy();
51
+ });
52
+
53
+ it('clears creatingSession normally on session_created (watchdog does not fire)', () => {
54
+ client.createSession('/tmp/project');
55
+ ws.last().receive({
56
+ type: 'session_created',
57
+ sessionId: 'sid-1',
58
+ sessionFile: '/tmp/project/session.jsonl',
59
+ cwd: '/tmp/project',
60
+ model: 'fake:model',
61
+ isStreaming: false,
62
+ });
63
+
64
+ expect(get(client.stateStore).creatingSession).toBe(false);
65
+
66
+ // The watchdog must have been disarmed: advancing time must NOT resurrect
67
+ // an error on the now-successfully-created session.
68
+ vi.advanceTimersByTime(30_000);
69
+ const s = get(client.stateStore);
70
+ expect(s.creatingSession).toBe(false);
71
+ expect(s.sessionError).toBeFalsy();
72
+ expect(s.activeSessionFile).toBe('/tmp/project/session.jsonl');
73
+ });
74
+
75
+ it('clears creatingSession on session_error', () => {
76
+ client.createSession('/tmp/project');
77
+ ws.last().receive({type: 'session_error', error: 'boom'});
78
+ const s = get(client.stateStore);
79
+ expect(s.creatingSession).toBe(false);
80
+ expect(s.sessionError).toBe('boom');
81
+ });
82
+ });
@@ -0,0 +1,97 @@
1
+ // Minimal fake WebSocket for driving WhereverClient.handleMessage deterministically
2
+ // in unit tests. It records outbound frames and lets a test push inbound frames
3
+ // (server -> client) synchronously. No real network. Mirrors the tiny slice of
4
+ // the WHATWG WebSocket API that the client uses (readyState, addEventListener for
5
+ // open/message/close/error, send, close).
6
+
7
+ export type WSListener = (event: any) => void;
8
+
9
+ export class FakeWebSocket {
10
+ // WHATWG readyState constants.
11
+ static CONNECTING = 0;
12
+ static OPEN = 1;
13
+ static CLOSING = 2;
14
+ static CLOSED = 3;
15
+
16
+ url: string;
17
+ readyState = FakeWebSocket.CONNECTING;
18
+ sent: any[] = [];
19
+ private listeners: Record<string, Set<WSListener>> = {
20
+ open: new Set(),
21
+ message: new Set(),
22
+ close: new Set(),
23
+ error: new Set(),
24
+ };
25
+
26
+ constructor(url: string) {
27
+ this.url = url;
28
+ }
29
+
30
+ addEventListener(type: string, cb: WSListener) {
31
+ this.listeners[type]?.add(cb);
32
+ }
33
+
34
+ removeEventListener(type: string, cb: WSListener) {
35
+ this.listeners[type]?.delete(cb);
36
+ }
37
+
38
+ removeAllListeners() {
39
+ for (const key of Object.keys(this.listeners)) {
40
+ this.listeners[key].clear();
41
+ }
42
+ }
43
+
44
+ send(data: string) {
45
+ this.sent.push(JSON.parse(data));
46
+ }
47
+
48
+ close() {
49
+ if (this.readyState === FakeWebSocket.CLOSED) return;
50
+ this.readyState = FakeWebSocket.CLOSED;
51
+ this.emit('close', {});
52
+ }
53
+
54
+ // terminate() is used by the liveness watchdog's forcible teardown path.
55
+ terminate() {
56
+ this.close();
57
+ }
58
+
59
+ // --- test-only helpers -------------------------------------------------
60
+
61
+ /** Simulate the socket opening (server accepted the connection). */
62
+ open() {
63
+ this.readyState = FakeWebSocket.OPEN;
64
+ this.emit('open', {});
65
+ }
66
+
67
+ /** Push a server -> client frame. */
68
+ receive(msg: any) {
69
+ this.emit('message', {data: JSON.stringify(msg)});
70
+ }
71
+
72
+ /** Last outbound frame of a given type, or undefined. */
73
+ lastSentOfType(type: string) {
74
+ return [...this.sent].reverse().find((m) => m.type === type);
75
+ }
76
+
77
+ private emit(type: string, event: any) {
78
+ for (const cb of this.listeners[type] ?? []) cb(event);
79
+ }
80
+ }
81
+
82
+ // A WebSocket constructor that records every instance it creates, so a test can
83
+ // grab the live socket the client just opened and drive it. Assigned to
84
+ // config.WebSocketCtor.
85
+ export function makeWSFactory() {
86
+ const instances: FakeWebSocket[] = [];
87
+ const ctor = function (url: string) {
88
+ const ws = new FakeWebSocket(url);
89
+ instances.push(ws);
90
+ return ws;
91
+ } as unknown as {new (url: string): FakeWebSocket};
92
+ return {
93
+ ctor,
94
+ instances,
95
+ last: () => instances[instances.length - 1],
96
+ };
97
+ }
@@ -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
+ });