@wherever-dev/client 0.8.0 → 0.8.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.
Files changed (39) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +63 -0
  3. package/dist/client.d.ts +5 -0
  4. package/dist/client.js +102 -44
  5. package/dist/client.js.map +1 -1
  6. package/dist/types.d.ts +1 -0
  7. package/dist/types.js.map +1 -1
  8. package/package.json +23 -3
  9. package/src/client.ts +105 -49
  10. package/src/types.ts +3 -0
  11. package/test/agent-pending.test.ts +0 -107
  12. package/test/chunked-upload.test.ts +0 -483
  13. package/test/conversation-mode-flag.test.ts +0 -111
  14. package/test/creating-session-watchdog.test.ts +0 -82
  15. package/test/folder-conflict-read-only.test.ts +0 -145
  16. package/test/folder-missing-read-only.test.ts +0 -114
  17. package/test/harness.ts +0 -133
  18. package/test/hydration-seam.test.ts +0 -400
  19. package/test/liveness-probe.test.ts +0 -183
  20. package/test/message-delivery-confirmation.test.ts +0 -320
  21. package/test/mid-stream-steer.test.ts +0 -91
  22. package/test/new-session-clone-progress.test.ts +0 -263
  23. package/test/optimistic-force-command.test.ts +0 -127
  24. package/test/queued-steer-restored.test.ts +0 -175
  25. package/test/reconnect-rejoins-session.test.ts +0 -136
  26. package/test/restore-panel.test.ts +0 -324
  27. package/test/resume-keeps-session.test.ts +0 -118
  28. package/test/session-load-by-id.test.ts +0 -100
  29. package/test/session-reload.test.ts +0 -82
  30. package/test/skills-autocomplete.test.ts +0 -113
  31. package/test/steer-queue-cancel.test.ts +0 -130
  32. package/test/superseded-connection-key.test.ts +0 -70
  33. package/test/superseded-session-load.test.ts +0 -180
  34. package/test/tool-aborted-render.test.ts +0 -170
  35. package/test/tool-duration-history.test.ts +0 -93
  36. package/test/tool-duration.test.ts +0 -86
  37. package/test/tool-interrupted-history.test.ts +0 -294
  38. package/test/upload-survives-reconnect.test.ts +0 -482
  39. package/tsconfig.json +0 -16
package/src/client.ts CHANGED
@@ -251,6 +251,7 @@ const defaultState: WhereverState = {
251
251
  messages: [],
252
252
  clientId: null,
253
253
  serverVersion: null,
254
+ piVersion: null,
254
255
  folderConflict: null,
255
256
  folderMissing: null,
256
257
  restore: null,
@@ -306,7 +307,11 @@ export class WhereverClient {
306
307
  private createWatchdog: any = null;
307
308
  private static readonly CREATE_WATCHDOG_MS = 25_000;
308
309
  private reconnectAttempts = 0;
309
- private reconnectDelay = 2000;
310
+ private static readonly MIN_RECONNECT_DELAY = 2000;
311
+ private reconnectDelay = WhereverClient.MIN_RECONNECT_DELAY;
312
+ // Wall-clock time the current socket was created, so a return to the page can
313
+ // tell a handshake that has hung across a freeze from one just started.
314
+ private socketStartedAt = 0;
310
315
  private maxReconnectDelay = 15000;
311
316
  // Whether the socket has EVER opened successfully since construction. Repeated
312
317
  // closes with zero successful opens almost always mean a rejected handshake
@@ -342,6 +347,20 @@ export class WhereverClient {
342
347
  // the timers fire BEFORE the frames queued during the freeze are dispatched,
343
348
  // so the raw silence verdict is routinely false on a phone.
344
349
  private static readonly PROBE_GRACE_MS = 5_000;
350
+ // The probe a return to the page starts (noteVisible) uses a shorter grace.
351
+ // The long grace above exists because timers that came due DURING a freeze
352
+ // fire before the frames queued during it; a probe started from the
353
+ // visibility event is a fresh timer, so the queued frames (and a healthy
354
+ // socket's pong, one round trip later) are dispatched well before it fires.
355
+ // Waiting the full 5 s there, then the reconnect backoff on top, is what made
356
+ // coming back to the PWA slower than a reload.
357
+ private static readonly VISIBLE_PROBE_GRACE_MS = 2_000;
358
+ // A socket still CONNECTING this long when the page becomes visible is
359
+ // treated as a handshake that hung (typically started before a freeze,
360
+ // against a network that was gone) and restarted. Well above an honest slow
361
+ // mobile TLS handshake, so a return never throws away one that is about to
362
+ // complete.
363
+ private static readonly STALLED_HANDSHAKE_MS = 8_000;
345
364
  // The pending probe's grace timer, and the socket it was started on. Cleared
346
365
  // by any inbound frame, by stopLivenessWatchdog (every socket change), and
347
366
  // ignored if the socket it belongs to is no longer current.
@@ -510,6 +529,7 @@ export class WhereverClient {
510
529
 
511
530
  // A new socket: its capabilities are unknown until its `connected` frame.
512
531
  this.socketCapabilities = null;
532
+ this.socketStartedAt = Date.now();
513
533
  try {
514
534
  const wsOptions = this.config.secure && this.config.WebSocketCtor ? { rejectUnauthorized: false } : undefined;
515
535
  this.ws = wsOptions ? new WebSocketImpl(wsUrl, wsOptions) : new WebSocketImpl(wsUrl);
@@ -532,7 +552,7 @@ export class WhereverClient {
532
552
  }
533
553
  this.hasEverConnected = true;
534
554
  this.reconnectAttempts = 0;
535
- this.reconnectDelay = 2000;
555
+ this.reconnectDelay = WhereverClient.MIN_RECONNECT_DELAY;
536
556
  this.isInitialConnect = false;
537
557
  this.startLivenessWatchdog();
538
558
  this.stateStore.update(s => ({
@@ -869,20 +889,40 @@ export class WhereverClient {
869
889
  // socket is OPEN and watched, probe it right away instead of waiting for the
870
890
  // next tick, and reset the stale baseline so the time the page spent frozen is
871
891
  // not counted as silence (the probe decides whether the socket is alive).
872
- // A no-op otherwise: on a CONNECTING socket the ping would be dropped by
873
- // send() and the grace check would tear down a socket still handshaking.
892
+ //
893
+ // The user is looking at the page, so a return must never pay the slow paths
894
+ // meant for an unattended client: the probe uses the short
895
+ // VISIBLE_PROBE_GRACE_MS, a socket it condemns is replaced at once instead of
896
+ // after the reconnect backoff, and the backoff grown while hidden is reset.
897
+ // A socket still CONNECTING after STALLED_HANDSHAKE_MS is restarted.
898
+ // With no socket at all this only resets the backoff: the page follows up
899
+ // with resume() / connect(), which connect at once.
874
900
  public noteVisible() {
901
+ this.reconnectDelay = WhereverClient.MIN_RECONNECT_DELAY;
875
902
  const ws = this.ws as any;
876
- if (!ws || ws.readyState !== 1 /* OPEN */ || !this.livenessTimer) return;
903
+ if (!ws) return;
904
+ if (ws.readyState === 0 /* CONNECTING */) {
905
+ if (Date.now() - this.socketStartedAt > WhereverClient.STALLED_HANDSHAKE_MS) {
906
+ console.info('[wherever] handshake stalled; restarting it');
907
+ this.reconnectNow();
908
+ }
909
+ return;
910
+ }
911
+ if (ws.readyState !== 1 /* OPEN */ || !this.livenessTimer) return;
877
912
  this.lastInboundAt = Date.now();
878
913
  this.lastLivenessTickAt = this.lastInboundAt;
879
914
  // Restart any pending probe: its grace may have been eaten by the freeze.
880
915
  this.cancelLivenessProbe();
881
- this.startLivenessProbe('page became visible');
916
+ this.startLivenessProbe('page became visible', true);
882
917
  }
883
918
 
884
919
  // Send a ping and arm the grace check. Idempotent while a probe is pending.
885
- private startLivenessProbe(reason: string) {
920
+ // `onReturn` marks the probe a return to the page started: short grace, and
921
+ // an immediate reconnect if it goes unanswered.
922
+ private startLivenessProbe(reason: string, onReturn = false) {
923
+ const grace = onReturn
924
+ ? WhereverClient.VISIBLE_PROBE_GRACE_MS
925
+ : WhereverClient.PROBE_GRACE_MS;
886
926
  if (this.probeTimer || !this.ws || typeof setTimeout !== 'function') return;
887
927
  const probedWs = this.ws;
888
928
  try {
@@ -899,15 +939,17 @@ export class WhereverClient {
899
939
  // background timer throttling (timers batched to ~1/min in a long-hidden
900
940
  // tab) every grace check is late, so the verdict on a dead socket is
901
941
  // deferred until the page is visible again, where noteVisible() restarts
902
- // an unthrottled probe and a dead socket goes ~5 s later. Accepted: a
942
+ // an unthrottled probe and a dead socket goes ~2 s later. Accepted: a
903
943
  // hidden page has no viewer, and a capped retry would reintroduce the
904
944
  // false teardown on thaw this probe exists to prevent.
905
- if (Date.now() - sentAt > 2 * WhereverClient.PROBE_GRACE_MS) {
945
+ // A return probe whose check ran late means the page froze again, so
946
+ // nobody is waiting on it any more: re-probe as an ordinary probe.
947
+ if (Date.now() - sentAt > 2 * grace) {
906
948
  this.startLivenessProbe(reason);
907
949
  return;
908
950
  }
909
- this.tearDownStaleSocket(reason);
910
- }, WhereverClient.PROBE_GRACE_MS);
951
+ this.tearDownStaleSocket(reason, grace, onReturn);
952
+ }, grace);
911
953
  if (this.probeTimer && typeof (this.probeTimer as any).unref === 'function') {
912
954
  (this.probeTimer as any).unref();
913
955
  }
@@ -923,12 +965,12 @@ export class WhereverClient {
923
965
  // The probe went unanswered: treat the socket as dead. Tearing it down
924
966
  // forcibly is what makes a half-open connection recover, since the OS never
925
967
  // produced a FIN/RST to trigger the normal close path.
926
- private tearDownStaleSocket(reason: string) {
968
+ private tearDownStaleSocket(reason: string, graceMs: number, immediate: boolean) {
927
969
  if (!this.ws) return;
928
970
  const streaming = get(this.stateStore).isStreaming;
929
971
  console.warn(
930
972
  `[wherever] relay connection stale: ${reason}; probe unanswered for ` +
931
- `${WhereverClient.PROBE_GRACE_MS}ms; tearing down dead socket and reconnecting`,
973
+ `${graceMs}ms; tearing down dead socket and reconnecting`,
932
974
  );
933
975
  this.stopLivenessWatchdog();
934
976
  const deadWs = this.ws;
@@ -956,7 +998,10 @@ export class WhereverClient {
956
998
  : s.sessionError,
957
999
  isStreaming: false,
958
1000
  }));
959
- this.scheduleReconnect();
1001
+ // A probe started by a return to the page has a user waiting on it: no
1002
+ // backoff, the dead socket is replaced now.
1003
+ if (immediate) this.reconnectNow();
1004
+ else this.scheduleReconnect();
960
1005
  }
961
1006
 
962
1007
  private stopLivenessWatchdog() {
@@ -1039,46 +1084,56 @@ export class WhereverClient {
1039
1084
  this.reconnectTimer = setTimeout(() => {
1040
1085
  this.reconnectTimer = null;
1041
1086
  this.reconnectDelay = Math.min(this.reconnectDelay * 1.5, this.maxReconnectDelay);
1042
- console.info(`[wherever] reconnecting to relay (attempt ${++this.reconnectAttempts})`);
1043
-
1044
- // If we have retried a few times and NEVER once opened the socket, this is
1045
- // almost certainly a rejected handshake, not a flaky network. Surface a
1046
- // concrete, actionable error (the server rejects a bad/missing token with
1047
- // HTTP 401 during the WS upgrade, which the browser reports only as an
1048
- // opaque 1006 close). Keep retrying, but stop looking like a mere network
1049
- // hiccup.
1050
- if (
1051
- !this.hasEverConnected &&
1052
- this.reconnectAttempts >= WhereverClient.HANDSHAKE_FAIL_HINT_AFTER
1053
- ) {
1054
- const scheme = this.config.secure ? 'wss' : 'ws';
1055
- this.stateStore.update(s => ({
1056
- ...s,
1057
- error:
1058
- 'Cannot connect to the wherever server: the connection is being rejected. ' +
1059
- 'This usually means a missing or wrong token, or a wrong host/port/scheme ' +
1060
- `(currently ${scheme}://${this.config.host}:${this.config.port}). ` +
1061
- 'Check the auth token and connection settings.',
1062
- }));
1063
- }
1064
-
1065
- // If we still hold an active session, PRESERVE the cached store across the
1066
- // reconnect. A default connect() resets to a blank store, which wiped
1067
- // activeSessionFile BEFORE onOpen could re-attach to it -- that is what
1068
- // silently detached the frontend from a still-running session (frozen
1069
- // conversation, no re-follow, not even a "connecting"/"loading" hint).
1070
- // Preserving the store keeps the conversation on screen and lets onOpen
1071
- // re-issue session_load from activeSessionFile.
1072
- const preserve = !!get(this.stateStore).activeSessionFile;
1087
+ this.reconnectNow();
1088
+ }, this.reconnectDelay);
1089
+ }
1073
1090
 
1091
+ // Reconnect right away (the body of a backoff timer firing), preserving the
1092
+ // store when a session is active so onOpen rejoins it in place.
1093
+ private reconnectNow() {
1094
+ if (this.reconnectTimer) {
1095
+ clearTimeout(this.reconnectTimer);
1096
+ this.reconnectTimer = null;
1097
+ }
1098
+ console.info(`[wherever] reconnecting to relay (attempt ${++this.reconnectAttempts})`);
1099
+
1100
+ // If we have retried a few times and NEVER once opened the socket, this is
1101
+ // almost certainly a rejected handshake, not a flaky network. Surface a
1102
+ // concrete, actionable error (the server rejects a bad/missing token with
1103
+ // HTTP 401 during the WS upgrade, which the browser reports only as an
1104
+ // opaque 1006 close). Keep retrying, but stop looking like a mere network
1105
+ // hiccup.
1106
+ if (
1107
+ !this.hasEverConnected &&
1108
+ this.reconnectAttempts >= WhereverClient.HANDSHAKE_FAIL_HINT_AFTER
1109
+ ) {
1110
+ const scheme = this.config.secure ? 'wss' : 'ws';
1074
1111
  this.stateStore.update(s => ({
1075
1112
  ...s,
1076
- connecting: true,
1077
- error: 'Reconnecting...',
1113
+ error:
1114
+ 'Cannot connect to the wherever server: the connection is being rejected. ' +
1115
+ 'This usually means a missing or wrong token, or a wrong host/port/scheme ' +
1116
+ `(currently ${scheme}://${this.config.host}:${this.config.port}). ` +
1117
+ 'Check the auth token and connection settings.',
1078
1118
  }));
1119
+ }
1079
1120
 
1080
- this.connect(undefined, preserve);
1081
- }, this.reconnectDelay);
1121
+ // If we still hold an active session, PRESERVE the cached store across the
1122
+ // reconnect. A default connect() resets to a blank store, which wiped
1123
+ // activeSessionFile BEFORE onOpen could re-attach to it -- that is what
1124
+ // silently detached the frontend from a still-running session (frozen
1125
+ // conversation, no re-follow, not even a "connecting"/"loading" hint).
1126
+ // Preserving the store keeps the conversation on screen and lets onOpen
1127
+ // re-issue session_load from activeSessionFile.
1128
+ const preserve = !!get(this.stateStore).activeSessionFile;
1129
+
1130
+ this.stateStore.update(s => ({
1131
+ ...s,
1132
+ connecting: true,
1133
+ error: 'Reconnecting...',
1134
+ }));
1135
+
1136
+ this.connect(undefined, preserve);
1082
1137
  }
1083
1138
 
1084
1139
  private handleMessage(msg: any) {
@@ -1132,6 +1187,7 @@ export class WhereverClient {
1132
1187
  connecting: false,
1133
1188
  clientId: msg.clientId,
1134
1189
  serverVersion: msg.serverVersion ?? null,
1190
+ piVersion: msg.piVersion ?? null,
1135
1191
  error: null,
1136
1192
  }));
1137
1193
  // Uploads held for unknown capabilities can now choose their protocol
package/src/types.ts CHANGED
@@ -227,6 +227,9 @@ export interface WhereverState {
227
227
  // version), as reported in its `connected` message. null until connected, or
228
228
  // when talking to a server old enough not to report it.
229
229
  serverVersion: string | null;
230
+ // Version of the pi SDK that server runs its sessions on. null until
231
+ // connected, or when the server is too old to report it.
232
+ piVersion: string | null;
230
233
  folderConflict: FolderConflictInfo | null;
231
234
  // The active session's working folder is gone from this machine (see
232
235
  // FolderMissingInfo). Non-null implies `readOnly`, and no `session_ready` is
@@ -1,107 +0,0 @@
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
- });