@wherever-dev/client 0.8.2 → 0.9.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,23 @@
1
1
  # @wherever-dev/client
2
2
 
3
+ ## 0.9.1
4
+
5
+ ### Patch Changes
6
+
7
+ - 58bb85d: Switching session while the previous one is still reconnecting no longer snaps back to it. Coming back to the PWA reconnects and rejoins the session that was open; if the user opened another session or created a new one before that finished, the rejoin landed afterwards and switched the view back. A switch is now the newer intent and cancels the rejoin: a session load or create requested while the socket is still opening is sent once it opens (instead of the rejoin, and it used to be lost), the late reply of an abandoned load is dropped (a create in flight used to accept it as its own), and the page no longer auto-joins a URL hash still naming the left session while a create is in flight or after leaving while disconnected.
8
+
9
+ ## 0.9.0
10
+
11
+ ### Minor Changes
12
+
13
+ - 016c887: Wherever is now usable on a slow connection. Before, opening or reconnecting to a session whose recent history held a large tool image (a `read` on a screenshot) could loop forever on a weak link: the history was one multi-MB WebSocket frame, the browser only delivers a frame once it has fully arrived, and the client's liveness watchdog took the long silence for a dead socket, reconnected and asked for the same history again. Measured at 30 KB/s with a 3 MB image: the history never painted; now it paints in about 2 s.
14
+ - Large server frames are split into small chunks for clients that ask (`frames=chunk.v1`), so a big transfer keeps proving the socket alive and no longer times out the session load.
15
+ - History tool images larger than 16 KB are sent by reference for clients that ask (`imageRefs=1`; `WhereverClient` gains an `imageRefs` option, off by default, which the web app turns on) and loaded lazily from the new `GET /session/tool-image`, which the browser caches for good. A reconnect now re-sends text only, and the on-device conversation cache keeps those images.
16
+ - WebSocket frames are compressed (`permessage-deflate`), and the web app's JS/CSS/HTML are served with brotli or gzip.
17
+ - Streamed reply, thinking and tool-output deltas are merged into about one frame per 50 ms instead of one frame per token (order unchanged, nothing dropped), and a client that falls behind catches up in a few large frames instead of thousands of tiny ones.
18
+
19
+ Chunking and images by reference are opt-in per connection, so an older cached web build or client keeps the previous behaviour; delta merging is transparent to every client.
20
+
3
21
  ## 0.8.2
4
22
 
5
23
  ### Patch Changes
package/dist/client.d.ts CHANGED
@@ -22,6 +22,7 @@ export interface WhereverClientConfig {
22
22
  hideTools?: boolean;
23
23
  clientKey?: string;
24
24
  onClientKeyChange?: (key: string) => void;
25
+ imageRefs?: boolean;
25
26
  }
26
27
  /** The capability a server advertises in `connected` for chunked uploads. */
27
28
  export declare const UPLOAD_CAPABILITY = "upload.v1";
@@ -74,6 +75,8 @@ export declare class WhereverClient {
74
75
  private resumeCwd?;
75
76
  private resumeModel?;
76
77
  private pendingLoadFile;
78
+ private queuedSessionRequest;
79
+ private abandonedSessions;
77
80
  private socketServerKey;
78
81
  private hydratedFile;
79
82
  private listeners;
@@ -177,6 +180,8 @@ export declare class WhereverClient {
177
180
  hydrateCachedSession(snapshot: HydrationSnapshot): void;
178
181
  private rejectHydration;
179
182
  joinSession(sessionFile: string, cwd?: string, model?: string): void;
183
+ private abandonPendingLoad;
184
+ private sendSessionLoad;
180
185
  switchSession(sessionFile: string, cwd?: string, model?: string): void;
181
186
  forkSession(sessionId: string, entryId: string): boolean;
182
187
  createSession(cwd: string, model?: string, gitInit?: boolean, createRemote?: boolean, repoVisibility?: 'private' | 'public', cloneRemote?: boolean): void;
package/dist/client.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { writable, get } from "sveltore";
2
2
  import { skillInvocationIdentity, } from "./types.js";
3
+ import { FrameReassembler, FRAME_CHUNK_PARAM, FRAME_CHUNK_VERSION } from "./frame-chunks.js";
3
4
  // Per-instance fallback identity: stable for the lifetime of this client object,
4
5
  // which is exactly the lifetime across which reconnects happen.
5
6
  function generateClientKey() {
@@ -266,6 +267,26 @@ export class WhereverClient {
266
267
  // null means "accept any" (e.g. session_new, whose target file is not known
267
268
  // until the reply). The latest tap always wins.
268
269
  pendingLoadFile = null;
270
+ // A session request (load or create) the user made while the socket was not
271
+ // open, so its frame could not be sent. It is the user's newest intent and so
272
+ // supersedes the automatic rejoin: onOpen replays it INSTEAD of rejoining the
273
+ // previously-active session. Without this, switching away from a session that
274
+ // was still reconnecting (PWA brought back to the foreground) lost the switch
275
+ // and the rejoin pulled the user back to the old session. Cleared by a leave,
276
+ // a full disconnect, a server-key wipe, the request's watchdog expiring
277
+ // while still armed, or the replay itself. A socket that closes before
278
+ // opening disarms that watchdog without dropping the request, so it is then
279
+ // replayed on a later socket: it is still the user's latest intent.
280
+ queuedSessionRequest = null;
281
+ // Session files and ids of loads the user moved away from while their reply
282
+ // was still on the wire on THIS socket (a rejoin, a slow load). Their late
283
+ // session_created / message_history are dropped even when nothing else would
284
+ // reject them: a session_new in flight accepts any session_created (its file
285
+ // is unknown until the reply), so a late rejoin reply used to be taken for the
286
+ // new session's and switch the view back. Reset on every new socket (the old
287
+ // socket's replies can no longer arrive), and an entry is removed when the
288
+ // user loads that session again.
289
+ abandonedSessions = new Set();
269
290
  // serverKey(config) of the socket currently open (captured by connect() next
270
291
  // to the socket it opens). session_created stamps it on the store, so the
271
292
  // stamp names the server that actually DELIVERED the session even if the
@@ -366,6 +387,7 @@ export class WhereverClient {
366
387
  this.resumeModel = undefined;
367
388
  this.pendingLoadFile = null;
368
389
  this.hydratedFile = null;
390
+ this.queuedSessionRequest = null;
369
391
  }
370
392
  this.socketServerKey = key;
371
393
  // preserveState keeps the cached session/messages in the store across a
@@ -389,6 +411,15 @@ export class WhereverClient {
389
411
  if (this.config.token)
390
412
  params.push(`token=${encodeURIComponent(this.config.token)}`);
391
413
  params.push(`clientKey=${encodeURIComponent(this.clientKey)}`);
414
+ // Ask the server to split large frames (frame-chunks.ts): a multi-MB history
415
+ // arriving as ONE frame over a slow link looked like a dead socket to the
416
+ // liveness watchdog, which tore it down and looped forever.
417
+ params.push(`${FRAME_CHUNK_PARAM}=${FRAME_CHUNK_VERSION}`);
418
+ // History tool images by reference (fetched lazily, cached by the browser)
419
+ // rather than as base64 re-sent on every load and reconnect. Opt-in: the
420
+ // caller must then render images that have no `data`.
421
+ if (this.config.imageRefs)
422
+ params.push('imageRefs=1');
392
423
  const wsUrl = `${protocol}://${host}:${this.config.port}/ws?${params.join('&')}`;
393
424
  const WebSocketImpl = this.config.WebSocketCtor || (typeof globalThis !== 'undefined' ? globalThis.WebSocket : null);
394
425
  if (!WebSocketImpl) {
@@ -416,6 +447,10 @@ export class WhereverClient {
416
447
  return;
417
448
  }
418
449
  const currentWs = this.ws;
450
+ const reassembler = new FrameReassembler();
451
+ // One warning per run of bad chunks: after one, every remaining chunk of
452
+ // that message is invalid too.
453
+ let inBadChunkRun = false;
419
454
  const onOpen = () => {
420
455
  if (this.ws !== currentWs)
421
456
  return;
@@ -426,6 +461,8 @@ export class WhereverClient {
426
461
  this.reconnectAttempts = 0;
427
462
  this.reconnectDelay = WhereverClient.MIN_RECONNECT_DELAY;
428
463
  this.isInitialConnect = false;
464
+ // Replies to loads issued on an earlier socket can no longer arrive.
465
+ this.abandonedSessions.clear();
429
466
  this.startLivenessWatchdog();
430
467
  this.stateStore.update(s => ({
431
468
  ...s,
@@ -450,6 +487,49 @@ export class WhereverClient {
450
487
  // 2. the store's activeSessionFile -> an UNSOLICITED drop (network
451
488
  // blip, tab switch, laptop sleep, half-open reap) where suspend()
452
489
  // never ran. This is the case that used to silently freeze.
490
+ //
491
+ // A session request the user made while the socket was down (a switch or
492
+ // a create, see queuedSessionRequest) is newer than any rejoin, so it is
493
+ // sent instead and nothing is rejoined.
494
+ let queued = this.queuedSessionRequest;
495
+ this.queuedSessionRequest = null;
496
+ // A queued load of the session we would rejoin anyway (reloadSession()
497
+ // while disconnected) IS the rejoin: take that path, which keeps held
498
+ // uploads and the resyncing affordance.
499
+ if (queued?.type === 'load' &&
500
+ queued.sessionFile === (this.resumeSessionFile ?? get(this.stateStore).activeSessionFile)) {
501
+ queued = null;
502
+ }
503
+ if (queued) {
504
+ this.resumeSessionFile = null;
505
+ this.resumeCwd = undefined;
506
+ this.resumeModel = undefined;
507
+ this.uploadsHeldForRejoin = false;
508
+ this.rejectPendingUploads('The session changed before the upload could be sent');
509
+ if (queued.type === 'load') {
510
+ this.stateStore.update(s => ({ ...s, loadingSession: true, resyncing: false }));
511
+ this.pendingLoadFile = queued.sessionFile;
512
+ this.send({
513
+ type: 'session_load',
514
+ sessionFile: queued.sessionFile,
515
+ cwd: queued.cwd,
516
+ model: queued.model,
517
+ });
518
+ this.armLoadWatchdog();
519
+ }
520
+ else {
521
+ this.stateStore.update(s => ({
522
+ ...s,
523
+ creatingSession: true,
524
+ loadingSession: false,
525
+ resyncing: false,
526
+ }));
527
+ this.pendingLoadFile = null;
528
+ this.send(queued.frame);
529
+ this.armCreateWatchdog();
530
+ }
531
+ return;
532
+ }
453
533
  const cached = get(this.stateStore);
454
534
  const rejoinFile = this.resumeSessionFile ?? cached.activeSessionFile;
455
535
  const rejoinCwd = this.resumeSessionFile != null
@@ -498,7 +578,23 @@ export class WhereverClient {
498
578
  this.cancelLivenessProbe();
499
579
  try {
500
580
  const rawData = typeof event.data === 'string' ? event.data : event.data.toString();
501
- const msg = JSON.parse(rawData);
581
+ const piece = reassembler.push(rawData);
582
+ if (piece.kind !== 'invalid')
583
+ inBadChunkRun = false;
584
+ if (piece.kind === 'partial') {
585
+ // A large frame is still arriving: the load it answers is making
586
+ // progress, so it must not time out meanwhile.
587
+ if (this.loadWatchdog)
588
+ this.armLoadWatchdog();
589
+ return;
590
+ }
591
+ if (piece.kind === 'invalid') {
592
+ if (!inBadChunkRun)
593
+ console.warn('[wherever] dropped a malformed or incomplete chunked frame');
594
+ inBadChunkRun = true;
595
+ return;
596
+ }
597
+ const msg = JSON.parse(piece.text);
502
598
  this.handleMessage(msg);
503
599
  }
504
600
  catch (err) {
@@ -611,6 +707,8 @@ export class WhereverClient {
611
707
  this.rejectPendingUploads('Disconnected before the upload completed');
612
708
  this.uploadsHeldForRejoin = false;
613
709
  this.hydratedFile = null;
710
+ this.queuedSessionRequest = null;
711
+ this.abandonedSessions.clear();
614
712
  this.stateStore.set({
615
713
  ...defaultState,
616
714
  hideThinking: !!this.config.hideThinking,
@@ -893,6 +991,8 @@ export class WhereverClient {
893
991
  this.loadWatchdog = setTimeout(() => {
894
992
  this.loadWatchdog = null;
895
993
  const s = get(this.stateStore);
994
+ if (this.queuedSessionRequest?.type === 'load')
995
+ this.queuedSessionRequest = null;
896
996
  if (!s.loadingSession && !s.resyncing)
897
997
  return;
898
998
  console.warn('[wherever] session load timed out; clearing loading state');
@@ -923,6 +1023,9 @@ export class WhereverClient {
923
1023
  this.createWatchdog = setTimeout(() => {
924
1024
  this.createWatchdog = null;
925
1025
  const s = get(this.stateStore);
1026
+ // The user was told it failed: a later reconnect must not create it anyway.
1027
+ if (this.queuedSessionRequest?.type === 'create')
1028
+ this.queuedSessionRequest = null;
926
1029
  if (!s.creatingSession)
927
1030
  return;
928
1031
  console.warn('[wherever] session create timed out; clearing creating state');
@@ -1016,6 +1119,8 @@ export class WhereverClient {
1016
1119
  const active = get(this.stateStore).sessionId;
1017
1120
  if (active && msg.sessionId && msg.sessionId !== active)
1018
1121
  break;
1122
+ if (msg.sessionId && this.abandonedSessions.has(msg.sessionId))
1123
+ break;
1019
1124
  this.clearLoadWatchdog();
1020
1125
  break;
1021
1126
  }
@@ -1498,10 +1603,21 @@ export class WhereverClient {
1498
1603
  (msg.sessionFile === this.pendingLoadFile ||
1499
1604
  msg.sessionId === this.pendingLoadFile);
1500
1605
  const isRequestedCreate = this.pendingLoadFile === null && st.creatingSession;
1501
- if (!matchesPendingLoad && !isRequestedCreate) {
1606
+ // A load the user moved away from (e.g. the rejoin still in flight
1607
+ // when they created a new session) is never the create's reply.
1608
+ const abandoned = this.abandonedSessions.has(msg.sessionFile) ||
1609
+ this.abandonedSessions.has(msg.sessionId);
1610
+ if (!matchesPendingLoad && (!isRequestedCreate || abandoned)) {
1611
+ // Its message_history follows: drop that too, unless it is the
1612
+ // session already on screen.
1613
+ if (msg.sessionId && msg.sessionId !== st.sessionId) {
1614
+ this.abandonedSessions.add(msg.sessionId);
1615
+ }
1502
1616
  break;
1503
1617
  }
1504
1618
  }
1619
+ this.abandonedSessions.delete(msg.sessionFile);
1620
+ this.abandonedSessions.delete(msg.sessionId);
1505
1621
  // This reply matches the load we were waiting on (or the create we
1506
1622
  // requested): the load is resolved, so stop guarding against it.
1507
1623
  this.pendingLoadFile = null;
@@ -1899,6 +2015,11 @@ export class WhereverClient {
1899
2015
  if (active && msg.sessionId && msg.sessionId !== active) {
1900
2016
  break;
1901
2017
  }
2018
+ // Or for a load the user abandoned, arriving before the new target's
2019
+ // own session_created (so no active sessionId guards it yet).
2020
+ if (msg.sessionId && this.abandonedSessions.has(msg.sessionId)) {
2021
+ break;
2022
+ }
1902
2023
  }
1903
2024
  // The server transcript is authoritative for what was actually persisted.
1904
2025
  // Reconcile it against any unconfirmed outbound messages: keep the ones
@@ -2722,10 +2843,44 @@ export class WhereverClient {
2722
2843
  loadingSession: true,
2723
2844
  agentPending: false,
2724
2845
  }));
2846
+ this.abandonPendingLoad(sessionFile);
2725
2847
  this.pendingLoadFile = sessionFile;
2726
- this.send({ type: 'session_load', sessionFile, cwd, model });
2848
+ this.sendSessionLoad(sessionFile, cwd, model);
2727
2849
  this.armLoadWatchdog();
2728
2850
  }
2851
+ // The in-flight load (if any) is being superseded by a new request: remember
2852
+ // it so its late reply is dropped (see abandonedSessions). `next` is the load
2853
+ // replacing it, which must not be dropped even if it was abandoned before.
2854
+ abandonPendingLoad(next, { keepShownSession = false } = {}) {
2855
+ if (this.pendingLoadFile && this.pendingLoadFile !== next) {
2856
+ this.abandonedSessions.add(this.pendingLoadFile);
2857
+ }
2858
+ // A load whose session_created was accepted but whose message_history is
2859
+ // still arriving (a rejoin's multi-MB history can take seconds, exactly
2860
+ // while the user is most likely to tap away): pendingLoadFile is already
2861
+ // null, so remember its sessionId instead, or its history would paint over
2862
+ // the next target and disarm that target's watchdog.
2863
+ // keepShownSession: a bare create (composer `/new`) keeps showing the
2864
+ // current session until the new one's session_created, after which the
2865
+ // active-id guard drops its history anyway; abandoning it here would only
2866
+ // blank it if the create then failed.
2867
+ const s = get(this.stateStore);
2868
+ if (!keepShownSession &&
2869
+ s.sessionId &&
2870
+ !s.historyAuthoritative &&
2871
+ s.activeSessionFile !== next &&
2872
+ s.sessionId !== next) {
2873
+ this.abandonedSessions.add(s.sessionId);
2874
+ }
2875
+ if (next)
2876
+ this.abandonedSessions.delete(next);
2877
+ }
2878
+ // Send a user-requested session_load, or queue it for the next open socket
2879
+ // when there is none (see queuedSessionRequest).
2880
+ sendSessionLoad(sessionFile, cwd, model) {
2881
+ const sent = this.send({ type: 'session_load', sessionFile, cwd, model });
2882
+ this.queuedSessionRequest = sent ? null : { type: 'load', sessionFile, cwd, model };
2883
+ }
2729
2884
  // Switch from the currently-active session (if any) straight to another one in
2730
2885
  // a single, atomic step. Leaving + loading used to be done by the UI as two
2731
2886
  // calls separated by a 100ms setTimeout; that gap could strand the loading
@@ -2745,6 +2900,8 @@ export class WhereverClient {
2745
2900
  if (s.sessionId) {
2746
2901
  this.send({ type: 'session_leave', sessionId: s.sessionId });
2747
2902
  }
2903
+ // Before the reset below, which forgets the session being left.
2904
+ this.abandonPendingLoad(sessionFile);
2748
2905
  // Reset to a clean loading state for the target session in one update so the
2749
2906
  // old conversation clears immediately and the spinner reflects the new load.
2750
2907
  this.stateStore.update((st) => ({
@@ -2777,7 +2934,7 @@ export class WhereverClient {
2777
2934
  // later fire against the newly loaded session.
2778
2935
  this.clearCreateWatchdog();
2779
2936
  this.pendingLoadFile = sessionFile;
2780
- this.send({ type: 'session_load', sessionFile, cwd, model });
2937
+ this.sendSessionLoad(sessionFile, cwd, model);
2781
2938
  this.armLoadWatchdog();
2782
2939
  }
2783
2940
  // Fork the given session at a specific user-message entry, mirroring pi's
@@ -2807,9 +2964,14 @@ export class WhereverClient {
2807
2964
  // A new session supersedes any in-flight load: its session_created must not
2808
2965
  // be rejected by a stale pendingLoadFile, and a late load reply for the old
2809
2966
  // target must not clobber the new session.
2967
+ this.abandonPendingLoad(undefined, { keepShownSession: true });
2810
2968
  this.pendingLoadFile = null;
2811
2969
  this.hydratedFile = null;
2812
- this.send({
2970
+ // A create supersedes any rejoin the next socket would otherwise make.
2971
+ this.resumeSessionFile = null;
2972
+ this.resumeCwd = undefined;
2973
+ this.resumeModel = undefined;
2974
+ const frame = {
2813
2975
  type: 'session_new',
2814
2976
  cwd,
2815
2977
  model,
@@ -2817,7 +2979,8 @@ export class WhereverClient {
2817
2979
  createRemote,
2818
2980
  repoVisibility,
2819
2981
  cloneRemote,
2820
- });
2982
+ };
2983
+ this.queuedSessionRequest = this.send(frame) ? null : { type: 'create', frame };
2821
2984
  // Never let the blocking "Creating session..." overlay hang if the reply is
2822
2985
  // lost. Symmetrical with armLoadWatchdog for session_load.
2823
2986
  this.armCreateWatchdog();
@@ -2828,7 +2991,14 @@ export class WhereverClient {
2828
2991
  // Leaving abandons any in-flight create too, so disarm its watchdog even when
2829
2992
  // there is no sessionId yet (a create that has not resolved).
2830
2993
  this.clearCreateWatchdog();
2831
- if (!s.sessionId) {
2994
+ // Leaving cancels whatever would otherwise (re)attach a session later: a
2995
+ // request queued while the socket was down, the rejoin of the session being
2996
+ // left, and the reply of a load still in flight. Done even with no
2997
+ // sessionId yet (a load or rejoin that has not resolved), since that is
2998
+ // exactly when a late reply would pull the user back.
2999
+ this.queuedSessionRequest = null;
3000
+ this.abandonPendingLoad();
3001
+ if (!s.sessionId && !s.activeSessionFile && this.pendingLoadFile === null && !this.resumeSessionFile) {
2832
3002
  if (s.creatingSession) {
2833
3003
  this.stateStore.update((st) => ({
2834
3004
  ...st,
@@ -2837,7 +3007,8 @@ export class WhereverClient {
2837
3007
  }
2838
3008
  return;
2839
3009
  }
2840
- this.send({ type: 'session_leave', sessionId: s.sessionId });
3010
+ if (s.sessionId)
3011
+ this.send({ type: 'session_leave', sessionId: s.sessionId });
2841
3012
  this.stateStore.update((s) => ({
2842
3013
  ...s,
2843
3014
  messages: [],