@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/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # @wherever-dev/client
2
2
 
3
+ ## 0.8.2
4
+
5
+ ### Patch Changes
6
+
7
+ - 6f0725a: Coming back to the PWA no longer reconnects slower than a page reload. When the page becomes visible again, the client probes the existing socket with a 2 s grace (was 5 s), replaces a dead socket at once instead of after the reconnect backoff, resets a backoff that grew while the app was in the background, and restarts a handshake still pending after 8 s. A dead socket on return used to cost 7 to 20 s of "Reconnecting...".
8
+
9
+ ## 0.8.1
10
+
11
+ ### Patch Changes
12
+
13
+ - 9573f1d: Publish a README with each npm package (they had none, so npmjs.com showed "No README data found"), and tidy the package metadata: clearer descriptions, keywords, `wherever.dev` as homepage, author, and the changelog in the tarball. `wherever-dev` now declares `engines.node >=22.19.0` (what the bundled pi SDK requires). `@wherever-dev/client` no longer ships its test suite and tsconfig (its `src/` stays, for the sourcemaps).
14
+
3
15
  ## 0.8.0
4
16
 
5
17
  ### Minor Changes
package/README.md ADDED
@@ -0,0 +1,63 @@
1
+ # @wherever-dev/client
2
+
3
+ A framework-agnostic TypeScript client for the [Wherever](https://wherever.dev) server ([`wherever-dev`](https://www.npmjs.com/package/wherever-dev)), which runs [pi coding agent](https://pi.dev) sessions behind a WebSocket API. It is what the Wherever web dashboard and the pi bridge extension ([`@wherever-dev/pi`](https://www.npmjs.com/package/@wherever-dev/pi)) are built on, and it works in browsers and in Node.js.
4
+
5
+ It owns the protocol details: reconnection with backoff, rejoining the session you were in, message history and paging, streaming replies and tool calls, steering, resumable uploads. You get the result as one observable state object.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ npm install @wherever-dev/client
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ ```ts
16
+ import { WhereverClient, type WhereverState } from '@wherever-dev/client';
17
+ import WebSocket from 'ws'; // Node.js only: browsers use their own WebSocket
18
+
19
+ const client = new WhereverClient({
20
+ host: '127.0.0.1',
21
+ port: 31415,
22
+ token: process.env.WHEREVER_TOKEN, // if the server requires one
23
+ secure: true, // wss:// (the default)
24
+ WebSocketCtor: WebSocket,
25
+ });
26
+
27
+ // Everything the client knows lives in ONE store: connection, active session,
28
+ // messages, streaming state, errors. subscribe() returns an unsubscribe function.
29
+ function until(ready: (state: WhereverState) => boolean): Promise<WhereverState> {
30
+ return new Promise((resolve) => {
31
+ let unsubscribe = () => {};
32
+ let done = false;
33
+ unsubscribe = client.stateStore.subscribe((state) => {
34
+ if (done || !ready(state)) return;
35
+ done = true;
36
+ queueMicrotask(() => unsubscribe());
37
+ resolve(state);
38
+ });
39
+ });
40
+ }
41
+
42
+ client.connect();
43
+ await until((s) => s.connected); // actions sent before this are dropped
44
+
45
+ client.createSession('/path/to/project'); // or joinSession(sessionFile) for an existing one
46
+ await until((s) => s.activeSessionFile !== null);
47
+
48
+ client.sendMessage('Summarise the README');
49
+ const done = await until((s) => !s.isStreaming && s.messages.some((m) => m.role === 'assistant'));
50
+ console.log(done.messages.filter((m) => m.role === 'assistant').at(-1)?.content);
51
+
52
+ client.disconnect();
53
+ ```
54
+
55
+ Other actions include `abort()`, `changeModel('provider:model')`, `forkSession()`, `reloadSession()`, `loadMoreHistory()`, `leaveSession()` and `disconnect()`; see the type declarations for the full API.
56
+
57
+ When you pass your own `WebSocketCtor` with `secure: true`, the client accepts the server's self-signed certificate (the default `wherever start` setup). Use a trusted certificate for anything exposed beyond a private network.
58
+
59
+ The client follows the server's protocol, so keep it on the same release line as the server it talks to.
60
+
61
+ ## License
62
+
63
+ [AGPL-3.0-only](https://github.com/wighawag/wherever/blob/main/LICENSE)
package/dist/client.d.ts CHANGED
@@ -52,7 +52,9 @@ export declare class WhereverClient {
52
52
  private createWatchdog;
53
53
  private static readonly CREATE_WATCHDOG_MS;
54
54
  private reconnectAttempts;
55
+ private static readonly MIN_RECONNECT_DELAY;
55
56
  private reconnectDelay;
57
+ private socketStartedAt;
56
58
  private maxReconnectDelay;
57
59
  private hasEverConnected;
58
60
  private static readonly HANDSHAKE_FAIL_HINT_AFTER;
@@ -63,6 +65,8 @@ export declare class WhereverClient {
63
65
  private static readonly TURN_STALL_MS;
64
66
  private static readonly HEARTBEAT_MS;
65
67
  private static readonly PROBE_GRACE_MS;
68
+ private static readonly VISIBLE_PROBE_GRACE_MS;
69
+ private static readonly STALLED_HANDSHAKE_MS;
66
70
  private probeTimer;
67
71
  private lastLivenessTickAt;
68
72
  private isInitialConnect;
@@ -102,6 +106,7 @@ export declare class WhereverClient {
102
106
  private armCreateWatchdog;
103
107
  private clearCreateWatchdog;
104
108
  private scheduleReconnect;
109
+ private reconnectNow;
105
110
  private handleMessage;
106
111
  /**
107
112
  * True when an errored tool result is the product of a USER ABORT (e.g. the
package/dist/client.js CHANGED
@@ -132,6 +132,7 @@ const defaultState = {
132
132
  messages: [],
133
133
  clientId: null,
134
134
  serverVersion: null,
135
+ piVersion: null,
135
136
  folderConflict: null,
136
137
  folderMissing: null,
137
138
  restore: null,
@@ -186,7 +187,11 @@ export class WhereverClient {
186
187
  createWatchdog = null;
187
188
  static CREATE_WATCHDOG_MS = 25_000;
188
189
  reconnectAttempts = 0;
189
- reconnectDelay = 2000;
190
+ static MIN_RECONNECT_DELAY = 2000;
191
+ reconnectDelay = WhereverClient.MIN_RECONNECT_DELAY;
192
+ // Wall-clock time the current socket was created, so a return to the page can
193
+ // tell a handshake that has hung across a freeze from one just started.
194
+ socketStartedAt = 0;
190
195
  maxReconnectDelay = 15000;
191
196
  // Whether the socket has EVER opened successfully since construction. Repeated
192
197
  // closes with zero successful opens almost always mean a rejected handshake
@@ -222,6 +227,20 @@ export class WhereverClient {
222
227
  // the timers fire BEFORE the frames queued during the freeze are dispatched,
223
228
  // so the raw silence verdict is routinely false on a phone.
224
229
  static PROBE_GRACE_MS = 5_000;
230
+ // The probe a return to the page starts (noteVisible) uses a shorter grace.
231
+ // The long grace above exists because timers that came due DURING a freeze
232
+ // fire before the frames queued during it; a probe started from the
233
+ // visibility event is a fresh timer, so the queued frames (and a healthy
234
+ // socket's pong, one round trip later) are dispatched well before it fires.
235
+ // Waiting the full 5 s there, then the reconnect backoff on top, is what made
236
+ // coming back to the PWA slower than a reload.
237
+ static VISIBLE_PROBE_GRACE_MS = 2_000;
238
+ // A socket still CONNECTING this long when the page becomes visible is
239
+ // treated as a handshake that hung (typically started before a freeze,
240
+ // against a network that was gone) and restarted. Well above an honest slow
241
+ // mobile TLS handshake, so a return never throws away one that is about to
242
+ // complete.
243
+ static STALLED_HANDSHAKE_MS = 8_000;
225
244
  // The pending probe's grace timer, and the socket it was started on. Cleared
226
245
  // by any inbound frame, by stopLivenessWatchdog (every socket change), and
227
246
  // ignored if the socket it belongs to is no longer current.
@@ -382,6 +401,7 @@ export class WhereverClient {
382
401
  }
383
402
  // A new socket: its capabilities are unknown until its `connected` frame.
384
403
  this.socketCapabilities = null;
404
+ this.socketStartedAt = Date.now();
385
405
  try {
386
406
  const wsOptions = this.config.secure && this.config.WebSocketCtor ? { rejectUnauthorized: false } : undefined;
387
407
  this.ws = wsOptions ? new WebSocketImpl(wsUrl, wsOptions) : new WebSocketImpl(wsUrl);
@@ -404,7 +424,7 @@ export class WhereverClient {
404
424
  }
405
425
  this.hasEverConnected = true;
406
426
  this.reconnectAttempts = 0;
407
- this.reconnectDelay = 2000;
427
+ this.reconnectDelay = WhereverClient.MIN_RECONNECT_DELAY;
408
428
  this.isInitialConnect = false;
409
429
  this.startLivenessWatchdog();
410
430
  this.stateStore.update(s => ({
@@ -735,20 +755,41 @@ export class WhereverClient {
735
755
  // socket is OPEN and watched, probe it right away instead of waiting for the
736
756
  // next tick, and reset the stale baseline so the time the page spent frozen is
737
757
  // not counted as silence (the probe decides whether the socket is alive).
738
- // A no-op otherwise: on a CONNECTING socket the ping would be dropped by
739
- // send() and the grace check would tear down a socket still handshaking.
758
+ //
759
+ // The user is looking at the page, so a return must never pay the slow paths
760
+ // meant for an unattended client: the probe uses the short
761
+ // VISIBLE_PROBE_GRACE_MS, a socket it condemns is replaced at once instead of
762
+ // after the reconnect backoff, and the backoff grown while hidden is reset.
763
+ // A socket still CONNECTING after STALLED_HANDSHAKE_MS is restarted.
764
+ // With no socket at all this only resets the backoff: the page follows up
765
+ // with resume() / connect(), which connect at once.
740
766
  noteVisible() {
767
+ this.reconnectDelay = WhereverClient.MIN_RECONNECT_DELAY;
741
768
  const ws = this.ws;
742
- if (!ws || ws.readyState !== 1 /* OPEN */ || !this.livenessTimer)
769
+ if (!ws)
770
+ return;
771
+ if (ws.readyState === 0 /* CONNECTING */) {
772
+ if (Date.now() - this.socketStartedAt > WhereverClient.STALLED_HANDSHAKE_MS) {
773
+ console.info('[wherever] handshake stalled; restarting it');
774
+ this.reconnectNow();
775
+ }
776
+ return;
777
+ }
778
+ if (ws.readyState !== 1 /* OPEN */ || !this.livenessTimer)
743
779
  return;
744
780
  this.lastInboundAt = Date.now();
745
781
  this.lastLivenessTickAt = this.lastInboundAt;
746
782
  // Restart any pending probe: its grace may have been eaten by the freeze.
747
783
  this.cancelLivenessProbe();
748
- this.startLivenessProbe('page became visible');
784
+ this.startLivenessProbe('page became visible', true);
749
785
  }
750
786
  // Send a ping and arm the grace check. Idempotent while a probe is pending.
751
- startLivenessProbe(reason) {
787
+ // `onReturn` marks the probe a return to the page started: short grace, and
788
+ // an immediate reconnect if it goes unanswered.
789
+ startLivenessProbe(reason, onReturn = false) {
790
+ const grace = onReturn
791
+ ? WhereverClient.VISIBLE_PROBE_GRACE_MS
792
+ : WhereverClient.PROBE_GRACE_MS;
752
793
  if (this.probeTimer || !this.ws || typeof setTimeout !== 'function')
753
794
  return;
754
795
  const probedWs = this.ws;
@@ -768,15 +809,17 @@ export class WhereverClient {
768
809
  // background timer throttling (timers batched to ~1/min in a long-hidden
769
810
  // tab) every grace check is late, so the verdict on a dead socket is
770
811
  // deferred until the page is visible again, where noteVisible() restarts
771
- // an unthrottled probe and a dead socket goes ~5 s later. Accepted: a
812
+ // an unthrottled probe and a dead socket goes ~2 s later. Accepted: a
772
813
  // hidden page has no viewer, and a capped retry would reintroduce the
773
814
  // false teardown on thaw this probe exists to prevent.
774
- if (Date.now() - sentAt > 2 * WhereverClient.PROBE_GRACE_MS) {
815
+ // A return probe whose check ran late means the page froze again, so
816
+ // nobody is waiting on it any more: re-probe as an ordinary probe.
817
+ if (Date.now() - sentAt > 2 * grace) {
775
818
  this.startLivenessProbe(reason);
776
819
  return;
777
820
  }
778
- this.tearDownStaleSocket(reason);
779
- }, WhereverClient.PROBE_GRACE_MS);
821
+ this.tearDownStaleSocket(reason, grace, onReturn);
822
+ }, grace);
780
823
  if (this.probeTimer && typeof this.probeTimer.unref === 'function') {
781
824
  this.probeTimer.unref();
782
825
  }
@@ -790,12 +833,12 @@ export class WhereverClient {
790
833
  // The probe went unanswered: treat the socket as dead. Tearing it down
791
834
  // forcibly is what makes a half-open connection recover, since the OS never
792
835
  // produced a FIN/RST to trigger the normal close path.
793
- tearDownStaleSocket(reason) {
836
+ tearDownStaleSocket(reason, graceMs, immediate) {
794
837
  if (!this.ws)
795
838
  return;
796
839
  const streaming = get(this.stateStore).isStreaming;
797
840
  console.warn(`[wherever] relay connection stale: ${reason}; probe unanswered for ` +
798
- `${WhereverClient.PROBE_GRACE_MS}ms; tearing down dead socket and reconnecting`);
841
+ `${graceMs}ms; tearing down dead socket and reconnecting`);
799
842
  this.stopLivenessWatchdog();
800
843
  const deadWs = this.ws;
801
844
  this.ws = null;
@@ -824,7 +867,12 @@ export class WhereverClient {
824
867
  : s.sessionError,
825
868
  isStreaming: false,
826
869
  }));
827
- this.scheduleReconnect();
870
+ // A probe started by a return to the page has a user waiting on it: no
871
+ // backoff, the dead socket is replaced now.
872
+ if (immediate)
873
+ this.reconnectNow();
874
+ else
875
+ this.scheduleReconnect();
828
876
  }
829
877
  stopLivenessWatchdog() {
830
878
  this.cancelLivenessProbe();
@@ -901,39 +949,48 @@ export class WhereverClient {
901
949
  this.reconnectTimer = setTimeout(() => {
902
950
  this.reconnectTimer = null;
903
951
  this.reconnectDelay = Math.min(this.reconnectDelay * 1.5, this.maxReconnectDelay);
904
- console.info(`[wherever] reconnecting to relay (attempt ${++this.reconnectAttempts})`);
905
- // If we have retried a few times and NEVER once opened the socket, this is
906
- // almost certainly a rejected handshake, not a flaky network. Surface a
907
- // concrete, actionable error (the server rejects a bad/missing token with
908
- // HTTP 401 during the WS upgrade, which the browser reports only as an
909
- // opaque 1006 close). Keep retrying, but stop looking like a mere network
910
- // hiccup.
911
- if (!this.hasEverConnected &&
912
- this.reconnectAttempts >= WhereverClient.HANDSHAKE_FAIL_HINT_AFTER) {
913
- const scheme = this.config.secure ? 'wss' : 'ws';
914
- this.stateStore.update(s => ({
915
- ...s,
916
- error: 'Cannot connect to the wherever server: the connection is being rejected. ' +
917
- 'This usually means a missing or wrong token, or a wrong host/port/scheme ' +
918
- `(currently ${scheme}://${this.config.host}:${this.config.port}). ` +
919
- 'Check the auth token and connection settings.',
920
- }));
921
- }
922
- // If we still hold an active session, PRESERVE the cached store across the
923
- // reconnect. A default connect() resets to a blank store, which wiped
924
- // activeSessionFile BEFORE onOpen could re-attach to it -- that is what
925
- // silently detached the frontend from a still-running session (frozen
926
- // conversation, no re-follow, not even a "connecting"/"loading" hint).
927
- // Preserving the store keeps the conversation on screen and lets onOpen
928
- // re-issue session_load from activeSessionFile.
929
- const preserve = !!get(this.stateStore).activeSessionFile;
952
+ this.reconnectNow();
953
+ }, this.reconnectDelay);
954
+ }
955
+ // Reconnect right away (the body of a backoff timer firing), preserving the
956
+ // store when a session is active so onOpen rejoins it in place.
957
+ reconnectNow() {
958
+ if (this.reconnectTimer) {
959
+ clearTimeout(this.reconnectTimer);
960
+ this.reconnectTimer = null;
961
+ }
962
+ console.info(`[wherever] reconnecting to relay (attempt ${++this.reconnectAttempts})`);
963
+ // If we have retried a few times and NEVER once opened the socket, this is
964
+ // almost certainly a rejected handshake, not a flaky network. Surface a
965
+ // concrete, actionable error (the server rejects a bad/missing token with
966
+ // HTTP 401 during the WS upgrade, which the browser reports only as an
967
+ // opaque 1006 close). Keep retrying, but stop looking like a mere network
968
+ // hiccup.
969
+ if (!this.hasEverConnected &&
970
+ this.reconnectAttempts >= WhereverClient.HANDSHAKE_FAIL_HINT_AFTER) {
971
+ const scheme = this.config.secure ? 'wss' : 'ws';
930
972
  this.stateStore.update(s => ({
931
973
  ...s,
932
- connecting: true,
933
- error: 'Reconnecting...',
974
+ error: 'Cannot connect to the wherever server: the connection is being rejected. ' +
975
+ 'This usually means a missing or wrong token, or a wrong host/port/scheme ' +
976
+ `(currently ${scheme}://${this.config.host}:${this.config.port}). ` +
977
+ 'Check the auth token and connection settings.',
934
978
  }));
935
- this.connect(undefined, preserve);
936
- }, this.reconnectDelay);
979
+ }
980
+ // If we still hold an active session, PRESERVE the cached store across the
981
+ // reconnect. A default connect() resets to a blank store, which wiped
982
+ // activeSessionFile BEFORE onOpen could re-attach to it -- that is what
983
+ // silently detached the frontend from a still-running session (frozen
984
+ // conversation, no re-follow, not even a "connecting"/"loading" hint).
985
+ // Preserving the store keeps the conversation on screen and lets onOpen
986
+ // re-issue session_load from activeSessionFile.
987
+ const preserve = !!get(this.stateStore).activeSessionFile;
988
+ this.stateStore.update(s => ({
989
+ ...s,
990
+ connecting: true,
991
+ error: 'Reconnecting...',
992
+ }));
993
+ this.connect(undefined, preserve);
937
994
  }
938
995
  handleMessage(msg) {
939
996
  for (const listener of this.listeners) {
@@ -985,6 +1042,7 @@ export class WhereverClient {
985
1042
  connecting: false,
986
1043
  clientId: msg.clientId,
987
1044
  serverVersion: msg.serverVersion ?? null,
1045
+ piVersion: msg.piVersion ?? null,
988
1046
  error: null,
989
1047
  }));
990
1048
  // Uploads held for unknown capabilities can now choose their protocol