@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/CHANGELOG.md +59 -0
- package/dist/client.d.ts +27 -3
- package/dist/client.js +566 -16
- package/dist/client.js.map +1 -1
- package/dist/types.d.ts +9 -0
- package/package.json +11 -3
- package/src/client.ts +591 -23
- package/src/types.ts +26 -0
- package/test/agent-pending.test.ts +107 -0
- package/test/creating-session-watchdog.test.ts +82 -0
- package/test/harness.ts +97 -0
- package/test/reconnect-rejoins-session.test.ts +136 -0
- package/test/resume-keeps-session.test.ts +118 -0
package/src/client.ts
CHANGED
|
@@ -15,6 +15,9 @@ const defaultState: WhereverState = {
|
|
|
15
15
|
connected: false,
|
|
16
16
|
connecting: false,
|
|
17
17
|
creatingSession: false,
|
|
18
|
+
loadingSession: false,
|
|
19
|
+
resyncing: false,
|
|
20
|
+
agentPending: false,
|
|
18
21
|
error: null,
|
|
19
22
|
session: null,
|
|
20
23
|
sessionId: null,
|
|
@@ -33,6 +36,7 @@ const defaultState: WhereverState = {
|
|
|
33
36
|
historyTotalCount: 0,
|
|
34
37
|
historyOffset: 0,
|
|
35
38
|
loadingMoreHistory: false,
|
|
39
|
+
contextUsage: null,
|
|
36
40
|
};
|
|
37
41
|
|
|
38
42
|
export class WhereverClient {
|
|
@@ -41,10 +45,56 @@ export class WhereverClient {
|
|
|
41
45
|
public stateStore: Writable<WhereverState>;
|
|
42
46
|
private reconnectTimer: any = null;
|
|
43
47
|
private agentEndTimeout: any = null;
|
|
48
|
+
// Watchdog for an in-flight session_load. We set loadingSession/resyncing the
|
|
49
|
+
// moment a load is requested and clear them when message_history (or an
|
|
50
|
+
// error/conflict/disconnect) arrives. If none of those ever comes back (a lost
|
|
51
|
+
// reply, a server that answered for a different session, or any unforeseen
|
|
52
|
+
// edge), the "Loading session..." / "Reconnecting..." affordance would hang
|
|
53
|
+
// forever. This timer guarantees the load state always resolves: on expiry we
|
|
54
|
+
// clear the flags and surface a recoverable error instead of an endless spin.
|
|
55
|
+
private loadWatchdog: any = null;
|
|
56
|
+
private static readonly LOAD_WATCHDOG_MS = 12_000;
|
|
57
|
+
// Watchdog for an in-flight session_new. Symmetrical to loadWatchdog: creating
|
|
58
|
+
// a session sets creatingSession=true and shows a BLOCKING full-screen overlay,
|
|
59
|
+
// and the only things that clear it are session_created/session_error/
|
|
60
|
+
// session_conflict/session_interrupted (or a socket close). If none of those
|
|
61
|
+
// ever arrives (a slow git init / remote-repo creation, an error thrown before
|
|
62
|
+
// the reply is sent, or a half-open socket the liveness watchdog has not yet
|
|
63
|
+
// reaped), the overlay spins forever and the only recovery is a reload. This
|
|
64
|
+
// timer guarantees creatingSession always resolves. It is longer than the load
|
|
65
|
+
// watchdog because creating can legitimately take a while (git init + creating
|
|
66
|
+
// a remote GitHub repo over the network).
|
|
67
|
+
private createWatchdog: any = null;
|
|
68
|
+
private static readonly CREATE_WATCHDOG_MS = 25_000;
|
|
44
69
|
private reconnectAttempts = 0;
|
|
45
70
|
private reconnectDelay = 2000;
|
|
46
71
|
private maxReconnectDelay = 15000;
|
|
72
|
+
// Liveness watchdog: a half-open TCP socket fires neither 'close' nor 'error',
|
|
73
|
+
// so the existing reconnect machinery never triggers and the agent hangs
|
|
74
|
+
// forever (see work/observations/ws-half-open-connection-hangs-agent-no-heartbeat.md).
|
|
75
|
+
// We record the time of the last inbound frame and, if the socket goes silent
|
|
76
|
+
// for longer than STALE_SOCKET_MS, proactively tear it down and reconnect.
|
|
77
|
+
// A periodic app-level {type:'ping'} keeps a healthy connection refreshed even
|
|
78
|
+
// during long, token-less model turns.
|
|
79
|
+
private livenessTimer: any = null;
|
|
80
|
+
private heartbeatTimer: any = null;
|
|
81
|
+
private lastInboundAt = 0;
|
|
82
|
+
// > the server heartbeat (when present) and any normal token-less gap, so a
|
|
83
|
+
// healthy connection is never falsely reaped; short enough to self-heal fast.
|
|
84
|
+
private static readonly STALE_SOCKET_MS = 60_000;
|
|
85
|
+
// While a turn is streaming, the keepalive pong should keep traffic flowing, so
|
|
86
|
+
// a shorter deadline surfaces a stalled transport (vs a merely slow model)
|
|
87
|
+
// faster. Still > one HEARTBEAT_MS so a single healthy pong keeps it fresh.
|
|
88
|
+
private static readonly TURN_STALL_MS = 45_000;
|
|
89
|
+
// Send a keepalive well under STALE_SOCKET_MS so the pong refreshes liveness.
|
|
90
|
+
private static readonly HEARTBEAT_MS = 25_000;
|
|
47
91
|
private isInitialConnect = true;
|
|
92
|
+
// When set, the next successful (re)connection should rejoin the previously
|
|
93
|
+
// active session instead of starting blank. Used by resume() so a backgrounded
|
|
94
|
+
// tab returns to its cached conversation and resyncs history in place.
|
|
95
|
+
private resumeSessionFile: string | null = null;
|
|
96
|
+
private resumeCwd?: string;
|
|
97
|
+
private resumeModel?: string;
|
|
48
98
|
private listeners = new Set<(msg: any) => void>();
|
|
49
99
|
private pendingUploads = new Map<string, {resolve: (val: any) => void, reject: (err: any) => void}>();
|
|
50
100
|
|
|
@@ -60,7 +110,7 @@ export class WhereverClient {
|
|
|
60
110
|
});
|
|
61
111
|
}
|
|
62
112
|
|
|
63
|
-
public connect(newConfig?: Partial<WhereverClientConfig
|
|
113
|
+
public connect(newConfig?: Partial<WhereverClientConfig>, preserveState = false) {
|
|
64
114
|
if (newConfig) {
|
|
65
115
|
this.config = {
|
|
66
116
|
...this.config,
|
|
@@ -70,12 +120,18 @@ export class WhereverClient {
|
|
|
70
120
|
|
|
71
121
|
this.disconnect(false);
|
|
72
122
|
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
123
|
+
// preserveState keeps the cached session/messages in the store across a
|
|
124
|
+
// reconnect (resume path), so the previous conversation stays visible while
|
|
125
|
+
// we reconnect and resync. The default (fresh connect) clears to a blank
|
|
126
|
+
// store as before.
|
|
127
|
+
this.stateStore.update(s => preserveState
|
|
128
|
+
? {...s, connecting: true, error: null}
|
|
129
|
+
: {
|
|
130
|
+
...defaultState,
|
|
131
|
+
connecting: true,
|
|
132
|
+
hideThinking: !!this.config.hideThinking,
|
|
133
|
+
hideTools: !!this.config.hideTools,
|
|
134
|
+
});
|
|
79
135
|
|
|
80
136
|
const protocol = this.config.secure ? "wss" : "ws";
|
|
81
137
|
const host = this.config.host.startsWith('http')
|
|
@@ -112,19 +168,67 @@ export class WhereverClient {
|
|
|
112
168
|
|
|
113
169
|
const onOpen = () => {
|
|
114
170
|
if (this.ws !== currentWs) return;
|
|
171
|
+
if (!this.isInitialConnect) {
|
|
172
|
+
console.info('[wherever] reconnected to relay');
|
|
173
|
+
}
|
|
115
174
|
this.reconnectAttempts = 0;
|
|
116
175
|
this.reconnectDelay = 2000;
|
|
117
176
|
this.isInitialConnect = false;
|
|
177
|
+
this.startLivenessWatchdog();
|
|
118
178
|
this.stateStore.update(s => ({
|
|
119
179
|
...s,
|
|
120
180
|
connected: true,
|
|
121
181
|
connecting: false,
|
|
122
182
|
error: null
|
|
123
183
|
}));
|
|
184
|
+
// Resume path: rejoin the previously-active session so its history is
|
|
185
|
+
// resynced in place. resyncing stays true until message_history (or an
|
|
186
|
+
// error/conflict) arrives, keeping the "reconnecting" affordance up and
|
|
187
|
+
// input blocked without dropping the cached messages.
|
|
188
|
+
//
|
|
189
|
+
// Re-attachment is REQUIRED on every reconnect that still holds a session,
|
|
190
|
+
// not just the suspend/resume path. The server is stateless per socket:
|
|
191
|
+
// each new connection starts attached to NO session (the old socket's
|
|
192
|
+
// close removed this client from the pool). If we do not re-issue
|
|
193
|
+
// session_load here, the relay is connected but the session stream is
|
|
194
|
+
// dead, so the UI shows a frozen conversation (a stale tool call as the
|
|
195
|
+
// last message, Abort disabled) while the agent keeps running headless.
|
|
196
|
+
// Two sources for what to rejoin:
|
|
197
|
+
// 1. resumeSessionFile -> explicit suspend()/resume() (tab background).
|
|
198
|
+
// 2. the store's activeSessionFile -> an UNSOLICITED drop (network
|
|
199
|
+
// blip, tab switch, laptop sleep, half-open reap) where suspend()
|
|
200
|
+
// never ran. This is the case that used to silently freeze.
|
|
201
|
+
const cached = get(this.stateStore);
|
|
202
|
+
const rejoinFile = this.resumeSessionFile ?? cached.activeSessionFile;
|
|
203
|
+
const rejoinCwd =
|
|
204
|
+
this.resumeSessionFile != null
|
|
205
|
+
? this.resumeCwd
|
|
206
|
+
: (cached.activeCwd ?? undefined);
|
|
207
|
+
const rejoinModel =
|
|
208
|
+
this.resumeSessionFile != null
|
|
209
|
+
? this.resumeModel
|
|
210
|
+
: (cached.activeModel ?? undefined);
|
|
211
|
+
this.resumeSessionFile = null;
|
|
212
|
+
this.resumeCwd = undefined;
|
|
213
|
+
this.resumeModel = undefined;
|
|
214
|
+
if (rejoinFile) {
|
|
215
|
+
// Keep the cached conversation on screen but mark it resyncing so the
|
|
216
|
+
// "Reconnecting and syncing session..." banner shows and sending is
|
|
217
|
+
// blocked until fresh history lands. resyncing is cleared by
|
|
218
|
+
// message_history (or an error/conflict) via the reducer.
|
|
219
|
+
this.stateStore.update(s => (s.resyncing ? s : {...s, resyncing: true}));
|
|
220
|
+
this.send({type: 'session_load', sessionFile: rejoinFile, cwd: rejoinCwd, model: rejoinModel});
|
|
221
|
+
this.armLoadWatchdog();
|
|
222
|
+
} else {
|
|
223
|
+
this.stateStore.update(s => (s.resyncing ? {...s, resyncing: false} : s));
|
|
224
|
+
}
|
|
124
225
|
};
|
|
125
226
|
|
|
126
227
|
const onMessage = (event: any) => {
|
|
127
228
|
if (this.ws !== currentWs) return;
|
|
229
|
+
// Any inbound frame (including the pong reply to our keepalive) proves the
|
|
230
|
+
// socket is alive and resets the stale-socket watchdog.
|
|
231
|
+
this.lastInboundAt = Date.now();
|
|
128
232
|
try {
|
|
129
233
|
const rawData = typeof event.data === 'string' ? event.data : event.data.toString();
|
|
130
234
|
const msg = JSON.parse(rawData);
|
|
@@ -136,11 +240,22 @@ export class WhereverClient {
|
|
|
136
240
|
|
|
137
241
|
const onClose = () => {
|
|
138
242
|
if (this.ws !== currentWs) return;
|
|
243
|
+
this.stopLivenessWatchdog();
|
|
244
|
+
this.clearLoadWatchdog();
|
|
139
245
|
this.ws = null;
|
|
140
246
|
this.stateStore.update(s => ({
|
|
141
247
|
...s,
|
|
142
248
|
connected: false,
|
|
143
249
|
connecting: false,
|
|
250
|
+
// Never leave a session-load spinner stuck if the socket drops mid-load.
|
|
251
|
+
loadingSession: false,
|
|
252
|
+
creatingSession: false,
|
|
253
|
+
// If we still hold an active session, the drop is an unsolicited one on a
|
|
254
|
+
// live conversation: mark it resyncing NOW (during the reconnect backoff)
|
|
255
|
+
// so the user immediately sees "Reconnecting..." instead of a frozen view
|
|
256
|
+
// with a stale tool call and a disabled Abort. onOpen re-attaches and the
|
|
257
|
+
// reducer clears resyncing when fresh history lands.
|
|
258
|
+
resyncing: s.activeSessionFile ? true : s.resyncing,
|
|
144
259
|
}));
|
|
145
260
|
this.scheduleReconnect();
|
|
146
261
|
};
|
|
@@ -171,7 +286,20 @@ export class WhereverClient {
|
|
|
171
286
|
clearTimeout(this.reconnectTimer);
|
|
172
287
|
this.reconnectTimer = null;
|
|
173
288
|
}
|
|
174
|
-
|
|
289
|
+
// A pending agent_end clear timer belongs to the socket we are tearing down.
|
|
290
|
+
// Leaving it armed lets it fire against a freshly (re)connected session's
|
|
291
|
+
// state, so cancel it here.
|
|
292
|
+
if (this.agentEndTimeout) {
|
|
293
|
+
clearTimeout(this.agentEndTimeout);
|
|
294
|
+
this.agentEndTimeout = null;
|
|
295
|
+
}
|
|
296
|
+
this.stopLivenessWatchdog();
|
|
297
|
+
// The load/create affordances belong to the socket we are tearing down. If
|
|
298
|
+
// left armed they would later fire against a fresh (re)connected session's
|
|
299
|
+
// state, so cancel them here.
|
|
300
|
+
this.clearLoadWatchdog();
|
|
301
|
+
this.clearCreateWatchdog();
|
|
302
|
+
|
|
175
303
|
if (this.ws) {
|
|
176
304
|
try {
|
|
177
305
|
if (typeof this.ws.removeAllListeners === 'function') {
|
|
@@ -188,6 +316,229 @@ export class WhereverClient {
|
|
|
188
316
|
hideThinking: !!this.config.hideThinking,
|
|
189
317
|
hideTools: !!this.config.hideTools,
|
|
190
318
|
});
|
|
319
|
+
} else {
|
|
320
|
+
// Preserve-cache teardown (suspend / resume's pre-connect close). The
|
|
321
|
+
// socket is gone, so the store MUST reflect disconnected: leaving a stale
|
|
322
|
+
// connected:true made resume() early-return (its `if (connected) return`
|
|
323
|
+
// guard), so the real reconnect fell through to a plain connect() that did
|
|
324
|
+
// NOT preserve the session, which is what flashed the search / new-session
|
|
325
|
+
// empty-state on tab return. Clearing connected here (without wiping the
|
|
326
|
+
// cached session/messages) lets resume() actually rejoin in place, and
|
|
327
|
+
// never leaves the blocking load/create overlays up on a dead socket.
|
|
328
|
+
this.stateStore.update(s => ({
|
|
329
|
+
...s,
|
|
330
|
+
connected: false,
|
|
331
|
+
connecting: false,
|
|
332
|
+
loadingSession: false,
|
|
333
|
+
creatingSession: false,
|
|
334
|
+
}));
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
// Suspend the connection without tearing down the cached session state. Used
|
|
339
|
+
// when the tab is backgrounded: closing the WebSocket improves bfcache
|
|
340
|
+
// eligibility, but we keep messages/sessionId so returning is a cheap resync
|
|
341
|
+
// rather than a full reload. Records the active session so resume() can rejoin
|
|
342
|
+
// it. Does NOT schedule a reconnect (disconnect(false) clears that timer).
|
|
343
|
+
public suspend() {
|
|
344
|
+
const s = get(this.stateStore);
|
|
345
|
+
if (s.activeSessionFile) {
|
|
346
|
+
this.resumeSessionFile = s.activeSessionFile;
|
|
347
|
+
this.resumeCwd = s.activeCwd ?? undefined;
|
|
348
|
+
this.resumeModel = s.activeModel ?? undefined;
|
|
349
|
+
}
|
|
350
|
+
// The socket producing the live stream is going away. If we carry a stale
|
|
351
|
+
// isStreaming:true across the suspend/resume gap, the composer will wrongly
|
|
352
|
+
// queue the next message as if the agent were still busy (and the queue
|
|
353
|
+
// never drains because no agent_end ever arrives on the dead socket). The
|
|
354
|
+
// authoritative value is re-established by session_created on rejoin.
|
|
355
|
+
if (s.isStreaming) {
|
|
356
|
+
this.stateStore.update(st => ({...st, isStreaming: false}));
|
|
357
|
+
}
|
|
358
|
+
this.disconnect(false);
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
// Resume after suspend(): reconnect while preserving the cached store, mark
|
|
362
|
+
// the session as resyncing, and let onOpen rejoin the recorded session. If
|
|
363
|
+
// there is no active session to rejoin, this is just a state-preserving
|
|
364
|
+
// reconnect.
|
|
365
|
+
public resume() {
|
|
366
|
+
const s = get(this.stateStore);
|
|
367
|
+
if (s.connected || s.connecting) return;
|
|
368
|
+
// Rejoin whatever session we still hold: an explicit suspend() record OR the
|
|
369
|
+
// cached active session from an unsolicited drop. In BOTH cases onOpen
|
|
370
|
+
// re-issues session_load, so mark resyncing here to show the affordance and
|
|
371
|
+
// block sending until fresh history lands.
|
|
372
|
+
if (this.resumeSessionFile || s.activeSessionFile) {
|
|
373
|
+
this.stateStore.update(st => ({...st, resyncing: true}));
|
|
374
|
+
// Arm here too: if the socket never opens, onOpen never runs and the
|
|
375
|
+
// resync affordance would otherwise hang. onClose also clears it, but the
|
|
376
|
+
// watchdog covers the half-open / never-opens case.
|
|
377
|
+
this.armLoadWatchdog();
|
|
378
|
+
}
|
|
379
|
+
this.connect(undefined, true);
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
// True when suspend() recorded an active session to rejoin on the next resume.
|
|
383
|
+
// Callers use this to take the resume (preserve-cache, rejoin-in-place) path
|
|
384
|
+
// only when there is actually a suspended session; otherwise a plain connect()
|
|
385
|
+
// is correct and avoids racing/latching the hash auto-join on a fresh load.
|
|
386
|
+
public hasSuspendedSession(): boolean {
|
|
387
|
+
return this.resumeSessionFile !== null;
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
// True when the store still holds an active session to rejoin in place -- from
|
|
391
|
+
// an explicit suspend() OR an unsolicited drop that left activeSessionFile set.
|
|
392
|
+
// Callers use this to prefer the preserve-cache resume() path over a fresh,
|
|
393
|
+
// session-wiping connect() when returning to a still-live conversation.
|
|
394
|
+
public hasActiveSession(): boolean {
|
|
395
|
+
return this.resumeSessionFile !== null || get(this.stateStore).activeSessionFile !== null;
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
// Start (or restart) the stale-socket watchdog + keepalive for the current
|
|
399
|
+
// socket. A half-open connection emits no 'close'/'error', so without this the
|
|
400
|
+
// existing reconnect logic would never fire and the agent would hang forever.
|
|
401
|
+
private startLivenessWatchdog() {
|
|
402
|
+
this.stopLivenessWatchdog();
|
|
403
|
+
this.lastInboundAt = Date.now();
|
|
404
|
+
|
|
405
|
+
const sendBeat = () => {
|
|
406
|
+
// Keep a healthy connection warm so the pong refreshes lastInboundAt even
|
|
407
|
+
// during long, token-less model turns.
|
|
408
|
+
try {
|
|
409
|
+
this.ping();
|
|
410
|
+
} catch {}
|
|
411
|
+
};
|
|
412
|
+
if (typeof setInterval === 'function') {
|
|
413
|
+
this.heartbeatTimer = setInterval(sendBeat, WhereverClient.HEARTBEAT_MS);
|
|
414
|
+
if (this.heartbeatTimer && typeof this.heartbeatTimer.unref === 'function') {
|
|
415
|
+
this.heartbeatTimer.unref();
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
const checkLiveness = () => {
|
|
420
|
+
if (!this.ws) return;
|
|
421
|
+
const silentFor = Date.now() - this.lastInboundAt;
|
|
422
|
+
const streaming = get(this.stateStore).isStreaming;
|
|
423
|
+
// Per-turn stall timeout: while a turn is in flight the heartbeat pong (and,
|
|
424
|
+
// normally, tokens) should keep traffic flowing, so a shorter deadline
|
|
425
|
+
// distinguishes "model is slow" (heartbeat still arriving -> not stale) from
|
|
426
|
+
// "transport is dead" (heartbeat stopped). When idle, fall back to the
|
|
427
|
+
// generic stale-socket threshold.
|
|
428
|
+
const threshold = streaming
|
|
429
|
+
? WhereverClient.TURN_STALL_MS
|
|
430
|
+
: WhereverClient.STALE_SOCKET_MS;
|
|
431
|
+
if (silentFor < threshold) return;
|
|
432
|
+
// The socket has been silent past the threshold: treat it as dead. Tearing
|
|
433
|
+
// it down forcibly is what makes a half-open connection recover, since the
|
|
434
|
+
// OS never produced a FIN/RST to trigger the normal close path.
|
|
435
|
+
console.warn(
|
|
436
|
+
`[wherever] relay connection stale: no inbound frame for ${silentFor}ms ` +
|
|
437
|
+
`(threshold ${threshold}ms, ${streaming ? 'mid-turn' : 'idle'}); ` +
|
|
438
|
+
`tearing down dead socket and reconnecting`,
|
|
439
|
+
);
|
|
440
|
+
this.stopLivenessWatchdog();
|
|
441
|
+
const deadWs = this.ws;
|
|
442
|
+
this.ws = null;
|
|
443
|
+
try {
|
|
444
|
+
if (typeof deadWs.terminate === 'function') {
|
|
445
|
+
deadWs.terminate();
|
|
446
|
+
} else if (typeof deadWs.close === 'function') {
|
|
447
|
+
deadWs.close();
|
|
448
|
+
}
|
|
449
|
+
} catch {}
|
|
450
|
+
this.stateStore.update(s => ({
|
|
451
|
+
...s,
|
|
452
|
+
connected: false,
|
|
453
|
+
connecting: false,
|
|
454
|
+
loadingSession: false,
|
|
455
|
+
creatingSession: false,
|
|
456
|
+
// If a turn was in flight, surface it as a recoverable error so the UI
|
|
457
|
+
// shows "the transport stalled" rather than silently parking mid-stream.
|
|
458
|
+
sessionError: streaming
|
|
459
|
+
? 'Connection to relay stalled mid-turn; reconnecting...'
|
|
460
|
+
: s.sessionError,
|
|
461
|
+
isStreaming: false,
|
|
462
|
+
}));
|
|
463
|
+
this.scheduleReconnect();
|
|
464
|
+
};
|
|
465
|
+
if (typeof setInterval === 'function') {
|
|
466
|
+
this.livenessTimer = setInterval(checkLiveness, WhereverClient.HEARTBEAT_MS);
|
|
467
|
+
if (this.livenessTimer && typeof this.livenessTimer.unref === 'function') {
|
|
468
|
+
this.livenessTimer.unref();
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
private stopLivenessWatchdog() {
|
|
474
|
+
if (this.heartbeatTimer) {
|
|
475
|
+
clearInterval(this.heartbeatTimer);
|
|
476
|
+
this.heartbeatTimer = null;
|
|
477
|
+
}
|
|
478
|
+
if (this.livenessTimer) {
|
|
479
|
+
clearInterval(this.livenessTimer);
|
|
480
|
+
this.livenessTimer = null;
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
// Arm (or re-arm) the load watchdog. Called whenever a session_load is issued
|
|
485
|
+
// so an unresolved load can never strand the loading UI. Idempotent: a fresh
|
|
486
|
+
// load resets the deadline.
|
|
487
|
+
private armLoadWatchdog() {
|
|
488
|
+
this.clearLoadWatchdog();
|
|
489
|
+
this.loadWatchdog = setTimeout(() => {
|
|
490
|
+
this.loadWatchdog = null;
|
|
491
|
+
const s = get(this.stateStore);
|
|
492
|
+
if (!s.loadingSession && !s.resyncing) return;
|
|
493
|
+
console.warn('[wherever] session load timed out; clearing loading state');
|
|
494
|
+
this.stateStore.update(st => ({
|
|
495
|
+
...st,
|
|
496
|
+
loadingSession: false,
|
|
497
|
+
resyncing: false,
|
|
498
|
+
sessionError:
|
|
499
|
+
st.sessionError ||
|
|
500
|
+
'Loading the session timed out. Please retry from the sidebar or reload.',
|
|
501
|
+
}));
|
|
502
|
+
}, WhereverClient.LOAD_WATCHDOG_MS);
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
// Clear the load watchdog. Called at every point the load resolves
|
|
506
|
+
// (message_history, session_error, session_conflict, disconnect, leave).
|
|
507
|
+
private clearLoadWatchdog() {
|
|
508
|
+
if (this.loadWatchdog) {
|
|
509
|
+
clearTimeout(this.loadWatchdog);
|
|
510
|
+
this.loadWatchdog = null;
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
// Arm (or re-arm) the create watchdog. Called when session_new is issued so an
|
|
515
|
+
// unanswered create can never strand the blocking "Creating session..."
|
|
516
|
+
// overlay. On expiry we clear creatingSession and surface a recoverable error
|
|
517
|
+
// instead of an endless spin that only a reload escapes.
|
|
518
|
+
private armCreateWatchdog() {
|
|
519
|
+
this.clearCreateWatchdog();
|
|
520
|
+
this.createWatchdog = setTimeout(() => {
|
|
521
|
+
this.createWatchdog = null;
|
|
522
|
+
const s = get(this.stateStore);
|
|
523
|
+
if (!s.creatingSession) return;
|
|
524
|
+
console.warn('[wherever] session create timed out; clearing creating state');
|
|
525
|
+
this.stateStore.update(st => ({
|
|
526
|
+
...st,
|
|
527
|
+
creatingSession: false,
|
|
528
|
+
sessionError:
|
|
529
|
+
st.sessionError ||
|
|
530
|
+
'Creating the session timed out. It may still be starting on the server; check the sidebar or reload.',
|
|
531
|
+
}));
|
|
532
|
+
}, WhereverClient.CREATE_WATCHDOG_MS);
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
// Clear the create watchdog. Called at every point a create resolves
|
|
536
|
+
// (session_created, session_error, session_conflict, session_interrupted,
|
|
537
|
+
// disconnect, leave).
|
|
538
|
+
private clearCreateWatchdog() {
|
|
539
|
+
if (this.createWatchdog) {
|
|
540
|
+
clearTimeout(this.createWatchdog);
|
|
541
|
+
this.createWatchdog = null;
|
|
191
542
|
}
|
|
192
543
|
}
|
|
193
544
|
|
|
@@ -197,14 +548,24 @@ export class WhereverClient {
|
|
|
197
548
|
this.reconnectTimer = setTimeout(() => {
|
|
198
549
|
this.reconnectTimer = null;
|
|
199
550
|
this.reconnectDelay = Math.min(this.reconnectDelay * 1.5, this.maxReconnectDelay);
|
|
200
|
-
|
|
551
|
+
console.info(`[wherever] reconnecting to relay (attempt ${++this.reconnectAttempts})`);
|
|
552
|
+
|
|
553
|
+
// If we still hold an active session, PRESERVE the cached store across the
|
|
554
|
+
// reconnect. A default connect() resets to a blank store, which wiped
|
|
555
|
+
// activeSessionFile BEFORE onOpen could re-attach to it -- that is what
|
|
556
|
+
// silently detached the frontend from a still-running session (frozen
|
|
557
|
+
// conversation, no re-follow, not even a "connecting"/"loading" hint).
|
|
558
|
+
// Preserving the store keeps the conversation on screen and lets onOpen
|
|
559
|
+
// re-issue session_load from activeSessionFile.
|
|
560
|
+
const preserve = !!get(this.stateStore).activeSessionFile;
|
|
561
|
+
|
|
201
562
|
this.stateStore.update(s => ({
|
|
202
563
|
...s,
|
|
203
564
|
connecting: true,
|
|
204
565
|
error: 'Reconnecting...',
|
|
205
566
|
}));
|
|
206
|
-
|
|
207
|
-
this.connect();
|
|
567
|
+
|
|
568
|
+
this.connect(undefined, preserve);
|
|
208
569
|
}, this.reconnectDelay);
|
|
209
570
|
}
|
|
210
571
|
|
|
@@ -217,6 +578,31 @@ export class WhereverClient {
|
|
|
217
578
|
}
|
|
218
579
|
}
|
|
219
580
|
|
|
581
|
+
// Any message that resolves an in-flight session_load disarms the watchdog.
|
|
582
|
+
// session_created arrives just before message_history; message_history is the
|
|
583
|
+
// real completion, but an error/conflict/destroy/interrupt also resolves it.
|
|
584
|
+
switch (msg.type) {
|
|
585
|
+
case 'message_history':
|
|
586
|
+
case 'session_error':
|
|
587
|
+
case 'session_conflict':
|
|
588
|
+
case 'session_destroyed':
|
|
589
|
+
case 'session_interrupted':
|
|
590
|
+
this.clearLoadWatchdog();
|
|
591
|
+
break;
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
// Any message that resolves an in-flight session_new disarms the create
|
|
595
|
+
// watchdog. session_created is the success path; error/conflict/interrupt end
|
|
596
|
+
// it too.
|
|
597
|
+
switch (msg.type) {
|
|
598
|
+
case 'session_created':
|
|
599
|
+
case 'session_error':
|
|
600
|
+
case 'session_conflict':
|
|
601
|
+
case 'session_interrupted':
|
|
602
|
+
this.clearCreateWatchdog();
|
|
603
|
+
break;
|
|
604
|
+
}
|
|
605
|
+
|
|
220
606
|
switch (msg.type) {
|
|
221
607
|
case 'connected':
|
|
222
608
|
this.stateStore.update((s: WhereverState) => ({
|
|
@@ -518,6 +904,42 @@ export class WhereverClient {
|
|
|
518
904
|
activeModel: msg.model,
|
|
519
905
|
isStreaming: msg.isStreaming ?? false,
|
|
520
906
|
creatingSession: false,
|
|
907
|
+
// The server forces read-only for sessions in a configured
|
|
908
|
+
// sessions.readOnly folder (observe-only fleet view).
|
|
909
|
+
readOnly: msg.readOnly ?? false,
|
|
910
|
+
// pending -> the history is painted now but the live agent is still
|
|
911
|
+
// building; keep the composer disabled (agentPending) until
|
|
912
|
+
// session_ready. A non-pending create (new session, warm reload) is
|
|
913
|
+
// immediately sendable.
|
|
914
|
+
agentPending: msg.pending === true,
|
|
915
|
+
// Initial context-usage snapshot for the new session (null if unknown;
|
|
916
|
+
// live updates arrive via 'context_usage').
|
|
917
|
+
contextUsage: msg.contextUsage ?? null,
|
|
918
|
+
}));
|
|
919
|
+
break;
|
|
920
|
+
|
|
921
|
+
case 'session_ready':
|
|
922
|
+
// The live agent finished building for a previously-pending load. Enable
|
|
923
|
+
// the composer and refresh the now-authoritative model/streaming/usage.
|
|
924
|
+
this.stateStore.update((s: WhereverState) => {
|
|
925
|
+
// Ignore a stale ready for a session we already switched away from.
|
|
926
|
+
if (msg.sessionFile && s.activeSessionFile && msg.sessionFile !== s.activeSessionFile) {
|
|
927
|
+
return s;
|
|
928
|
+
}
|
|
929
|
+
return {
|
|
930
|
+
...s,
|
|
931
|
+
agentPending: false,
|
|
932
|
+
activeModel: msg.model ?? s.activeModel,
|
|
933
|
+
isStreaming: msg.isStreaming ?? s.isStreaming,
|
|
934
|
+
contextUsage: msg.contextUsage ?? s.contextUsage,
|
|
935
|
+
};
|
|
936
|
+
});
|
|
937
|
+
break;
|
|
938
|
+
|
|
939
|
+
case 'context_usage':
|
|
940
|
+
this.stateStore.update((s: WhereverState) => ({
|
|
941
|
+
...s,
|
|
942
|
+
contextUsage: msg.contextUsage ?? null,
|
|
521
943
|
}));
|
|
522
944
|
break;
|
|
523
945
|
|
|
@@ -532,6 +954,8 @@ export class WhereverClient {
|
|
|
532
954
|
activeSessionFile: null,
|
|
533
955
|
activeCwd: null,
|
|
534
956
|
activeModel: null,
|
|
957
|
+
loadingSession: false,
|
|
958
|
+
agentPending: false,
|
|
535
959
|
};
|
|
536
960
|
}
|
|
537
961
|
return s;
|
|
@@ -544,6 +968,12 @@ export class WhereverClient {
|
|
|
544
968
|
sessionError: msg.error,
|
|
545
969
|
isStreaming: false,
|
|
546
970
|
creatingSession: false,
|
|
971
|
+
loadingSession: false,
|
|
972
|
+
resyncing: false,
|
|
973
|
+
// A failed (cold) agent build clears pending: the session stays
|
|
974
|
+
// readable, but sending remains blocked (no live agent) and the error
|
|
975
|
+
// is surfaced. This is the degrade-to-read-only path.
|
|
976
|
+
agentPending: false,
|
|
547
977
|
}));
|
|
548
978
|
break;
|
|
549
979
|
|
|
@@ -556,6 +986,9 @@ export class WhereverClient {
|
|
|
556
986
|
conflictingCwd: msg.conflictingCwd,
|
|
557
987
|
},
|
|
558
988
|
creatingSession: false,
|
|
989
|
+
loadingSession: false,
|
|
990
|
+
resyncing: false,
|
|
991
|
+
agentPending: false,
|
|
559
992
|
}));
|
|
560
993
|
break;
|
|
561
994
|
|
|
@@ -571,6 +1004,8 @@ export class WhereverClient {
|
|
|
571
1004
|
activeCwd: null,
|
|
572
1005
|
activeModel: null,
|
|
573
1006
|
creatingSession: false,
|
|
1007
|
+
loadingSession: false,
|
|
1008
|
+
agentPending: false,
|
|
574
1009
|
}));
|
|
575
1010
|
break;
|
|
576
1011
|
|
|
@@ -586,6 +1021,8 @@ export class WhereverClient {
|
|
|
586
1021
|
historyTotalCount: totalCount,
|
|
587
1022
|
historyOffset: offset,
|
|
588
1023
|
loadingMoreHistory: false,
|
|
1024
|
+
loadingSession: false,
|
|
1025
|
+
resyncing: false,
|
|
589
1026
|
};
|
|
590
1027
|
});
|
|
591
1028
|
break;
|
|
@@ -725,18 +1162,76 @@ export class WhereverClient {
|
|
|
725
1162
|
});
|
|
726
1163
|
}
|
|
727
1164
|
|
|
728
|
-
|
|
1165
|
+
// Returns true only when the frame was actually handed to an OPEN socket.
|
|
1166
|
+
// A non-OPEN (null / CONNECTING / CLOSING / half-open) socket silently
|
|
1167
|
+
// dropping the frame is what made messages vanish: they rendered locally but
|
|
1168
|
+
// never reached the server, so they were gone after a reload. Callers that
|
|
1169
|
+
// carry user intent (sendMessage) must check this and surface the failure.
|
|
1170
|
+
public send(msg: any): boolean {
|
|
729
1171
|
if (this.ws && this.ws.readyState === 1 /* OPEN */) {
|
|
730
|
-
|
|
1172
|
+
try {
|
|
1173
|
+
this.ws.send(JSON.stringify(msg));
|
|
1174
|
+
return true;
|
|
1175
|
+
} catch {
|
|
1176
|
+
return false;
|
|
1177
|
+
}
|
|
731
1178
|
}
|
|
1179
|
+
return false;
|
|
732
1180
|
}
|
|
733
1181
|
|
|
734
|
-
|
|
1182
|
+
// Returns true only if the message actually went out over an OPEN socket.
|
|
1183
|
+
// Callers MUST use the return value to decide whether to clear the input:
|
|
1184
|
+
// clearing on a false return is what loses the user's text on a dropped send.
|
|
1185
|
+
public sendMessage(text: string): boolean {
|
|
735
1186
|
const s = get(this.stateStore);
|
|
736
|
-
if (!s.sessionId) return;
|
|
1187
|
+
if (!s.sessionId) return false;
|
|
1188
|
+
|
|
1189
|
+
// The session's transcript is loaded but its live agent is still building
|
|
1190
|
+
// (cold, fast-first load). Reading is fine; sending is not possible yet, and
|
|
1191
|
+
// a message sent now would have no agent to receive it. Surface a clear,
|
|
1192
|
+
// recoverable hint and keep the text (the composer is disabled anyway, but a
|
|
1193
|
+
// programmatic caller could still reach here).
|
|
1194
|
+
if (s.agentPending) {
|
|
1195
|
+
this.stateStore.update((st: WhereverState) => ({
|
|
1196
|
+
...st,
|
|
1197
|
+
sessionError:
|
|
1198
|
+
st.sessionError ?? 'Preparing the session agent; please wait a moment, then resend.',
|
|
1199
|
+
}));
|
|
1200
|
+
return false;
|
|
1201
|
+
}
|
|
1202
|
+
|
|
1203
|
+
// Guard against sending on a dead / half-open socket. getIsConnected()
|
|
1204
|
+
// checks the real readyState (not the store's connected flag, which can lag
|
|
1205
|
+
// a half-open socket the liveness watchdog has not reaped yet). Sending here
|
|
1206
|
+
// would be silently dropped, the message would appear locally, then vanish
|
|
1207
|
+
// on reload. Surface a recoverable error and make sure we are reconnecting
|
|
1208
|
+
// instead of optimistically rendering a message that never left.
|
|
1209
|
+
if (!this.getIsConnected()) {
|
|
1210
|
+
this.stateStore.update((st: WhereverState) => ({
|
|
1211
|
+
...st,
|
|
1212
|
+
sessionError:
|
|
1213
|
+
'Not connected to the relay; your message was not sent. Reconnecting, then please resend.',
|
|
1214
|
+
}));
|
|
1215
|
+
if (!this.ws && !this.reconnectTimer) {
|
|
1216
|
+
this.scheduleReconnect();
|
|
1217
|
+
}
|
|
1218
|
+
return false;
|
|
1219
|
+
}
|
|
1220
|
+
|
|
1221
|
+
// Send first; only commit the optimistic local echo + clear the error once
|
|
1222
|
+
// the frame is confirmed handed to an OPEN socket. This way a send that
|
|
1223
|
+
// fails (a narrow race between the readyState check and send) leaves no
|
|
1224
|
+
// phantom local message and keeps the input intact for the caller to retry.
|
|
1225
|
+
const ok = this.send({type: 'message', message: text, sessionId: s.sessionId});
|
|
1226
|
+
if (!ok) {
|
|
1227
|
+
this.stateStore.update((st: WhereverState) => ({
|
|
1228
|
+
...st,
|
|
1229
|
+
sessionError:
|
|
1230
|
+
'Message failed to send (connection dropped). Please resend once reconnected.',
|
|
1231
|
+
}));
|
|
1232
|
+
return false;
|
|
1233
|
+
}
|
|
737
1234
|
|
|
738
|
-
this.stateStore.update((s: WhereverState) => ({...s, sessionError: null}));
|
|
739
|
-
|
|
740
1235
|
const message: ChatMessage = {
|
|
741
1236
|
id: this.generateId(),
|
|
742
1237
|
role: 'user',
|
|
@@ -745,12 +1240,12 @@ export class WhereverClient {
|
|
|
745
1240
|
isStreaming: false,
|
|
746
1241
|
sessionId: s.sessionId,
|
|
747
1242
|
};
|
|
748
|
-
this.stateStore.update((
|
|
749
|
-
...
|
|
750
|
-
|
|
1243
|
+
this.stateStore.update((st: WhereverState) => ({
|
|
1244
|
+
...st,
|
|
1245
|
+
sessionError: null,
|
|
1246
|
+
messages: [...st.messages, message],
|
|
751
1247
|
}));
|
|
752
|
-
|
|
753
|
-
this.send({type: 'message', message: text, sessionId: s.sessionId});
|
|
1248
|
+
return true;
|
|
754
1249
|
}
|
|
755
1250
|
|
|
756
1251
|
public abort() {
|
|
@@ -764,8 +1259,58 @@ export class WhereverClient {
|
|
|
764
1259
|
...s,
|
|
765
1260
|
conflict: null,
|
|
766
1261
|
sessionError: null,
|
|
1262
|
+
loadingSession: true,
|
|
1263
|
+
agentPending: false,
|
|
1264
|
+
}));
|
|
1265
|
+
this.send({type: 'session_load', sessionFile, cwd, model});
|
|
1266
|
+
this.armLoadWatchdog();
|
|
1267
|
+
}
|
|
1268
|
+
|
|
1269
|
+
// Switch from the currently-active session (if any) straight to another one in
|
|
1270
|
+
// a single, atomic step. Leaving + loading used to be done by the UI as two
|
|
1271
|
+
// calls separated by a 100ms setTimeout; that gap could strand the loading
|
|
1272
|
+
// state (a tap landing mid-switch, a leave whose load never fired) and leave
|
|
1273
|
+
// the "Loading session..." spinner hanging with an open sidebar. Doing both
|
|
1274
|
+
// here, synchronously, means there is never an in-between state and the
|
|
1275
|
+
// watchdog is always (re)armed for the new load, so a superseded or lost load
|
|
1276
|
+
// can never strand the UI: the latest tap always wins.
|
|
1277
|
+
public switchSession(sessionFile: string, cwd?: string, model?: string) {
|
|
1278
|
+
const s = get(this.stateStore);
|
|
1279
|
+
// Tapping the already-active session is a no-op (don't tear it down just to
|
|
1280
|
+
// reload the same history).
|
|
1281
|
+
if (s.activeSessionFile === sessionFile && !s.loadingSession && !s.resyncing) {
|
|
1282
|
+
return;
|
|
1283
|
+
}
|
|
1284
|
+
if (s.sessionId) {
|
|
1285
|
+
this.send({type: 'session_leave', sessionId: s.sessionId});
|
|
1286
|
+
}
|
|
1287
|
+
// Reset to a clean loading state for the target session in one update so the
|
|
1288
|
+
// old conversation clears immediately and the spinner reflects the new load.
|
|
1289
|
+
this.stateStore.update((st: WhereverState) => ({
|
|
1290
|
+
...st,
|
|
1291
|
+
messages: [],
|
|
1292
|
+
session: null,
|
|
1293
|
+
sessionId: null,
|
|
1294
|
+
activeSessionFile: null,
|
|
1295
|
+
activeCwd: null,
|
|
1296
|
+
activeModel: null,
|
|
1297
|
+
readOnly: false,
|
|
1298
|
+
conflict: null,
|
|
1299
|
+
sessionError: null,
|
|
1300
|
+
creatingSession: false,
|
|
1301
|
+
resyncing: false,
|
|
1302
|
+
agentPending: false,
|
|
1303
|
+
contextUsage: null,
|
|
1304
|
+
loadingSession: true,
|
|
767
1305
|
}));
|
|
1306
|
+
this.resumeSessionFile = null;
|
|
1307
|
+
this.resumeCwd = undefined;
|
|
1308
|
+
this.resumeModel = undefined;
|
|
1309
|
+
// Switching supersedes any in-flight create; disarm its watchdog so it can't
|
|
1310
|
+
// later fire against the newly loaded session.
|
|
1311
|
+
this.clearCreateWatchdog();
|
|
768
1312
|
this.send({type: 'session_load', sessionFile, cwd, model});
|
|
1313
|
+
this.armLoadWatchdog();
|
|
769
1314
|
}
|
|
770
1315
|
|
|
771
1316
|
public createSession(
|
|
@@ -780,6 +1325,7 @@ export class WhereverClient {
|
|
|
780
1325
|
conflict: null,
|
|
781
1326
|
sessionError: null,
|
|
782
1327
|
creatingSession: true,
|
|
1328
|
+
loadingSession: false,
|
|
783
1329
|
}));
|
|
784
1330
|
this.send({
|
|
785
1331
|
type: 'session_new',
|
|
@@ -789,11 +1335,25 @@ export class WhereverClient {
|
|
|
789
1335
|
createRemote,
|
|
790
1336
|
repoVisibility,
|
|
791
1337
|
});
|
|
1338
|
+
// Never let the blocking "Creating session..." overlay hang if the reply is
|
|
1339
|
+
// lost. Symmetrical with armLoadWatchdog for session_load.
|
|
1340
|
+
this.armCreateWatchdog();
|
|
792
1341
|
}
|
|
793
1342
|
|
|
794
1343
|
public leaveSession() {
|
|
795
1344
|
const s = get(this.stateStore);
|
|
796
|
-
|
|
1345
|
+
// Leaving abandons any in-flight create too, so disarm its watchdog even when
|
|
1346
|
+
// there is no sessionId yet (a create that has not resolved).
|
|
1347
|
+
this.clearCreateWatchdog();
|
|
1348
|
+
if (!s.sessionId) {
|
|
1349
|
+
if (s.creatingSession) {
|
|
1350
|
+
this.stateStore.update((st: WhereverState) => ({
|
|
1351
|
+
...st,
|
|
1352
|
+
creatingSession: false,
|
|
1353
|
+
}));
|
|
1354
|
+
}
|
|
1355
|
+
return;
|
|
1356
|
+
}
|
|
797
1357
|
this.send({type: 'session_leave', sessionId: s.sessionId});
|
|
798
1358
|
this.stateStore.update((s: WhereverState) => ({
|
|
799
1359
|
...s,
|
|
@@ -805,7 +1365,15 @@ export class WhereverClient {
|
|
|
805
1365
|
activeModel: null,
|
|
806
1366
|
readOnly: false,
|
|
807
1367
|
creatingSession: false,
|
|
1368
|
+
loadingSession: false,
|
|
1369
|
+
resyncing: false,
|
|
1370
|
+
agentPending: false,
|
|
1371
|
+
contextUsage: null,
|
|
808
1372
|
}));
|
|
1373
|
+
this.clearLoadWatchdog();
|
|
1374
|
+
this.resumeSessionFile = null;
|
|
1375
|
+
this.resumeCwd = undefined;
|
|
1376
|
+
this.resumeModel = undefined;
|
|
809
1377
|
}
|
|
810
1378
|
|
|
811
1379
|
public resolveConflict(action: 'take_over' | 'read_only', cwd?: string) {
|