@wherever-dev/client 0.2.1 → 0.2.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.
- package/CHANGELOG.md +37 -0
- package/dist/client.d.ts +22 -3
- package/dist/client.js +381 -14
- package/dist/client.js.map +1 -1
- package/dist/types.d.ts +8 -0
- package/package.json +6 -1
- package/src/client.ts +394 -19
- package/src/types.ts +19 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,42 @@
|
|
|
1
1
|
# @wherever-dev/client
|
|
2
2
|
|
|
3
|
+
## 0.2.2
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- cf11972: Stop silently losing (or wrongly queueing) a message sent right after returning to a backgrounded/idle tab.
|
|
8
|
+
|
|
9
|
+
Two related failures, both rooted in the suspend/resume-on-background path:
|
|
10
|
+
- Lost message: `send()` silently dropped any frame issued on a non-OPEN socket (null / CONNECTING / CLOSING / half-open), so a message typed during the reconnect+resync window rendered locally but never reached the server and was gone after reload. `send()` now reports whether the frame actually went out, and `sendMessage()` checks the real socket `readyState` (via `getIsConnected()`, not the laggy store `connected` flag) and only commits the local echo + clears the error after the frame is confirmed sent; on failure it surfaces a recoverable "not connected, your message was not sent" error, ensures a reconnect is scheduled, and returns `false`. `sendMessage()` now returns a success boolean so the composer only clears the textarea on a real send: a dropped send keeps the typed text intact for retry instead of losing it.
|
|
11
|
+
- Cannot send while disconnected + clear status: the chat composer is now disabled when the socket is not connected (previously only gated on having a session, so you could press send into a dead socket). The placeholder and the existing status line now show "Reconnecting to remote server..." / "Disconnected - cannot send" so the connection state is visible.
|
|
12
|
+
- Wrongly queued, never drained: `isStreaming` could stay stuck `true` across a suspend/resume (the `agent_end` that would clear it arrives on the now-dead socket), so the composer queued the next message as if the agent were still busy, and the queue never drained. `suspend()` now clears the stale `isStreaming` (the authoritative value is re-established by `session_created` on rejoin), `disconnect()` cancels any pending `agent_end` clear timer so it cannot fire against a fresh connection, and the composer only queues when streaming AND connected (and only auto-drains the queue when connected), falling through to a clear error otherwise.
|
|
13
|
+
|
|
14
|
+
- 605693a: Fix the sidebar getting stuck on "Loading session..." when switching sessions, where the previous session would close but the sidebar stayed open over a hanging spinner and tapping other sessions appeared to do nothing.
|
|
15
|
+
- client: add an atomic `switchSession()` that leaves the current session (if any) and loads the target in a single step. The UI previously did `leaveSession()` then `joinSession()` separated by a 100ms `setTimeout`; that gap could strand the loading state if a tap landed mid-switch or a leave's follow-up load never fired. `switchSession()` always (re)arms the load watchdog for the new target, so a superseded or lost load can never strand the UI and the latest tap always wins.
|
|
16
|
+
- client: shorten the session-load watchdog from 20s to 12s so a genuinely stuck load surfaces a recoverable error (and frees the UI) sooner.
|
|
17
|
+
- web: the sidebar now closes as soon as a load is in flight (loading/resync), not only once the session id is set. A stalled load no longer leaves the sidebar open on top of the spinner.
|
|
18
|
+
- web: the sidebar session click and the URL-hash change handler both use the atomic `switchSession()` path, removing the fragile leave -> setTimeout -> join dance.
|
|
19
|
+
|
|
20
|
+
- f9080e1: Fix a "Loading session..." spinner that could hang forever, and stop losing a typed message during session resync.
|
|
21
|
+
|
|
22
|
+
Stuck loading state (hash auto-join, sidebar selection, and tab-return after >8s):
|
|
23
|
+
- web: only take the resume (preserve-cache, rejoin-in-place) path when a session was actually suspended; otherwise do a plain `connect()` so the hash auto-join drives the load.
|
|
24
|
+
- web: make the hash auto-join self-healing by gating on live state (active session id + loading/resync flags) instead of a latched guard that connect/disconnect churn could strand, and debounce the join via a single tracked timer.
|
|
25
|
+
- client: add a session-load watchdog. The loading/resync flags are set the moment a `session_load` is issued and cleared when `message_history` (or an error/conflict/disconnect) arrives; if none ever comes back (a lost reply, a half-open socket, or any unforeseen edge), the watchdog now clears the flags and surfaces a recoverable error instead of spinning forever. Armed for the sidebar/hash join and the resume-on-reconnect path alike.
|
|
26
|
+
- client: add `hasSuspendedSession()` so callers can choose resume vs. plain connect.
|
|
27
|
+
|
|
28
|
+
Lost message draft during resync:
|
|
29
|
+
- web: keep the composer (ChatInput) mounted during reconnect/resync instead of swapping it for a status line, showing a thin "Reconnecting and syncing session..." banner above a disabled input so the in-progress text stays in the live DOM.
|
|
30
|
+
- web: also persist the draft to localStorage and restore it on (re)mount, so the typed message survives even a full unmount or reload. The draft is cleared automatically on a successful send. Drafts are scoped per session, with the no-session search composer getting its own shared draft: switching contexts does not carry text over (the box swaps to the target's own draft, or empties), and returning to a session (or back to search mode by closing the session or hitting the search button) brings its draft back.
|
|
31
|
+
|
|
32
|
+
- caabb92: Keep the session cached when the tab is backgrounded instead of reloading it on return.
|
|
33
|
+
|
|
34
|
+
Previously, backgrounding the tab disconnected and reset the whole client state, so coming back re-fetched and re-rendered the entire session (a visible "reload"). Now the connection is suspended without dropping the cached messages/session: the client records the active session, reconnects preserving the store, and rejoins+resyncs that session in place.
|
|
35
|
+
|
|
36
|
+
While reconnecting and resyncing, the composer is replaced by a "Reconnecting and syncing session..." status line so no message can be sent until the socket is back and history has resynced.
|
|
37
|
+
|
|
38
|
+
Also fixes the session error banner: long error text now wraps and scrolls within a bounded area instead of pushing the dismiss (X) button off-screen.
|
|
39
|
+
|
|
3
40
|
## 0.2.1
|
|
4
41
|
|
|
5
42
|
### Patch Changes
|
package/dist/client.d.ts
CHANGED
|
@@ -15,15 +15,33 @@ export declare class WhereverClient {
|
|
|
15
15
|
stateStore: Writable<WhereverState>;
|
|
16
16
|
private reconnectTimer;
|
|
17
17
|
private agentEndTimeout;
|
|
18
|
+
private loadWatchdog;
|
|
19
|
+
private static readonly LOAD_WATCHDOG_MS;
|
|
18
20
|
private reconnectAttempts;
|
|
19
21
|
private reconnectDelay;
|
|
20
22
|
private maxReconnectDelay;
|
|
23
|
+
private livenessTimer;
|
|
24
|
+
private heartbeatTimer;
|
|
25
|
+
private lastInboundAt;
|
|
26
|
+
private static readonly STALE_SOCKET_MS;
|
|
27
|
+
private static readonly TURN_STALL_MS;
|
|
28
|
+
private static readonly HEARTBEAT_MS;
|
|
21
29
|
private isInitialConnect;
|
|
30
|
+
private resumeSessionFile;
|
|
31
|
+
private resumeCwd?;
|
|
32
|
+
private resumeModel?;
|
|
22
33
|
private listeners;
|
|
23
34
|
private pendingUploads;
|
|
24
35
|
constructor(config: WhereverClientConfig);
|
|
25
|
-
connect(newConfig?: Partial<WhereverClientConfig
|
|
36
|
+
connect(newConfig?: Partial<WhereverClientConfig>, preserveState?: boolean): void;
|
|
26
37
|
disconnect(resetState?: boolean): void;
|
|
38
|
+
suspend(): void;
|
|
39
|
+
resume(): void;
|
|
40
|
+
hasSuspendedSession(): boolean;
|
|
41
|
+
private startLivenessWatchdog;
|
|
42
|
+
private stopLivenessWatchdog;
|
|
43
|
+
private armLoadWatchdog;
|
|
44
|
+
private clearLoadWatchdog;
|
|
27
45
|
private scheduleReconnect;
|
|
28
46
|
private handleMessage;
|
|
29
47
|
/**
|
|
@@ -39,10 +57,11 @@ export declare class WhereverClient {
|
|
|
39
57
|
* flight.
|
|
40
58
|
*/
|
|
41
59
|
loadMoreHistory(): void;
|
|
42
|
-
send(msg: any):
|
|
43
|
-
sendMessage(text: string):
|
|
60
|
+
send(msg: any): boolean;
|
|
61
|
+
sendMessage(text: string): boolean;
|
|
44
62
|
abort(): void;
|
|
45
63
|
joinSession(sessionFile: string, cwd?: string, model?: string): void;
|
|
64
|
+
switchSession(sessionFile: string, cwd?: string, model?: string): void;
|
|
46
65
|
createSession(cwd: string, model?: string, gitInit?: boolean, createRemote?: boolean, repoVisibility?: 'private' | 'public'): void;
|
|
47
66
|
leaveSession(): void;
|
|
48
67
|
resolveConflict(action: 'take_over' | 'read_only', cwd?: string): void;
|
package/dist/client.js
CHANGED
|
@@ -3,6 +3,8 @@ const defaultState = {
|
|
|
3
3
|
connected: false,
|
|
4
4
|
connecting: false,
|
|
5
5
|
creatingSession: false,
|
|
6
|
+
loadingSession: false,
|
|
7
|
+
resyncing: false,
|
|
6
8
|
error: null,
|
|
7
9
|
session: null,
|
|
8
10
|
sessionId: null,
|
|
@@ -21,6 +23,7 @@ const defaultState = {
|
|
|
21
23
|
historyTotalCount: 0,
|
|
22
24
|
historyOffset: 0,
|
|
23
25
|
loadingMoreHistory: false,
|
|
26
|
+
contextUsage: null,
|
|
24
27
|
};
|
|
25
28
|
export class WhereverClient {
|
|
26
29
|
ws = null;
|
|
@@ -28,10 +31,44 @@ export class WhereverClient {
|
|
|
28
31
|
stateStore;
|
|
29
32
|
reconnectTimer = null;
|
|
30
33
|
agentEndTimeout = null;
|
|
34
|
+
// Watchdog for an in-flight session_load. We set loadingSession/resyncing the
|
|
35
|
+
// moment a load is requested and clear them when message_history (or an
|
|
36
|
+
// error/conflict/disconnect) arrives. If none of those ever comes back (a lost
|
|
37
|
+
// reply, a server that answered for a different session, or any unforeseen
|
|
38
|
+
// edge), the "Loading session..." / "Reconnecting..." affordance would hang
|
|
39
|
+
// forever. This timer guarantees the load state always resolves: on expiry we
|
|
40
|
+
// clear the flags and surface a recoverable error instead of an endless spin.
|
|
41
|
+
loadWatchdog = null;
|
|
42
|
+
static LOAD_WATCHDOG_MS = 12_000;
|
|
31
43
|
reconnectAttempts = 0;
|
|
32
44
|
reconnectDelay = 2000;
|
|
33
45
|
maxReconnectDelay = 15000;
|
|
46
|
+
// Liveness watchdog: a half-open TCP socket fires neither 'close' nor 'error',
|
|
47
|
+
// so the existing reconnect machinery never triggers and the agent hangs
|
|
48
|
+
// forever (see work/observations/ws-half-open-connection-hangs-agent-no-heartbeat.md).
|
|
49
|
+
// We record the time of the last inbound frame and, if the socket goes silent
|
|
50
|
+
// for longer than STALE_SOCKET_MS, proactively tear it down and reconnect.
|
|
51
|
+
// A periodic app-level {type:'ping'} keeps a healthy connection refreshed even
|
|
52
|
+
// during long, token-less model turns.
|
|
53
|
+
livenessTimer = null;
|
|
54
|
+
heartbeatTimer = null;
|
|
55
|
+
lastInboundAt = 0;
|
|
56
|
+
// > the server heartbeat (when present) and any normal token-less gap, so a
|
|
57
|
+
// healthy connection is never falsely reaped; short enough to self-heal fast.
|
|
58
|
+
static STALE_SOCKET_MS = 60_000;
|
|
59
|
+
// While a turn is streaming, the keepalive pong should keep traffic flowing, so
|
|
60
|
+
// a shorter deadline surfaces a stalled transport (vs a merely slow model)
|
|
61
|
+
// faster. Still > one HEARTBEAT_MS so a single healthy pong keeps it fresh.
|
|
62
|
+
static TURN_STALL_MS = 45_000;
|
|
63
|
+
// Send a keepalive well under STALE_SOCKET_MS so the pong refreshes liveness.
|
|
64
|
+
static HEARTBEAT_MS = 25_000;
|
|
34
65
|
isInitialConnect = true;
|
|
66
|
+
// When set, the next successful (re)connection should rejoin the previously
|
|
67
|
+
// active session instead of starting blank. Used by resume() so a backgrounded
|
|
68
|
+
// tab returns to its cached conversation and resyncs history in place.
|
|
69
|
+
resumeSessionFile = null;
|
|
70
|
+
resumeCwd;
|
|
71
|
+
resumeModel;
|
|
35
72
|
listeners = new Set();
|
|
36
73
|
pendingUploads = new Map();
|
|
37
74
|
constructor(config) {
|
|
@@ -45,7 +82,7 @@ export class WhereverClient {
|
|
|
45
82
|
hideTools: !!this.config.hideTools,
|
|
46
83
|
});
|
|
47
84
|
}
|
|
48
|
-
connect(newConfig) {
|
|
85
|
+
connect(newConfig, preserveState = false) {
|
|
49
86
|
if (newConfig) {
|
|
50
87
|
this.config = {
|
|
51
88
|
...this.config,
|
|
@@ -53,12 +90,18 @@ export class WhereverClient {
|
|
|
53
90
|
};
|
|
54
91
|
}
|
|
55
92
|
this.disconnect(false);
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
93
|
+
// preserveState keeps the cached session/messages in the store across a
|
|
94
|
+
// reconnect (resume path), so the previous conversation stays visible while
|
|
95
|
+
// we reconnect and resync. The default (fresh connect) clears to a blank
|
|
96
|
+
// store as before.
|
|
97
|
+
this.stateStore.update(s => preserveState
|
|
98
|
+
? { ...s, connecting: true, error: null }
|
|
99
|
+
: {
|
|
100
|
+
...defaultState,
|
|
101
|
+
connecting: true,
|
|
102
|
+
hideThinking: !!this.config.hideThinking,
|
|
103
|
+
hideTools: !!this.config.hideTools,
|
|
104
|
+
});
|
|
62
105
|
const protocol = this.config.secure ? "wss" : "ws";
|
|
63
106
|
const host = this.config.host.startsWith('http')
|
|
64
107
|
? this.config.host.replace(/^https?:\/\//, '')
|
|
@@ -91,19 +134,43 @@ export class WhereverClient {
|
|
|
91
134
|
const onOpen = () => {
|
|
92
135
|
if (this.ws !== currentWs)
|
|
93
136
|
return;
|
|
137
|
+
if (!this.isInitialConnect) {
|
|
138
|
+
console.info('[wherever] reconnected to relay');
|
|
139
|
+
}
|
|
94
140
|
this.reconnectAttempts = 0;
|
|
95
141
|
this.reconnectDelay = 2000;
|
|
96
142
|
this.isInitialConnect = false;
|
|
143
|
+
this.startLivenessWatchdog();
|
|
97
144
|
this.stateStore.update(s => ({
|
|
98
145
|
...s,
|
|
99
146
|
connected: true,
|
|
100
147
|
connecting: false,
|
|
101
148
|
error: null
|
|
102
149
|
}));
|
|
150
|
+
// Resume path: rejoin the previously-active session so its history is
|
|
151
|
+
// resynced in place. resyncing stays true until message_history (or an
|
|
152
|
+
// error/conflict) arrives, keeping the "reconnecting" affordance up and
|
|
153
|
+
// input blocked without dropping the cached messages.
|
|
154
|
+
if (this.resumeSessionFile) {
|
|
155
|
+
const file = this.resumeSessionFile;
|
|
156
|
+
const cwd = this.resumeCwd;
|
|
157
|
+
const model = this.resumeModel;
|
|
158
|
+
this.resumeSessionFile = null;
|
|
159
|
+
this.resumeCwd = undefined;
|
|
160
|
+
this.resumeModel = undefined;
|
|
161
|
+
this.send({ type: 'session_load', sessionFile: file, cwd, model });
|
|
162
|
+
this.armLoadWatchdog();
|
|
163
|
+
}
|
|
164
|
+
else {
|
|
165
|
+
this.stateStore.update(s => (s.resyncing ? { ...s, resyncing: false } : s));
|
|
166
|
+
}
|
|
103
167
|
};
|
|
104
168
|
const onMessage = (event) => {
|
|
105
169
|
if (this.ws !== currentWs)
|
|
106
170
|
return;
|
|
171
|
+
// Any inbound frame (including the pong reply to our keepalive) proves the
|
|
172
|
+
// socket is alive and resets the stale-socket watchdog.
|
|
173
|
+
this.lastInboundAt = Date.now();
|
|
107
174
|
try {
|
|
108
175
|
const rawData = typeof event.data === 'string' ? event.data : event.data.toString();
|
|
109
176
|
const msg = JSON.parse(rawData);
|
|
@@ -116,11 +183,16 @@ export class WhereverClient {
|
|
|
116
183
|
const onClose = () => {
|
|
117
184
|
if (this.ws !== currentWs)
|
|
118
185
|
return;
|
|
186
|
+
this.stopLivenessWatchdog();
|
|
187
|
+
this.clearLoadWatchdog();
|
|
119
188
|
this.ws = null;
|
|
120
189
|
this.stateStore.update(s => ({
|
|
121
190
|
...s,
|
|
122
191
|
connected: false,
|
|
123
192
|
connecting: false,
|
|
193
|
+
// Never leave a session-load spinner stuck if the socket drops mid-load.
|
|
194
|
+
loadingSession: false,
|
|
195
|
+
creatingSession: false,
|
|
124
196
|
}));
|
|
125
197
|
this.scheduleReconnect();
|
|
126
198
|
};
|
|
@@ -150,6 +222,14 @@ export class WhereverClient {
|
|
|
150
222
|
clearTimeout(this.reconnectTimer);
|
|
151
223
|
this.reconnectTimer = null;
|
|
152
224
|
}
|
|
225
|
+
// A pending agent_end clear timer belongs to the socket we are tearing down.
|
|
226
|
+
// Leaving it armed lets it fire against a freshly (re)connected session's
|
|
227
|
+
// state, so cancel it here.
|
|
228
|
+
if (this.agentEndTimeout) {
|
|
229
|
+
clearTimeout(this.agentEndTimeout);
|
|
230
|
+
this.agentEndTimeout = null;
|
|
231
|
+
}
|
|
232
|
+
this.stopLivenessWatchdog();
|
|
153
233
|
if (this.ws) {
|
|
154
234
|
try {
|
|
155
235
|
if (typeof this.ws.removeAllListeners === 'function') {
|
|
@@ -168,12 +248,172 @@ export class WhereverClient {
|
|
|
168
248
|
});
|
|
169
249
|
}
|
|
170
250
|
}
|
|
251
|
+
// Suspend the connection without tearing down the cached session state. Used
|
|
252
|
+
// when the tab is backgrounded: closing the WebSocket improves bfcache
|
|
253
|
+
// eligibility, but we keep messages/sessionId so returning is a cheap resync
|
|
254
|
+
// rather than a full reload. Records the active session so resume() can rejoin
|
|
255
|
+
// it. Does NOT schedule a reconnect (disconnect(false) clears that timer).
|
|
256
|
+
suspend() {
|
|
257
|
+
const s = get(this.stateStore);
|
|
258
|
+
if (s.activeSessionFile) {
|
|
259
|
+
this.resumeSessionFile = s.activeSessionFile;
|
|
260
|
+
this.resumeCwd = s.activeCwd ?? undefined;
|
|
261
|
+
this.resumeModel = s.activeModel ?? undefined;
|
|
262
|
+
}
|
|
263
|
+
// The socket producing the live stream is going away. If we carry a stale
|
|
264
|
+
// isStreaming:true across the suspend/resume gap, the composer will wrongly
|
|
265
|
+
// queue the next message as if the agent were still busy (and the queue
|
|
266
|
+
// never drains because no agent_end ever arrives on the dead socket). The
|
|
267
|
+
// authoritative value is re-established by session_created on rejoin.
|
|
268
|
+
if (s.isStreaming) {
|
|
269
|
+
this.stateStore.update(st => ({ ...st, isStreaming: false }));
|
|
270
|
+
}
|
|
271
|
+
this.disconnect(false);
|
|
272
|
+
}
|
|
273
|
+
// Resume after suspend(): reconnect while preserving the cached store, mark
|
|
274
|
+
// the session as resyncing, and let onOpen rejoin the recorded session. If
|
|
275
|
+
// there is no active session to rejoin, this is just a state-preserving
|
|
276
|
+
// reconnect.
|
|
277
|
+
resume() {
|
|
278
|
+
const s = get(this.stateStore);
|
|
279
|
+
if (s.connected || s.connecting)
|
|
280
|
+
return;
|
|
281
|
+
if (this.resumeSessionFile) {
|
|
282
|
+
this.stateStore.update(st => ({ ...st, resyncing: true }));
|
|
283
|
+
// Arm here too: if the socket never opens, onOpen never runs and the
|
|
284
|
+
// resync affordance would otherwise hang. onClose also clears it, but the
|
|
285
|
+
// watchdog covers the half-open / never-opens case.
|
|
286
|
+
this.armLoadWatchdog();
|
|
287
|
+
}
|
|
288
|
+
this.connect(undefined, true);
|
|
289
|
+
}
|
|
290
|
+
// True when suspend() recorded an active session to rejoin on the next resume.
|
|
291
|
+
// Callers use this to take the resume (preserve-cache, rejoin-in-place) path
|
|
292
|
+
// only when there is actually a suspended session; otherwise a plain connect()
|
|
293
|
+
// is correct and avoids racing/latching the hash auto-join on a fresh load.
|
|
294
|
+
hasSuspendedSession() {
|
|
295
|
+
return this.resumeSessionFile !== null;
|
|
296
|
+
}
|
|
297
|
+
// Start (or restart) the stale-socket watchdog + keepalive for the current
|
|
298
|
+
// socket. A half-open connection emits no 'close'/'error', so without this the
|
|
299
|
+
// existing reconnect logic would never fire and the agent would hang forever.
|
|
300
|
+
startLivenessWatchdog() {
|
|
301
|
+
this.stopLivenessWatchdog();
|
|
302
|
+
this.lastInboundAt = Date.now();
|
|
303
|
+
const sendBeat = () => {
|
|
304
|
+
// Keep a healthy connection warm so the pong refreshes lastInboundAt even
|
|
305
|
+
// during long, token-less model turns.
|
|
306
|
+
try {
|
|
307
|
+
this.ping();
|
|
308
|
+
}
|
|
309
|
+
catch { }
|
|
310
|
+
};
|
|
311
|
+
if (typeof setInterval === 'function') {
|
|
312
|
+
this.heartbeatTimer = setInterval(sendBeat, WhereverClient.HEARTBEAT_MS);
|
|
313
|
+
if (this.heartbeatTimer && typeof this.heartbeatTimer.unref === 'function') {
|
|
314
|
+
this.heartbeatTimer.unref();
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
const checkLiveness = () => {
|
|
318
|
+
if (!this.ws)
|
|
319
|
+
return;
|
|
320
|
+
const silentFor = Date.now() - this.lastInboundAt;
|
|
321
|
+
const streaming = get(this.stateStore).isStreaming;
|
|
322
|
+
// Per-turn stall timeout: while a turn is in flight the heartbeat pong (and,
|
|
323
|
+
// normally, tokens) should keep traffic flowing, so a shorter deadline
|
|
324
|
+
// distinguishes "model is slow" (heartbeat still arriving -> not stale) from
|
|
325
|
+
// "transport is dead" (heartbeat stopped). When idle, fall back to the
|
|
326
|
+
// generic stale-socket threshold.
|
|
327
|
+
const threshold = streaming
|
|
328
|
+
? WhereverClient.TURN_STALL_MS
|
|
329
|
+
: WhereverClient.STALE_SOCKET_MS;
|
|
330
|
+
if (silentFor < threshold)
|
|
331
|
+
return;
|
|
332
|
+
// The socket has been silent past the threshold: treat it as dead. Tearing
|
|
333
|
+
// it down forcibly is what makes a half-open connection recover, since the
|
|
334
|
+
// OS never produced a FIN/RST to trigger the normal close path.
|
|
335
|
+
console.warn(`[wherever] relay connection stale: no inbound frame for ${silentFor}ms ` +
|
|
336
|
+
`(threshold ${threshold}ms, ${streaming ? 'mid-turn' : 'idle'}); ` +
|
|
337
|
+
`tearing down dead socket and reconnecting`);
|
|
338
|
+
this.stopLivenessWatchdog();
|
|
339
|
+
const deadWs = this.ws;
|
|
340
|
+
this.ws = null;
|
|
341
|
+
try {
|
|
342
|
+
if (typeof deadWs.terminate === 'function') {
|
|
343
|
+
deadWs.terminate();
|
|
344
|
+
}
|
|
345
|
+
else if (typeof deadWs.close === 'function') {
|
|
346
|
+
deadWs.close();
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
catch { }
|
|
350
|
+
this.stateStore.update(s => ({
|
|
351
|
+
...s,
|
|
352
|
+
connected: false,
|
|
353
|
+
connecting: false,
|
|
354
|
+
loadingSession: false,
|
|
355
|
+
creatingSession: false,
|
|
356
|
+
// If a turn was in flight, surface it as a recoverable error so the UI
|
|
357
|
+
// shows "the transport stalled" rather than silently parking mid-stream.
|
|
358
|
+
sessionError: streaming
|
|
359
|
+
? 'Connection to relay stalled mid-turn; reconnecting...'
|
|
360
|
+
: s.sessionError,
|
|
361
|
+
isStreaming: false,
|
|
362
|
+
}));
|
|
363
|
+
this.scheduleReconnect();
|
|
364
|
+
};
|
|
365
|
+
if (typeof setInterval === 'function') {
|
|
366
|
+
this.livenessTimer = setInterval(checkLiveness, WhereverClient.HEARTBEAT_MS);
|
|
367
|
+
if (this.livenessTimer && typeof this.livenessTimer.unref === 'function') {
|
|
368
|
+
this.livenessTimer.unref();
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
stopLivenessWatchdog() {
|
|
373
|
+
if (this.heartbeatTimer) {
|
|
374
|
+
clearInterval(this.heartbeatTimer);
|
|
375
|
+
this.heartbeatTimer = null;
|
|
376
|
+
}
|
|
377
|
+
if (this.livenessTimer) {
|
|
378
|
+
clearInterval(this.livenessTimer);
|
|
379
|
+
this.livenessTimer = null;
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
// Arm (or re-arm) the load watchdog. Called whenever a session_load is issued
|
|
383
|
+
// so an unresolved load can never strand the loading UI. Idempotent: a fresh
|
|
384
|
+
// load resets the deadline.
|
|
385
|
+
armLoadWatchdog() {
|
|
386
|
+
this.clearLoadWatchdog();
|
|
387
|
+
this.loadWatchdog = setTimeout(() => {
|
|
388
|
+
this.loadWatchdog = null;
|
|
389
|
+
const s = get(this.stateStore);
|
|
390
|
+
if (!s.loadingSession && !s.resyncing)
|
|
391
|
+
return;
|
|
392
|
+
console.warn('[wherever] session load timed out; clearing loading state');
|
|
393
|
+
this.stateStore.update(st => ({
|
|
394
|
+
...st,
|
|
395
|
+
loadingSession: false,
|
|
396
|
+
resyncing: false,
|
|
397
|
+
sessionError: st.sessionError ||
|
|
398
|
+
'Loading the session timed out. Please retry from the sidebar or reload.',
|
|
399
|
+
}));
|
|
400
|
+
}, WhereverClient.LOAD_WATCHDOG_MS);
|
|
401
|
+
}
|
|
402
|
+
// Clear the load watchdog. Called at every point the load resolves
|
|
403
|
+
// (message_history, session_error, session_conflict, disconnect, leave).
|
|
404
|
+
clearLoadWatchdog() {
|
|
405
|
+
if (this.loadWatchdog) {
|
|
406
|
+
clearTimeout(this.loadWatchdog);
|
|
407
|
+
this.loadWatchdog = null;
|
|
408
|
+
}
|
|
409
|
+
}
|
|
171
410
|
scheduleReconnect() {
|
|
172
411
|
if (this.reconnectTimer)
|
|
173
412
|
return;
|
|
174
413
|
this.reconnectTimer = setTimeout(() => {
|
|
175
414
|
this.reconnectTimer = null;
|
|
176
415
|
this.reconnectDelay = Math.min(this.reconnectDelay * 1.5, this.maxReconnectDelay);
|
|
416
|
+
console.info(`[wherever] reconnecting to relay (attempt ${++this.reconnectAttempts})`);
|
|
177
417
|
this.stateStore.update(s => ({
|
|
178
418
|
...s,
|
|
179
419
|
connecting: true,
|
|
@@ -191,6 +431,18 @@ export class WhereverClient {
|
|
|
191
431
|
console.error("Error in message listener:", err);
|
|
192
432
|
}
|
|
193
433
|
}
|
|
434
|
+
// Any message that resolves an in-flight session_load disarms the watchdog.
|
|
435
|
+
// session_created arrives just before message_history; message_history is the
|
|
436
|
+
// real completion, but an error/conflict/destroy/interrupt also resolves it.
|
|
437
|
+
switch (msg.type) {
|
|
438
|
+
case 'message_history':
|
|
439
|
+
case 'session_error':
|
|
440
|
+
case 'session_conflict':
|
|
441
|
+
case 'session_destroyed':
|
|
442
|
+
case 'session_interrupted':
|
|
443
|
+
this.clearLoadWatchdog();
|
|
444
|
+
break;
|
|
445
|
+
}
|
|
194
446
|
switch (msg.type) {
|
|
195
447
|
case 'connected':
|
|
196
448
|
this.stateStore.update((s) => ({
|
|
@@ -449,6 +701,18 @@ export class WhereverClient {
|
|
|
449
701
|
activeModel: msg.model,
|
|
450
702
|
isStreaming: msg.isStreaming ?? false,
|
|
451
703
|
creatingSession: false,
|
|
704
|
+
// The server forces read-only for sessions in a configured
|
|
705
|
+
// sessions.readOnly folder (observe-only fleet view).
|
|
706
|
+
readOnly: msg.readOnly ?? false,
|
|
707
|
+
// Initial context-usage snapshot for the new session (null if unknown;
|
|
708
|
+
// live updates arrive via 'context_usage').
|
|
709
|
+
contextUsage: msg.contextUsage ?? null,
|
|
710
|
+
}));
|
|
711
|
+
break;
|
|
712
|
+
case 'context_usage':
|
|
713
|
+
this.stateStore.update((s) => ({
|
|
714
|
+
...s,
|
|
715
|
+
contextUsage: msg.contextUsage ?? null,
|
|
452
716
|
}));
|
|
453
717
|
break;
|
|
454
718
|
case 'session_destroyed':
|
|
@@ -462,6 +726,7 @@ export class WhereverClient {
|
|
|
462
726
|
activeSessionFile: null,
|
|
463
727
|
activeCwd: null,
|
|
464
728
|
activeModel: null,
|
|
729
|
+
loadingSession: false,
|
|
465
730
|
};
|
|
466
731
|
}
|
|
467
732
|
return s;
|
|
@@ -473,6 +738,8 @@ export class WhereverClient {
|
|
|
473
738
|
sessionError: msg.error,
|
|
474
739
|
isStreaming: false,
|
|
475
740
|
creatingSession: false,
|
|
741
|
+
loadingSession: false,
|
|
742
|
+
resyncing: false,
|
|
476
743
|
}));
|
|
477
744
|
break;
|
|
478
745
|
case 'session_conflict':
|
|
@@ -484,6 +751,8 @@ export class WhereverClient {
|
|
|
484
751
|
conflictingCwd: msg.conflictingCwd,
|
|
485
752
|
},
|
|
486
753
|
creatingSession: false,
|
|
754
|
+
loadingSession: false,
|
|
755
|
+
resyncing: false,
|
|
487
756
|
}));
|
|
488
757
|
break;
|
|
489
758
|
case 'session_interrupted':
|
|
@@ -498,6 +767,7 @@ export class WhereverClient {
|
|
|
498
767
|
activeCwd: null,
|
|
499
768
|
activeModel: null,
|
|
500
769
|
creatingSession: false,
|
|
770
|
+
loadingSession: false,
|
|
501
771
|
}));
|
|
502
772
|
break;
|
|
503
773
|
case 'message_history':
|
|
@@ -511,6 +781,8 @@ export class WhereverClient {
|
|
|
511
781
|
historyTotalCount: totalCount,
|
|
512
782
|
historyOffset: offset,
|
|
513
783
|
loadingMoreHistory: false,
|
|
784
|
+
loadingSession: false,
|
|
785
|
+
resyncing: false,
|
|
514
786
|
};
|
|
515
787
|
});
|
|
516
788
|
break;
|
|
@@ -640,16 +912,58 @@ export class WhereverClient {
|
|
|
640
912
|
beforeOffset: s.historyOffset,
|
|
641
913
|
});
|
|
642
914
|
}
|
|
915
|
+
// Returns true only when the frame was actually handed to an OPEN socket.
|
|
916
|
+
// A non-OPEN (null / CONNECTING / CLOSING / half-open) socket silently
|
|
917
|
+
// dropping the frame is what made messages vanish: they rendered locally but
|
|
918
|
+
// never reached the server, so they were gone after a reload. Callers that
|
|
919
|
+
// carry user intent (sendMessage) must check this and surface the failure.
|
|
643
920
|
send(msg) {
|
|
644
921
|
if (this.ws && this.ws.readyState === 1 /* OPEN */) {
|
|
645
|
-
|
|
922
|
+
try {
|
|
923
|
+
this.ws.send(JSON.stringify(msg));
|
|
924
|
+
return true;
|
|
925
|
+
}
|
|
926
|
+
catch {
|
|
927
|
+
return false;
|
|
928
|
+
}
|
|
646
929
|
}
|
|
930
|
+
return false;
|
|
647
931
|
}
|
|
932
|
+
// Returns true only if the message actually went out over an OPEN socket.
|
|
933
|
+
// Callers MUST use the return value to decide whether to clear the input:
|
|
934
|
+
// clearing on a false return is what loses the user's text on a dropped send.
|
|
648
935
|
sendMessage(text) {
|
|
649
936
|
const s = get(this.stateStore);
|
|
650
937
|
if (!s.sessionId)
|
|
651
|
-
return;
|
|
652
|
-
|
|
938
|
+
return false;
|
|
939
|
+
// Guard against sending on a dead / half-open socket. getIsConnected()
|
|
940
|
+
// checks the real readyState (not the store's connected flag, which can lag
|
|
941
|
+
// a half-open socket the liveness watchdog has not reaped yet). Sending here
|
|
942
|
+
// would be silently dropped, the message would appear locally, then vanish
|
|
943
|
+
// on reload. Surface a recoverable error and make sure we are reconnecting
|
|
944
|
+
// instead of optimistically rendering a message that never left.
|
|
945
|
+
if (!this.getIsConnected()) {
|
|
946
|
+
this.stateStore.update((st) => ({
|
|
947
|
+
...st,
|
|
948
|
+
sessionError: 'Not connected to the relay; your message was not sent. Reconnecting, then please resend.',
|
|
949
|
+
}));
|
|
950
|
+
if (!this.ws && !this.reconnectTimer) {
|
|
951
|
+
this.scheduleReconnect();
|
|
952
|
+
}
|
|
953
|
+
return false;
|
|
954
|
+
}
|
|
955
|
+
// Send first; only commit the optimistic local echo + clear the error once
|
|
956
|
+
// the frame is confirmed handed to an OPEN socket. This way a send that
|
|
957
|
+
// fails (a narrow race between the readyState check and send) leaves no
|
|
958
|
+
// phantom local message and keeps the input intact for the caller to retry.
|
|
959
|
+
const ok = this.send({ type: 'message', message: text, sessionId: s.sessionId });
|
|
960
|
+
if (!ok) {
|
|
961
|
+
this.stateStore.update((st) => ({
|
|
962
|
+
...st,
|
|
963
|
+
sessionError: 'Message failed to send (connection dropped). Please resend once reconnected.',
|
|
964
|
+
}));
|
|
965
|
+
return false;
|
|
966
|
+
}
|
|
653
967
|
const message = {
|
|
654
968
|
id: this.generateId(),
|
|
655
969
|
role: 'user',
|
|
@@ -658,11 +972,12 @@ export class WhereverClient {
|
|
|
658
972
|
isStreaming: false,
|
|
659
973
|
sessionId: s.sessionId,
|
|
660
974
|
};
|
|
661
|
-
this.stateStore.update((
|
|
662
|
-
...
|
|
663
|
-
|
|
975
|
+
this.stateStore.update((st) => ({
|
|
976
|
+
...st,
|
|
977
|
+
sessionError: null,
|
|
978
|
+
messages: [...st.messages, message],
|
|
664
979
|
}));
|
|
665
|
-
|
|
980
|
+
return true;
|
|
666
981
|
}
|
|
667
982
|
abort() {
|
|
668
983
|
const s = get(this.stateStore);
|
|
@@ -675,8 +990,52 @@ export class WhereverClient {
|
|
|
675
990
|
...s,
|
|
676
991
|
conflict: null,
|
|
677
992
|
sessionError: null,
|
|
993
|
+
loadingSession: true,
|
|
994
|
+
}));
|
|
995
|
+
this.send({ type: 'session_load', sessionFile, cwd, model });
|
|
996
|
+
this.armLoadWatchdog();
|
|
997
|
+
}
|
|
998
|
+
// Switch from the currently-active session (if any) straight to another one in
|
|
999
|
+
// a single, atomic step. Leaving + loading used to be done by the UI as two
|
|
1000
|
+
// calls separated by a 100ms setTimeout; that gap could strand the loading
|
|
1001
|
+
// state (a tap landing mid-switch, a leave whose load never fired) and leave
|
|
1002
|
+
// the "Loading session..." spinner hanging with an open sidebar. Doing both
|
|
1003
|
+
// here, synchronously, means there is never an in-between state and the
|
|
1004
|
+
// watchdog is always (re)armed for the new load, so a superseded or lost load
|
|
1005
|
+
// can never strand the UI: the latest tap always wins.
|
|
1006
|
+
switchSession(sessionFile, cwd, model) {
|
|
1007
|
+
const s = get(this.stateStore);
|
|
1008
|
+
// Tapping the already-active session is a no-op (don't tear it down just to
|
|
1009
|
+
// reload the same history).
|
|
1010
|
+
if (s.activeSessionFile === sessionFile && !s.loadingSession && !s.resyncing) {
|
|
1011
|
+
return;
|
|
1012
|
+
}
|
|
1013
|
+
if (s.sessionId) {
|
|
1014
|
+
this.send({ type: 'session_leave', sessionId: s.sessionId });
|
|
1015
|
+
}
|
|
1016
|
+
// Reset to a clean loading state for the target session in one update so the
|
|
1017
|
+
// old conversation clears immediately and the spinner reflects the new load.
|
|
1018
|
+
this.stateStore.update((st) => ({
|
|
1019
|
+
...st,
|
|
1020
|
+
messages: [],
|
|
1021
|
+
session: null,
|
|
1022
|
+
sessionId: null,
|
|
1023
|
+
activeSessionFile: null,
|
|
1024
|
+
activeCwd: null,
|
|
1025
|
+
activeModel: null,
|
|
1026
|
+
readOnly: false,
|
|
1027
|
+
conflict: null,
|
|
1028
|
+
sessionError: null,
|
|
1029
|
+
creatingSession: false,
|
|
1030
|
+
resyncing: false,
|
|
1031
|
+
contextUsage: null,
|
|
1032
|
+
loadingSession: true,
|
|
678
1033
|
}));
|
|
1034
|
+
this.resumeSessionFile = null;
|
|
1035
|
+
this.resumeCwd = undefined;
|
|
1036
|
+
this.resumeModel = undefined;
|
|
679
1037
|
this.send({ type: 'session_load', sessionFile, cwd, model });
|
|
1038
|
+
this.armLoadWatchdog();
|
|
680
1039
|
}
|
|
681
1040
|
createSession(cwd, model, gitInit, createRemote, repoVisibility) {
|
|
682
1041
|
this.stateStore.update((s) => ({
|
|
@@ -684,6 +1043,7 @@ export class WhereverClient {
|
|
|
684
1043
|
conflict: null,
|
|
685
1044
|
sessionError: null,
|
|
686
1045
|
creatingSession: true,
|
|
1046
|
+
loadingSession: false,
|
|
687
1047
|
}));
|
|
688
1048
|
this.send({
|
|
689
1049
|
type: 'session_new',
|
|
@@ -709,7 +1069,14 @@ export class WhereverClient {
|
|
|
709
1069
|
activeModel: null,
|
|
710
1070
|
readOnly: false,
|
|
711
1071
|
creatingSession: false,
|
|
1072
|
+
loadingSession: false,
|
|
1073
|
+
resyncing: false,
|
|
1074
|
+
contextUsage: null,
|
|
712
1075
|
}));
|
|
1076
|
+
this.clearLoadWatchdog();
|
|
1077
|
+
this.resumeSessionFile = null;
|
|
1078
|
+
this.resumeCwd = undefined;
|
|
1079
|
+
this.resumeModel = undefined;
|
|
713
1080
|
}
|
|
714
1081
|
resolveConflict(action, cwd) {
|
|
715
1082
|
const s = get(this.stateStore);
|