@wherever-dev/client 0.5.3 → 0.6.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/src/client.ts CHANGED
@@ -1,5 +1,24 @@
1
1
  import { writable, get, type Writable } from "sveltore";
2
- import { type ChatMessage, type WhereverState, skillInvocationIdentity } from "./types.js";
2
+ import {
3
+ type ChatMessage,
4
+ type RestoreInfo,
5
+ type RestoreJobInfo,
6
+ type WhereverState,
7
+ skillInvocationIdentity,
8
+ } from "./types.js";
9
+
10
+ /**
11
+ * Per-send options for a user message.
12
+ *
13
+ * `conversationMode` is the per-turn CONVERSATION-MODE SIGNAL: true means a spoken
14
+ * conversation is active for this send (the web app stamps it when its
15
+ * conversation-mode AND speak-replies knobs are both active), so the agent adds a
16
+ * short spoken `say` reply alongside its written answer. Omitted/false means off,
17
+ * which is exactly the pre-existing behaviour.
18
+ */
19
+ export interface SendMessageOptions {
20
+ conversationMode?: boolean;
21
+ }
3
22
 
4
23
  export interface WhereverClientConfig {
5
24
  host: string;
@@ -9,6 +28,29 @@ export interface WhereverClientConfig {
9
28
  WebSocketCtor?: any;
10
29
  hideThinking?: boolean;
11
30
  hideTools?: boolean;
31
+ // Stable identity for THIS viewer across reconnects. The server keys its
32
+ // per-connection client records by socket, so a silently dropped socket (phone
33
+ // sleep, network switch, half-open TCP) leaves a PHANTOM client attached to
34
+ // the session until the heartbeat reaper notices, up to a minute later. In
35
+ // that window the phantom counts as "another viewer", which turns an explicit
36
+ // "New Session Here" into a folder conflict (read-only attach to the existing
37
+ // session). Sending a stable key lets the server evict this viewer's own
38
+ // previous connection the moment it reconnects. Callers should scope the key
39
+ // per TAB (e.g. sessionStorage), never per browser: two real tabs must stay
40
+ // two distinct viewers. Omitted -> a per-instance key is generated, which
41
+ // already covers in-process reconnects.
42
+ clientKey?: string;
43
+ // Called when the client had to take a NEW clientKey because the server
44
+ // reported this one as superseded (two viewers ended up sharing it). Persist it
45
+ // wherever `clientKey` came from, so the collision is resolved for good rather
46
+ // than re-created on the next reconnect.
47
+ onClientKeyChange?: (key: string) => void;
48
+ }
49
+
50
+ // Per-instance fallback identity: stable for the lifetime of this client object,
51
+ // which is exactly the lifetime across which reconnects happen.
52
+ function generateClientKey(): string {
53
+ return `ck-${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`;
12
54
  }
13
55
 
14
56
  const defaultState: WhereverState = {
@@ -24,7 +66,10 @@ const defaultState: WhereverState = {
24
66
  isStreaming: false,
25
67
  messages: [],
26
68
  clientId: null,
69
+ serverVersion: null,
27
70
  folderConflict: null,
71
+ folderMissing: null,
72
+ restore: null,
28
73
  isInterrupted: false,
29
74
  notice: null,
30
75
  sudoPrompt: null,
@@ -46,6 +91,10 @@ const defaultState: WhereverState = {
46
91
  export class WhereverClient {
47
92
  private ws: any = null;
48
93
  private config: WhereverClientConfig;
94
+ // Identity sent on every connect so the server can retire this viewer's own
95
+ // stale/phantom connection instead of counting it as a second viewer. Replaced
96
+ // (once) if the server reports it as superseded by another live connection.
97
+ private clientKey: string;
49
98
  public stateStore: Writable<WhereverState>;
50
99
  private reconnectTimer: any = null;
51
100
  private agentEndTimeout: any = null;
@@ -131,6 +180,7 @@ export class WhereverClient {
131
180
  secure: true,
132
181
  ...config
133
182
  };
183
+ this.clientKey = this.config.clientKey || generateClientKey();
134
184
  this.stateStore = writable<WhereverState>({
135
185
  ...defaultState,
136
186
  hideThinking: !!this.config.hideThinking,
@@ -165,8 +215,13 @@ export class WhereverClient {
165
215
  const host = this.config.host.startsWith('http')
166
216
  ? this.config.host.replace(/^https?:\/\//, '')
167
217
  : this.config.host;
168
- const tokenQuery = this.config.token ? `?token=${encodeURIComponent(this.config.token)}` : "";
169
- const wsUrl = `${protocol}://${host}:${this.config.port}/ws${tokenQuery}`;
218
+ // clientKey rides on the URL (not a post-connect frame) so the server can
219
+ // evict this viewer's previous connection BEFORE any session traffic is
220
+ // handled, closing the phantom-viewer window entirely.
221
+ const params: string[] = [];
222
+ if (this.config.token) params.push(`token=${encodeURIComponent(this.config.token)}`);
223
+ params.push(`clientKey=${encodeURIComponent(this.clientKey)}`);
224
+ const wsUrl = `${protocol}://${host}:${this.config.port}/ws?${params.join('&')}`;
170
225
 
171
226
  const WebSocketImpl = this.config.WebSocketCtor || (typeof globalThis !== 'undefined' ? (globalThis as any).WebSocket : null);
172
227
 
@@ -693,10 +748,26 @@ export class WhereverClient {
693
748
  connected: true,
694
749
  connecting: false,
695
750
  clientId: msg.clientId,
751
+ serverVersion: msg.serverVersion ?? null,
696
752
  error: null,
697
753
  }));
698
754
  break;
699
755
 
756
+ case 'connection_superseded':
757
+ // A newer connection arrived carrying OUR clientKey, so the server is
758
+ // retiring this socket as a superseded duplicate. Receiving this proves we
759
+ // are alive, i.e. the key is being shared by accident (a duplicated tab
760
+ // clones sessionStorage). Take a fresh identity BEFORE the reconnect the
761
+ // imminent close will schedule, so the two connections stop evicting each
762
+ // other; the owner of the key keeps it and we come back as our own viewer.
763
+ this.clientKey = generateClientKey();
764
+ try {
765
+ this.config.onClientKeyChange?.(this.clientKey);
766
+ } catch (err) {
767
+ console.error('onClientKeyChange failed:', err);
768
+ }
769
+ break;
770
+
700
771
  case 'file_uploaded': {
701
772
  const pending = this.pendingUploads.get(msg.uploadId);
702
773
  if (pending) {
@@ -790,17 +861,22 @@ export class WhereverClient {
790
861
  }
791
862
  break;
792
863
 
793
- case 'queue_update':
864
+ case 'queue_update': {
794
865
  // The server relayed pi's current steer queue. Replace our pending-steer
795
866
  // set outright (it is the full queue): a message whose content is still
796
867
  // in this set is a queued steer that has NOT yet been injected, so the
797
868
  // UI can offer to cancel it. When a queued steer is delivered or
798
869
  // cancelled, a fresh queue_update arrives with it removed.
870
+ const steering: string[] = Array.isArray(msg.steering)
871
+ ? [...msg.steering]
872
+ : [];
799
873
  this.stateStore.update((s: WhereverState) => ({
800
874
  ...s,
801
- pendingSteering: Array.isArray(msg.steering) ? [...msg.steering] : [],
875
+ pendingSteering: steering,
876
+ messages: this.withRestoredQueuedMessages(s.messages, steering),
802
877
  }));
803
878
  break;
879
+ }
804
880
 
805
881
  case 'message_end':
806
882
  this.stateStore.update((s: WhereverState) => {
@@ -843,6 +919,26 @@ export class WhereverClient {
843
919
  // Re-read: confirmDeliveredByContent already updated the store.
844
920
  return get(this.stateStore);
845
921
  }
922
+ // A steer we restored from the queue snapshot has now been injected:
923
+ // this echo IS that bubble, so reconcile onto it (drop the marker)
924
+ // rather than appending a duplicate. Oldest first, since pi delivers
925
+ // the queue in order.
926
+ const restoredQueued = newMessages.find(
927
+ (m) =>
928
+ m.role === 'user' &&
929
+ m.restoredFromQueue &&
930
+ m.content === msg.content,
931
+ );
932
+ if (restoredQueued) {
933
+ return {
934
+ ...s,
935
+ messages: newMessages.map((m) =>
936
+ m.id === restoredQueued.id
937
+ ? {...m, restoredFromQueue: undefined}
938
+ : m,
939
+ ),
940
+ };
941
+ }
846
942
  }
847
943
  // Skill invocations arrive TWICE from the server: first the RAW
848
944
  // `/skill:<name> <args>` (as the immediate message_ack, which already
@@ -1161,7 +1257,11 @@ export class WhereverClient {
1161
1257
  // late session_created for the abandoned load must not clobber what the
1162
1258
  // user is now looking at. A session_created is accepted only when it is
1163
1259
  // the reply we are actually waiting on:
1164
- // - a session_load we issued -> matches pendingLoadFile, OR
1260
+ // - a session_load we issued -> matches pendingLoadFile, by FILE or by
1261
+ // ID (a load may be requested by session ID, e.g. the URL-hash deep
1262
+ // link `/#<sessionId>`; the server resolves it and always replies
1263
+ // with the resolved FILE, so a file-only comparison would reject the
1264
+ // load's own reply and hang the "Loading session..." spinner), OR
1165
1265
  // - a session_new we issued -> creatingSession is true (its target
1166
1266
  // file is unknown until this reply, so pendingLoadFile is null).
1167
1267
  // Anything else (pendingLoadFile set but a different file; or no pending
@@ -1173,7 +1273,8 @@ export class WhereverClient {
1173
1273
  const st = get(this.stateStore);
1174
1274
  const matchesPendingLoad =
1175
1275
  this.pendingLoadFile !== null &&
1176
- msg.sessionFile === this.pendingLoadFile;
1276
+ (msg.sessionFile === this.pendingLoadFile ||
1277
+ msg.sessionId === this.pendingLoadFile);
1177
1278
  const isRequestedCreate =
1178
1279
  this.pendingLoadFile === null && st.creatingSession;
1179
1280
  if (!matchesPendingLoad && !isRequestedCreate) {
@@ -1203,6 +1304,15 @@ export class WhereverClient {
1203
1304
  folderConflict: msg.folderConflict
1204
1305
  ? {cwd: msg.cwd, active: true, continued: false}
1205
1306
  : null,
1307
+ // The session's working folder is gone from this machine: the server
1308
+ // built no agent and refuses every send, so the composer is replaced
1309
+ // by a notice naming the path. Hard (no "Continue anyway"); the
1310
+ // authoritative `folder_missing` frame follows with the same cwd.
1311
+ folderMissing: msg.folderMissing ? {cwd: msg.cwd} : null,
1312
+ // The restore panel's state belongs to the folder we are leaving; the
1313
+ // authoritative `folder_missing` frame below re-creates it for this
1314
+ // session (carrying any job already running for its path).
1315
+ restore: null,
1206
1316
  // pending -> the history is painted now but the live agent is still
1207
1317
  // building; keep the composer disabled (agentPending) until
1208
1318
  // session_ready. A non-pending create (new session, warm reload) is
@@ -1212,9 +1322,19 @@ export class WhereverClient {
1212
1322
  // live updates arrive via 'context_usage').
1213
1323
  contextUsage: msg.contextUsage ?? null,
1214
1324
  // Reset skill-command autocomplete for the newly attached session; the
1215
- // authoritative list is (re-)requested on session_ready.
1325
+ // authoritative list is (re-)requested just below (already-live
1326
+ // session) or on session_ready (cold, still-building agent).
1216
1327
  skills: [],
1217
1328
  }));
1329
+ // A session that is ALREADY live -- a brand-new session (session_new) or
1330
+ // a warm attach -- has its agent (and resource loader) right now, but a
1331
+ // brand-new session never emits session_ready, so waiting for that alone
1332
+ // left `/skill:` autocomplete empty on a fresh session. Request the list
1333
+ // here whenever the agent is not pending; re-requesting is safe (the
1334
+ // server always replies with the full list).
1335
+ if (msg.pending !== true && msg.sessionId) {
1336
+ this.send({type: 'skills_request', sessionId: msg.sessionId});
1337
+ }
1218
1338
  break;
1219
1339
  }
1220
1340
 
@@ -1300,6 +1420,8 @@ export class WhereverClient {
1300
1420
  activeModel: null,
1301
1421
  loadingSession: false,
1302
1422
  agentPending: false,
1423
+ folderMissing: null,
1424
+ restore: null,
1303
1425
  notice: null,
1304
1426
  sudoPrompt: null,
1305
1427
  };
@@ -1323,6 +1445,126 @@ export class WhereverClient {
1323
1445
  }));
1324
1446
  break;
1325
1447
 
1448
+ case 'folder_missing':
1449
+ // The server states, authoritatively, that this session's working folder
1450
+ // is not usable -- it does not exist on this machine, or a restore is
1451
+ // still materialising it -- and names the absolute path. No session_ready
1452
+ // is coming (no agent was built), so this is also the end of the load:
1453
+ // read-only, with an explanation. Ignore a frame for a session we already
1454
+ // switched away from.
1455
+ //
1456
+ // `job` is any restore the server is ALREADY running for that path, so a
1457
+ // reconnect or a second device paints the running clone from this one
1458
+ // frame. With no job the panel simply offers to start one; either way the
1459
+ // restore state exists from here on, so a job another device starts is
1460
+ // painted by the progress frames that follow.
1461
+ this.stateStore.update((s: WhereverState) => {
1462
+ if (s.sessionId && msg.sessionId && s.sessionId !== msg.sessionId) return s;
1463
+ return {
1464
+ ...s,
1465
+ readOnly: true,
1466
+ folderMissing: {cwd: msg.cwd},
1467
+ restore: {
1468
+ targetPath: msg.cwd,
1469
+ job: (msg.job as RestoreJobInfo | undefined) ?? null,
1470
+ joined: false,
1471
+ rejection: null,
1472
+ },
1473
+ };
1474
+ });
1475
+ break;
1476
+
1477
+ case 'restore_started': {
1478
+ // The answer to OUR restore_start. `outcome: 'joined'` means a job was
1479
+ // already running for this path and we coalesced onto it, so `job.url` is
1480
+ // the url really in flight -- which the panel must show when it differs
1481
+ // from the one this client asked for, rather than pretending the edited
1482
+ // url was accepted.
1483
+ //
1484
+ // It is ALSO the answer to a `session_new` that chose to CLONE an
1485
+ // existing remote. That create has no restore state yet (no session, so
1486
+ // no folder-missing frame ever created one), so the job is ADOPTED here
1487
+ // as the create's own: the blocking "Creating session..." overlay gives
1488
+ // way to the same progress the restore panel renders, and the create
1489
+ // watchdog -- which fires long before a large repository finishes -- is
1490
+ // disarmed, because a watched job is no longer something to time out.
1491
+ const before = get(this.stateStore);
1492
+ if (before.creatingSession && !before.restore) {
1493
+ this.clearCreateWatchdog();
1494
+ this.stateStore.update((s: WhereverState) => ({
1495
+ ...s,
1496
+ creatingSession: false,
1497
+ restore: {
1498
+ targetPath: msg.targetPath,
1499
+ job: msg.job as RestoreJobInfo,
1500
+ joined: msg.outcome === 'joined',
1501
+ rejection: null,
1502
+ forSessionCreate: true,
1503
+ },
1504
+ }));
1505
+ break;
1506
+ }
1507
+ this.stateStore.update((s: WhereverState) =>
1508
+ this.withRestore(s, msg.targetPath, (r) => ({
1509
+ ...r,
1510
+ job: msg.job as RestoreJobInfo,
1511
+ joined: msg.outcome === 'joined',
1512
+ rejection: null,
1513
+ })),
1514
+ );
1515
+ break;
1516
+ }
1517
+
1518
+ case 'restore_rejected':
1519
+ // Refused before anything was spawned: no job, no completion coming. Keep
1520
+ // whatever job state we had (a rejection answers OUR request, it does not
1521
+ // touch a job someone else is running) and surface the reason.
1522
+ this.stateStore.update((s: WhereverState) =>
1523
+ this.withRestore(s, msg.targetPath, (r) => ({
1524
+ ...r,
1525
+ rejection: {reason: msg.reason, message: msg.message},
1526
+ })),
1527
+ );
1528
+ break;
1529
+
1530
+ case 'restore_progress':
1531
+ case 'restore_complete': {
1532
+ // Broadcast frames: the server sends them to every client whose folder
1533
+ // matches the job path, so they arrive whether or not THIS client started
1534
+ // the restore (a second device, or a reconnect mid-clone). Each carries
1535
+ // the whole job snapshot, so one frame is enough to repaint.
1536
+ //
1537
+ // The new-session clone ends differently from the panel's: there is
1538
+ // nothing to reload, so a job that SUCCEEDED hands the screen straight
1539
+ // back to the create the server is already continuing with (overlay +
1540
+ // watchdog re-armed for that last, ordinary step). A failed or cancelled
1541
+ // one ends the create; the server's session_error, carrying the mapped
1542
+ // cause, arrives beside this frame.
1543
+ const current = get(this.stateStore).restore;
1544
+ if (
1545
+ msg.type === 'restore_complete' &&
1546
+ current?.forSessionCreate &&
1547
+ current.targetPath === msg.targetPath
1548
+ ) {
1549
+ const cloned = (msg.job as RestoreJobInfo).state === 'done';
1550
+ this.stateStore.update((s: WhereverState) => ({
1551
+ ...s,
1552
+ restore: null,
1553
+ creatingSession: cloned,
1554
+ }));
1555
+ if (cloned) this.armCreateWatchdog();
1556
+ break;
1557
+ }
1558
+ this.stateStore.update((s: WhereverState) =>
1559
+ this.withRestore(s, msg.targetPath, (r) => ({
1560
+ ...r,
1561
+ job: msg.job as RestoreJobInfo,
1562
+ rejection: null,
1563
+ })),
1564
+ );
1565
+ break;
1566
+ }
1567
+
1326
1568
  case 'folder_conflict':
1327
1569
  // Live update of whether another active session still exists in this
1328
1570
  // client's folder. The banner appears when a second session shows up in
@@ -1331,15 +1573,25 @@ export class WhereverClient {
1331
1573
  this.stateStore.update((s: WhereverState) => {
1332
1574
  if (!s.sessionId) return s;
1333
1575
  if (s.activeCwd && msg.cwd !== s.activeCwd) return s;
1576
+ // The server re-evaluates this client's read-only state on every
1577
+ // conflict update, so mirror it when reported. This is what releases
1578
+ // the composer once the conflict resolves (the banner alone cannot: it
1579
+ // disappears, taking its "Continue anyway" button with it) and what
1580
+ // keeps a hard sessions.readOnly folder locked. Older servers omit the
1581
+ // field, leaving read-only untouched as before.
1582
+ const readOnly = msg.readOnly ?? s.readOnly;
1334
1583
  if (!msg.active) {
1335
1584
  // No other session remains: fully resolved, drop the banner.
1336
- return s.folderConflict ? {...s, folderConflict: null} : s;
1585
+ return s.folderConflict || readOnly !== s.readOnly
1586
+ ? {...s, folderConflict: null, readOnly}
1587
+ : s;
1337
1588
  }
1338
1589
  if (s.folderConflict) {
1339
1590
  // Already showing: just refresh, preserving the user's `continued`
1340
1591
  // choice (so we don't re-disable a composer they already enabled).
1341
1592
  return {
1342
1593
  ...s,
1594
+ readOnly,
1343
1595
  folderConflict: {...s.folderConflict, cwd: msg.cwd, active: true},
1344
1596
  };
1345
1597
  }
@@ -1349,6 +1601,7 @@ export class WhereverClient {
1349
1601
  // than yanking the composer into read-only underneath the user.
1350
1602
  return {
1351
1603
  ...s,
1604
+ readOnly,
1352
1605
  folderConflict: {cwd: msg.cwd, active: true, continued: true},
1353
1606
  };
1354
1607
  });
@@ -1713,10 +1966,27 @@ export class WhereverClient {
1713
1966
  return false;
1714
1967
  }
1715
1968
 
1969
+ // Build the outbound `message` frame. The optional conversationMode flag is the
1970
+ // per-turn spoken-conversation SIGNAL: it is a FIELD on this existing payload
1971
+ // (no new message type), and it is OMITTED when off so a normal send is
1972
+ // byte-identical to before and an older server simply ignores it.
1973
+ private messageFrame(text: string, sessionId: string, options?: SendMessageOptions) {
1974
+ return {
1975
+ type: 'message',
1976
+ message: text,
1977
+ sessionId,
1978
+ ...(options?.conversationMode ? {conversationMode: true} : {}),
1979
+ };
1980
+ }
1981
+
1716
1982
  // Returns true only if the message actually went out over an OPEN socket.
1717
1983
  // Callers MUST use the return value to decide whether to clear the input:
1718
1984
  // clearing on a false return is what loses the user's text on a dropped send.
1719
- public sendMessage(text: string): boolean {
1985
+ //
1986
+ // `options.conversationMode` tells the agent, for this turn only, that a spoken
1987
+ // conversation is active (so it also emits a short `say` reply). The caller owns
1988
+ // that decision: the web app stamps it from its conversation-mode knobs.
1989
+ public sendMessage(text: string, options?: SendMessageOptions): boolean {
1720
1990
  const s = get(this.stateStore);
1721
1991
  if (!s.sessionId) return false;
1722
1992
 
@@ -1756,7 +2026,7 @@ export class WhereverClient {
1756
2026
  // the frame is confirmed handed to an OPEN socket. This way a send that
1757
2027
  // fails (a narrow race between the readyState check and send) leaves no
1758
2028
  // phantom local message and keeps the input intact for the caller to retry.
1759
- const ok = this.send({type: 'message', message: text, sessionId: s.sessionId});
2029
+ const ok = this.send(this.messageFrame(text, s.sessionId, options));
1760
2030
  if (!ok) {
1761
2031
  this.stateStore.update((st: WhereverState) => ({
1762
2032
  ...st,
@@ -1838,6 +2108,52 @@ export class WhereverClient {
1838
2108
  return true;
1839
2109
  }
1840
2110
 
2111
+ // Re-materialize queued steers the message list does not have. A queued
2112
+ // message lives ONLY in the agent's memory until pi injects it at the next
2113
+ // step: it is not in the session file, so message_history cannot contain it.
2114
+ // On attach (a reload, or a second device) the server sends the queue as a
2115
+ // snapshot; without this the text would be invisible until it was delivered,
2116
+ // even though it was still going to be sent. Any queued entry with no matching
2117
+ // user message is appended so the UI can render it with the "Queued" badge and
2118
+ // the session-level cancel.
2119
+ //
2120
+ // Matching is by CONTENT, because the queue is a list of strings (pi exposes
2121
+ // no per-entry id). Occurrences are COUNTED, so a text queued twice restores
2122
+ // two bubbles, and a locally-sent (optimistic) steer already on screen is not
2123
+ // duplicated by the snapshot that follows it.
2124
+ private withRestoredQueuedMessages(
2125
+ messages: ChatMessage[],
2126
+ steering: string[],
2127
+ ): ChatMessage[] {
2128
+ if (steering.length === 0) return messages;
2129
+ const have = new Map<string, number>();
2130
+ for (const m of messages) {
2131
+ if (m.role !== 'user') continue;
2132
+ have.set(m.content, (have.get(m.content) ?? 0) + 1);
2133
+ }
2134
+ const restored: ChatMessage[] = [];
2135
+ for (const text of steering) {
2136
+ const remaining = have.get(text) ?? 0;
2137
+ if (remaining > 0) {
2138
+ have.set(text, remaining - 1);
2139
+ continue;
2140
+ }
2141
+ restored.push({
2142
+ id: this.generateId(),
2143
+ role: 'user',
2144
+ content: text,
2145
+ timestamp: Date.now(),
2146
+ isStreaming: false,
2147
+ restoredFromQueue: true,
2148
+ // NOT delivery-tracked: the server already holds this message, so it is
2149
+ // delivered as far as we are concerned. Tagging it pending would arm a
2150
+ // confirmation watchdog and wrongly offer "Retry" for a message that is
2151
+ // queued and will be sent.
2152
+ });
2153
+ }
2154
+ return restored.length > 0 ? [...messages, ...restored] : messages;
2155
+ }
2156
+
1841
2157
  // ==========================================================================
1842
2158
  // Outbound-message delivery confirmation + recovery.
1843
2159
  //
@@ -2001,7 +2317,11 @@ export class WhereverClient {
2001
2317
  // Retry a failed (or sending) outbound message: re-send its frame and re-arm
2002
2318
  // confirmation. Returns false if it could not be handed to an OPEN socket (the
2003
2319
  // message stays failed/recoverable).
2004
- public resendMessage(messageId: string): boolean {
2320
+ //
2321
+ // A resend starts a FRESH turn, so the caller re-stamps the per-turn
2322
+ // conversation-mode signal from the knobs as they are NOW (the mode may have
2323
+ // been flipped since the original send).
2324
+ public resendMessage(messageId: string, options?: SendMessageOptions): boolean {
2005
2325
  const s = get(this.stateStore);
2006
2326
  const m = s.messages.find((x) => x.id === messageId && x.role === 'user');
2007
2327
  if (!m || !s.sessionId) return false;
@@ -2009,7 +2329,7 @@ export class WhereverClient {
2009
2329
  if (!this.ws && !this.reconnectTimer) this.scheduleReconnect();
2010
2330
  return false;
2011
2331
  }
2012
- const ok = this.send({type: 'message', message: m.content, sessionId: s.sessionId});
2332
+ const ok = this.send(this.messageFrame(m.content, s.sessionId, options));
2013
2333
  if (!ok) return false;
2014
2334
  this.stateStore.update((st: WhereverState) => ({
2015
2335
  ...st,
@@ -2055,10 +2375,32 @@ export class WhereverClient {
2055
2375
  this.stateStore.update((st: WhereverState) => ({...st, pendingSteering: []}));
2056
2376
  }
2057
2377
 
2378
+ /**
2379
+ * Apply `mutate` to the restore state for `targetPath`, or ignore the frame.
2380
+ *
2381
+ * Restore frames are addressed by PATH (the server's job key) rather than by
2382
+ * session id, because the server derives who gets them from a path match. This
2383
+ * is where a frame for a folder this client is no longer looking at is dropped
2384
+ * -- the one still in flight when the user switched sessions.
2385
+ */
2386
+ private withRestore(
2387
+ s: WhereverState,
2388
+ targetPath: string,
2389
+ mutate: (restore: RestoreInfo) => RestoreInfo,
2390
+ ): WhereverState {
2391
+ const current = s.restore;
2392
+ if (!current || current.targetPath !== targetPath) return s;
2393
+ return {...s, restore: mutate(current)};
2394
+ }
2395
+
2058
2396
  public joinSession(sessionFile: string, cwd?: string, model?: string) {
2059
2397
  this.stateStore.update((s: WhereverState) => ({
2060
2398
  ...s,
2061
2399
  folderConflict: null,
2400
+ // Both folder verdicts belong to the session being left; the load we are
2401
+ // starting re-states its own (the server re-checks on every load).
2402
+ folderMissing: null,
2403
+ restore: null,
2062
2404
  sessionError: null,
2063
2405
  loadingSession: true,
2064
2406
  agentPending: false,
@@ -2098,6 +2440,8 @@ export class WhereverClient {
2098
2440
  activeModel: null,
2099
2441
  readOnly: false,
2100
2442
  folderConflict: null,
2443
+ folderMissing: null,
2444
+ restore: null,
2101
2445
  sessionError: null,
2102
2446
  notice: null,
2103
2447
  sudoPrompt: null,
@@ -2141,6 +2485,10 @@ export class WhereverClient {
2141
2485
  this.stateStore.update((s: WhereverState) => ({
2142
2486
  ...s,
2143
2487
  folderConflict: null,
2488
+ // Creating a session creates its folder, so no missing-folder lock can
2489
+ // survive into it.
2490
+ folderMissing: null,
2491
+ restore: null,
2144
2492
  sessionError: null,
2145
2493
  creatingSession: true,
2146
2494
  loadingSession: false,
@@ -2187,6 +2535,8 @@ export class WhereverClient {
2187
2535
  activeCwd: null,
2188
2536
  activeModel: null,
2189
2537
  readOnly: false,
2538
+ folderMissing: null,
2539
+ restore: null,
2190
2540
  notice: null,
2191
2541
  sudoPrompt: null,
2192
2542
  creatingSession: false,
@@ -2203,6 +2553,88 @@ export class WhereverClient {
2203
2553
  this.resumeModel = undefined;
2204
2554
  }
2205
2555
 
2556
+ // --- RESTORE: materialise the active session's missing working folder -----
2557
+ //
2558
+ // "Restore" here means making the missing FOLDER exist again (clone it back,
2559
+ // or create it), never the unrelated re-materialising of queued steers/drafts
2560
+ // after a reload. See CONTEXT.md; the whole family is namespaced `restore*`.
2561
+
2562
+ /**
2563
+ * Ask the server to restore the folder of the folder-missing session this
2564
+ * client is looking at: CLONE `url` into it, or CREATE it.
2565
+ *
2566
+ * The job is server-owned and keyed by that path, so this may well JOIN a job
2567
+ * another device (or this client's previous, dropped socket) already started;
2568
+ * the server's `restore_started` says which, and carries the url really in
2569
+ * flight. Returns false when there is no missing folder to restore, or when a
2570
+ * clone was asked for with no url.
2571
+ */
2572
+ public startRestore(
2573
+ action: 'clone' | 'create',
2574
+ url?: string,
2575
+ gitInit?: boolean,
2576
+ ): boolean {
2577
+ const s = get(this.stateStore);
2578
+ const targetPath = s.restore?.targetPath ?? s.folderMissing?.cwd;
2579
+ if (!targetPath) return false;
2580
+ const trimmedUrl = url?.trim();
2581
+ if (action === 'clone' && !trimmedUrl) return false;
2582
+ // Record what WE asked for before the answer lands, so the panel can compare
2583
+ // it with the url the (possibly joined) job is really cloning.
2584
+ this.stateStore.update((st: WhereverState) => {
2585
+ const previous = st.restore?.targetPath === targetPath ? st.restore.job : null;
2586
+ return {
2587
+ ...st,
2588
+ restore: {
2589
+ targetPath,
2590
+ // A RUNNING job is the one this request will join, so it stays on
2591
+ // screen. A terminal one belonged to the attempt being retried: drop
2592
+ // it, so the panel shows this request in flight rather than the
2593
+ // previous failure until the server answers.
2594
+ job: previous && previous.state === 'running' ? previous : null,
2595
+ joined: false,
2596
+ requestedUrl: trimmedUrl,
2597
+ rejection: null,
2598
+ },
2599
+ };
2600
+ });
2601
+ return this.send({
2602
+ type: 'restore_start',
2603
+ targetPath,
2604
+ action,
2605
+ ...(trimmedUrl ? {url: trimmedUrl} : {}),
2606
+ ...(gitInit !== undefined ? {gitInit} : {}),
2607
+ });
2608
+ }
2609
+
2610
+ /**
2611
+ * Cancel the restore running for this session's folder. The server settles the
2612
+ * job authoritatively and broadcasts the `cancelled` completion to every client
2613
+ * watching that folder (this one included), so no state is guessed here.
2614
+ */
2615
+ public cancelRestore(): boolean {
2616
+ const s = get(this.stateStore);
2617
+ const targetPath = s.restore?.targetPath;
2618
+ if (!targetPath) return false;
2619
+ return this.send({type: 'restore_cancel', targetPath});
2620
+ }
2621
+
2622
+ /**
2623
+ * Re-load the active session file.
2624
+ *
2625
+ * This is how a completed restore goes LIVE: whether a session has a live agent
2626
+ * is a load-time decision, and the load that found the folder missing
2627
+ * deliberately built none. Re-loading is therefore the honest way to get one,
2628
+ * not a refresh hint. Returns false when there is no active session file.
2629
+ */
2630
+ public reloadSession(): boolean {
2631
+ const s = get(this.stateStore);
2632
+ const sessionFile = s.activeSessionFile;
2633
+ if (!sessionFile) return false;
2634
+ this.joinSession(sessionFile, s.activeCwd ?? undefined);
2635
+ return true;
2636
+ }
2637
+
2206
2638
  // "Continue anyway" on the folder-conflict warning banner: ask the server to
2207
2639
  // lift read-only for this client's current session (both sessions in the
2208
2640
  // folder then run concurrently; the other is NOT aborted). Optimistically
@@ -2211,6 +2643,10 @@ export class WhereverClient {
2211
2643
  public continueFolderConflict() {
2212
2644
  const s = get(this.stateStore);
2213
2645
  if (!s.folderConflict || !s.sessionId) return;
2646
+ // "Continue anyway" answers a folder CONFLICT only. A missing folder is a
2647
+ // hard lock (there is nothing to drive, and no agent was built), and the
2648
+ // server refuses to lift it, so do not flash an enabled composer here.
2649
+ if (s.folderMissing) return;
2214
2650
 
2215
2651
  this.send({
2216
2652
  type: 'folder_conflict_continue',