@wherever-dev/client 0.7.0 → 0.8.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.
Files changed (35) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README.md +63 -0
  3. package/dist/client.d.ts +93 -2
  4. package/dist/client.js +960 -63
  5. package/dist/client.js.map +1 -1
  6. package/dist/types.d.ts +69 -0
  7. package/dist/types.js.map +1 -1
  8. package/package.json +23 -3
  9. package/src/client.ts +1031 -63
  10. package/src/types.ts +97 -0
  11. package/test/agent-pending.test.ts +0 -107
  12. package/test/conversation-mode-flag.test.ts +0 -111
  13. package/test/creating-session-watchdog.test.ts +0 -82
  14. package/test/folder-conflict-read-only.test.ts +0 -145
  15. package/test/folder-missing-read-only.test.ts +0 -114
  16. package/test/harness.ts +0 -97
  17. package/test/message-delivery-confirmation.test.ts +0 -320
  18. package/test/mid-stream-steer.test.ts +0 -91
  19. package/test/new-session-clone-progress.test.ts +0 -263
  20. package/test/optimistic-force-command.test.ts +0 -127
  21. package/test/queued-steer-restored.test.ts +0 -175
  22. package/test/reconnect-rejoins-session.test.ts +0 -136
  23. package/test/restore-panel.test.ts +0 -324
  24. package/test/resume-keeps-session.test.ts +0 -118
  25. package/test/session-load-by-id.test.ts +0 -100
  26. package/test/session-reload.test.ts +0 -82
  27. package/test/skills-autocomplete.test.ts +0 -113
  28. package/test/steer-queue-cancel.test.ts +0 -130
  29. package/test/superseded-connection-key.test.ts +0 -70
  30. package/test/superseded-session-load.test.ts +0 -180
  31. package/test/tool-aborted-render.test.ts +0 -170
  32. package/test/tool-duration-history.test.ts +0 -93
  33. package/test/tool-duration.test.ts +0 -86
  34. package/test/tool-interrupted-history.test.ts +0 -294
  35. package/tsconfig.json +0 -16
package/CHANGELOG.md CHANGED
@@ -1,5 +1,30 @@
1
1
  # @wherever-dev/client
2
2
 
3
+ ## 0.8.1
4
+
5
+ ### Patch Changes
6
+
7
+ - 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).
8
+
9
+ ## 0.8.0
10
+
11
+ ### Minor Changes
12
+
13
+ - 18696b8: Uploads over the WebSocket are now resumable and report real progress when the server supports it (`upload.v1`). The client sends the file as binary chunks, counts progress only from the server's acknowledgements, pauses on a dropped connection and, after the reconnect rejoins the session, continues from where the server got to instead of starting over. Cancelling an upload now tells the server to drop the partial file. Against an older server the client falls back to the previous single-frame upload, with the same limits as before (72 MB, three attempts). A file the phone can no longer read fails with "The file is no longer readable, pick it again".
14
+
15
+ Breaking for `@wherever-dev/client`: `uploadFileViaWebSocket(sessionId, filename, source, options)` now takes a byte source (`{size, read(offset, length)}`) instead of a base64 string, and gains `options.onProgress` and `options.mime`. The client also exposes `uploadsStore` (progress per upload id) and `forgetUpload(id)`. In the web app, `uploadFile()` accepts an `onProgress` callback that reports `{acked, size, state, error?}` for every upload method.
16
+
17
+ ### Patch Changes
18
+
19
+ - bdafbcc: Client groundwork for showing a cached conversation instantly after a reload. `@wherever-dev/client` now exports `serverKey(config)` (a synchronous `host:port` plus token-hash identity) and `WhereverClient.hydrateCachedSession(snapshot)`, which paints a cached conversation before the socket is up and lets the normal reconnect rejoin replace it with the server's history. The store gains `serverKey` (the server that actually delivered the active session) and `historyAuthoritative` (gates `loadMoreHistory()` until the real history has arrived). A reconnect after the host, port or token were edited no longer preserves or rejoins the previous server's session. When the server refuses the load of a hydrated session outright, the client clears it and emits a synthesized `hydration_rejected` event to `onMessage` listeners. `resume()` no longer arms a load watchdog that was immediately cleared.
20
+ - 338a3c0: Returning to the app after the file picker, the camera or a short app switch no longer tears down a healthy connection and resyncs the session. The client's liveness watchdog now treats a silent socket as suspect, not dead: it sends a ping and waits a 5 s grace period, and only reconnects if nothing at all arrives. The page also probes the socket on every return to visibility (`client.noteVisible()`), and a detected freeze (a wall-clock jump between watchdog ticks) triggers the same probe. A genuinely dead socket is still torn down and reconnected, about 5 s later than before.
21
+ - 3da6573: Mobile resilience fixes for loading sessions, reconnecting and uploading files:
22
+ - Opening a session no longer flashes "New Session Started" while its history is still arriving. A "Loading conversation..." spinner is shown until the history lands.
23
+ - While disconnected or resyncing, the composer stays editable: you can keep reading, typing and attaching. Only sending (Send/Steer, Enter, dictation auto-send) waits for the connection and the resync.
24
+ - A WebSocket file upload is no longer tied to the socket it started on. If the socket drops (e.g. the file picker or camera backgrounds the page on mobile), the upload waits and is sent again automatically once the session has rejoined (after the server re-applies its read-only verdict). The chip shows "waiting for connection" in the meantime. Uploads always settle: they used to hang forever, leaving Send disabled. They now complete, fail, or time out after 10 minutes of waiting for a connection (time spent actually transferring does not count).
25
+ - Removing an attachment chip cancels its pending upload, and no longer updates the wrong chip.
26
+ - Uploads that waited for an unreachable server now time out after 10 minutes as intended (the clock used to restart on every reconnect attempt). An upload whose connection drops during the transfer on 3 consecutive attempts now fails with a clear message instead of retrying forever, and files too large for a single WebSocket frame (over 72 MB) are refused before being read.
27
+
3
28
  ## 0.7.0
4
29
 
5
30
  ### 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
@@ -1,5 +1,5 @@
1
1
  import { type Writable } from "sveltore";
2
- import { type WhereverState } from "./types.js";
2
+ import { type HydrationSnapshot, type UploadByteSource, type UploadOptions, type UploadProgress, type WhereverState } from "./types.js";
3
3
  /**
4
4
  * Per-send options for a user message.
5
5
  *
@@ -23,6 +23,23 @@ export interface WhereverClientConfig {
23
23
  clientKey?: string;
24
24
  onClientKeyChange?: (key: string) => void;
25
25
  }
26
+ /** The capability a server advertises in `connected` for chunked uploads. */
27
+ export declare const UPLOAD_CAPABILITY = "upload.v1";
28
+ /** `[u8 kind=1][u8 version=1][u8 idLen][uploadId ascii][u64 offset BE][payload]` */
29
+ export declare function encodeChunkFrame(uploadId: string, offset: number, payload: Uint8Array): Uint8Array;
30
+ /**
31
+ * The identity of the server a config points at: `host:port#<fnv1a(token)>`.
32
+ * Two configured servers (or one server with a rotated token) never share a
33
+ * key, so the web's conversation cache can never show one server's
34
+ * conversation for another (ADR 0013).
35
+ *
36
+ * Synchronous and pure on purpose: `connect()` is synchronous and must compare
37
+ * it with the stamp before deciding whether to preserve the store, and
38
+ * `crypto.subtle` is both async and missing on plain-http LAN origins. The
39
+ * scheme (`secure`) is deliberately NOT part of the key: ws vs wss to the same
40
+ * host:port is the same server.
41
+ */
42
+ export declare function serverKey(config: Pick<WhereverClientConfig, 'host' | 'port' | 'token'>): string;
26
43
  export declare class WhereverClient {
27
44
  private ws;
28
45
  private config;
@@ -45,13 +62,25 @@ export declare class WhereverClient {
45
62
  private static readonly STALE_SOCKET_MS;
46
63
  private static readonly TURN_STALL_MS;
47
64
  private static readonly HEARTBEAT_MS;
65
+ private static readonly PROBE_GRACE_MS;
66
+ private probeTimer;
67
+ private lastLivenessTickAt;
48
68
  private isInitialConnect;
49
69
  private resumeSessionFile;
50
70
  private resumeCwd?;
51
71
  private resumeModel?;
52
72
  private pendingLoadFile;
73
+ private socketServerKey;
74
+ private hydratedFile;
53
75
  private listeners;
54
76
  private pendingUploads;
77
+ uploadsStore: Writable<Record<string, UploadProgress>>;
78
+ private socketCapabilities;
79
+ private static readonly MAX_UPLOAD_SENDS;
80
+ private static readonly MAX_UPLOAD_BASE64_CHARS;
81
+ private static readonly MAX_LEGACY_UPLOAD_BYTES;
82
+ private static readonly UPLOAD_TIMEOUT_MS;
83
+ private uploadsHeldForRejoin;
55
84
  private confirmTimers;
56
85
  private static readonly CONFIRM_MS;
57
86
  private static readonly PENDING_PREFIX;
@@ -63,6 +92,10 @@ export declare class WhereverClient {
63
92
  hasSuspendedSession(): boolean;
64
93
  hasActiveSession(): boolean;
65
94
  private startLivenessWatchdog;
95
+ noteVisible(): void;
96
+ private startLivenessProbe;
97
+ private cancelLivenessProbe;
98
+ private tearDownStaleSocket;
66
99
  private stopLivenessWatchdog;
67
100
  private armLoadWatchdog;
68
101
  private clearLoadWatchdog;
@@ -119,6 +152,25 @@ export declare class WhereverClient {
119
152
  * -- the one still in flight when the user switched sessions.
120
153
  */
121
154
  private withRestore;
155
+ /**
156
+ * Paint a conversation from the web's on-device cache before the socket is up
157
+ * (ADR 0013), so a reload after the OS killed the PWA shows it at once. Call
158
+ * it, then `connect(cfg, true)`: onOpen's normal rejoin issues the
159
+ * `session_load` and its `message_history` replaces the cached messages.
160
+ *
161
+ * A no-op unless the client holds nothing that could be clobbered: no active
162
+ * session, no load in flight, not connected. The painted session is
163
+ * `resyncing` (sending blocked) and NOT `historyAuthoritative`. `agentPending`,
164
+ * `folderConflict`, `sudoPrompt` and `readOnly` stay at their defaults: they
165
+ * are verdicts the server re-states on the rejoin. `pendingLoadFile` is NOT
166
+ * set here (the rejoin sets it when it actually sends the load).
167
+ *
168
+ * Delivery-tagged user messages in the snapshot are dropped: undelivered
169
+ * outbound messages are recovered only from localStorage on the history
170
+ * reply (`loadPersistedPending`), so a cached copy would double-surface them.
171
+ */
172
+ hydrateCachedSession(snapshot: HydrationSnapshot): void;
173
+ private rejectHydration;
122
174
  joinSession(sessionFile: string, cwd?: string, model?: string): void;
123
175
  switchSession(sessionFile: string, cwd?: string, model?: string): void;
124
176
  forkSession(sessionId: string, entryId: string): boolean;
@@ -160,10 +212,49 @@ export declare class WhereverClient {
160
212
  changeModel(model: string): void;
161
213
  setConfig(updates: Partial<WhereverClientConfig>): void;
162
214
  onMessage(cb: (msg: any) => void): () => void;
163
- uploadFileViaWebSocket(sessionId: string, filename: string, base64Data: string): Promise<{
215
+ /**
216
+ * Upload a file over the WebSocket. Resolves with the server's saved path;
217
+ * rejects on failure (an `Error`, with `code: 'not_readable'` when the byte
218
+ * source can no longer be read) or with "Upload cancelled" when
219
+ * `options.signal` aborts. Progress (`{acked, size, state, error?}`) goes to
220
+ * `options.onProgress` and to `uploadsStore`.
221
+ *
222
+ * The protocol is chosen when the upload is SENT, from that socket's
223
+ * `connected.capabilities`: chunked (`upload.v1`) when advertised, else the
224
+ * legacy base64 `file_upload` frame (see PendingUpload). The legacy path
225
+ * refuses files over 72 MiB from `source.size`, before reading anything.
226
+ */
227
+ uploadFileViaWebSocket(sessionId: string, filename: string, source: UploadByteSource, options?: UploadOptions): Promise<{
164
228
  savedPath: string;
165
229
  filename: string;
166
230
  }>;
231
+ pendingUploadCount(): number;
232
+ /** Drop a SETTLED upload's entry from uploadsStore (in-flight ones stay). */
233
+ forgetUpload(uploadId: string): void;
234
+ private trySendUpload;
235
+ private sendLegacyUpload;
236
+ private prepareLegacyFrame;
237
+ private readLegacyBase64;
238
+ private beginChunkedUpload;
239
+ private handleUploadOffset;
240
+ private uploadWindow;
241
+ private pumpUpload;
242
+ private sendBinary;
243
+ private reportUpload;
244
+ private completeUpload;
245
+ private failUpload;
246
+ private abortUpload;
247
+ private isUploadOnWire;
248
+ private uploadsLostSocket;
249
+ private failUnsentUploads;
250
+ private failHeldUploads;
251
+ private abandonUnsentUploads;
252
+ private ensureUploadTimer;
253
+ private stopUploadTimer;
254
+ private armUploadTimer;
255
+ private takePendingUpload;
256
+ private resendPendingUploads;
257
+ private rejectPendingUploads;
167
258
  private generateId;
168
259
  getIsConnected(): any;
169
260
  }