@wherever-dev/client 0.5.4 → 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,11 @@
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";
3
9
 
4
10
  /**
5
11
  * Per-send options for a user message.
@@ -22,6 +28,29 @@ export interface WhereverClientConfig {
22
28
  WebSocketCtor?: any;
23
29
  hideThinking?: boolean;
24
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)}`;
25
54
  }
26
55
 
27
56
  const defaultState: WhereverState = {
@@ -37,7 +66,10 @@ const defaultState: WhereverState = {
37
66
  isStreaming: false,
38
67
  messages: [],
39
68
  clientId: null,
69
+ serverVersion: null,
40
70
  folderConflict: null,
71
+ folderMissing: null,
72
+ restore: null,
41
73
  isInterrupted: false,
42
74
  notice: null,
43
75
  sudoPrompt: null,
@@ -59,6 +91,10 @@ const defaultState: WhereverState = {
59
91
  export class WhereverClient {
60
92
  private ws: any = null;
61
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;
62
98
  public stateStore: Writable<WhereverState>;
63
99
  private reconnectTimer: any = null;
64
100
  private agentEndTimeout: any = null;
@@ -144,6 +180,7 @@ export class WhereverClient {
144
180
  secure: true,
145
181
  ...config
146
182
  };
183
+ this.clientKey = this.config.clientKey || generateClientKey();
147
184
  this.stateStore = writable<WhereverState>({
148
185
  ...defaultState,
149
186
  hideThinking: !!this.config.hideThinking,
@@ -178,8 +215,13 @@ export class WhereverClient {
178
215
  const host = this.config.host.startsWith('http')
179
216
  ? this.config.host.replace(/^https?:\/\//, '')
180
217
  : this.config.host;
181
- const tokenQuery = this.config.token ? `?token=${encodeURIComponent(this.config.token)}` : "";
182
- 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('&')}`;
183
225
 
184
226
  const WebSocketImpl = this.config.WebSocketCtor || (typeof globalThis !== 'undefined' ? (globalThis as any).WebSocket : null);
185
227
 
@@ -706,10 +748,26 @@ export class WhereverClient {
706
748
  connected: true,
707
749
  connecting: false,
708
750
  clientId: msg.clientId,
751
+ serverVersion: msg.serverVersion ?? null,
709
752
  error: null,
710
753
  }));
711
754
  break;
712
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
+
713
771
  case 'file_uploaded': {
714
772
  const pending = this.pendingUploads.get(msg.uploadId);
715
773
  if (pending) {
@@ -803,17 +861,22 @@ export class WhereverClient {
803
861
  }
804
862
  break;
805
863
 
806
- case 'queue_update':
864
+ case 'queue_update': {
807
865
  // The server relayed pi's current steer queue. Replace our pending-steer
808
866
  // set outright (it is the full queue): a message whose content is still
809
867
  // in this set is a queued steer that has NOT yet been injected, so the
810
868
  // UI can offer to cancel it. When a queued steer is delivered or
811
869
  // cancelled, a fresh queue_update arrives with it removed.
870
+ const steering: string[] = Array.isArray(msg.steering)
871
+ ? [...msg.steering]
872
+ : [];
812
873
  this.stateStore.update((s: WhereverState) => ({
813
874
  ...s,
814
- pendingSteering: Array.isArray(msg.steering) ? [...msg.steering] : [],
875
+ pendingSteering: steering,
876
+ messages: this.withRestoredQueuedMessages(s.messages, steering),
815
877
  }));
816
878
  break;
879
+ }
817
880
 
818
881
  case 'message_end':
819
882
  this.stateStore.update((s: WhereverState) => {
@@ -856,6 +919,26 @@ export class WhereverClient {
856
919
  // Re-read: confirmDeliveredByContent already updated the store.
857
920
  return get(this.stateStore);
858
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
+ }
859
942
  }
860
943
  // Skill invocations arrive TWICE from the server: first the RAW
861
944
  // `/skill:<name> <args>` (as the immediate message_ack, which already
@@ -1174,7 +1257,11 @@ export class WhereverClient {
1174
1257
  // late session_created for the abandoned load must not clobber what the
1175
1258
  // user is now looking at. A session_created is accepted only when it is
1176
1259
  // the reply we are actually waiting on:
1177
- // - 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
1178
1265
  // - a session_new we issued -> creatingSession is true (its target
1179
1266
  // file is unknown until this reply, so pendingLoadFile is null).
1180
1267
  // Anything else (pendingLoadFile set but a different file; or no pending
@@ -1186,7 +1273,8 @@ export class WhereverClient {
1186
1273
  const st = get(this.stateStore);
1187
1274
  const matchesPendingLoad =
1188
1275
  this.pendingLoadFile !== null &&
1189
- msg.sessionFile === this.pendingLoadFile;
1276
+ (msg.sessionFile === this.pendingLoadFile ||
1277
+ msg.sessionId === this.pendingLoadFile);
1190
1278
  const isRequestedCreate =
1191
1279
  this.pendingLoadFile === null && st.creatingSession;
1192
1280
  if (!matchesPendingLoad && !isRequestedCreate) {
@@ -1216,6 +1304,15 @@ export class WhereverClient {
1216
1304
  folderConflict: msg.folderConflict
1217
1305
  ? {cwd: msg.cwd, active: true, continued: false}
1218
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,
1219
1316
  // pending -> the history is painted now but the live agent is still
1220
1317
  // building; keep the composer disabled (agentPending) until
1221
1318
  // session_ready. A non-pending create (new session, warm reload) is
@@ -1225,9 +1322,19 @@ export class WhereverClient {
1225
1322
  // live updates arrive via 'context_usage').
1226
1323
  contextUsage: msg.contextUsage ?? null,
1227
1324
  // Reset skill-command autocomplete for the newly attached session; the
1228
- // 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).
1229
1327
  skills: [],
1230
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
+ }
1231
1338
  break;
1232
1339
  }
1233
1340
 
@@ -1313,6 +1420,8 @@ export class WhereverClient {
1313
1420
  activeModel: null,
1314
1421
  loadingSession: false,
1315
1422
  agentPending: false,
1423
+ folderMissing: null,
1424
+ restore: null,
1316
1425
  notice: null,
1317
1426
  sudoPrompt: null,
1318
1427
  };
@@ -1336,6 +1445,126 @@ export class WhereverClient {
1336
1445
  }));
1337
1446
  break;
1338
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
+
1339
1568
  case 'folder_conflict':
1340
1569
  // Live update of whether another active session still exists in this
1341
1570
  // client's folder. The banner appears when a second session shows up in
@@ -1344,15 +1573,25 @@ export class WhereverClient {
1344
1573
  this.stateStore.update((s: WhereverState) => {
1345
1574
  if (!s.sessionId) return s;
1346
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;
1347
1583
  if (!msg.active) {
1348
1584
  // No other session remains: fully resolved, drop the banner.
1349
- return s.folderConflict ? {...s, folderConflict: null} : s;
1585
+ return s.folderConflict || readOnly !== s.readOnly
1586
+ ? {...s, folderConflict: null, readOnly}
1587
+ : s;
1350
1588
  }
1351
1589
  if (s.folderConflict) {
1352
1590
  // Already showing: just refresh, preserving the user's `continued`
1353
1591
  // choice (so we don't re-disable a composer they already enabled).
1354
1592
  return {
1355
1593
  ...s,
1594
+ readOnly,
1356
1595
  folderConflict: {...s.folderConflict, cwd: msg.cwd, active: true},
1357
1596
  };
1358
1597
  }
@@ -1362,6 +1601,7 @@ export class WhereverClient {
1362
1601
  // than yanking the composer into read-only underneath the user.
1363
1602
  return {
1364
1603
  ...s,
1604
+ readOnly,
1365
1605
  folderConflict: {cwd: msg.cwd, active: true, continued: true},
1366
1606
  };
1367
1607
  });
@@ -1868,6 +2108,52 @@ export class WhereverClient {
1868
2108
  return true;
1869
2109
  }
1870
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
+
1871
2157
  // ==========================================================================
1872
2158
  // Outbound-message delivery confirmation + recovery.
1873
2159
  //
@@ -2089,10 +2375,32 @@ export class WhereverClient {
2089
2375
  this.stateStore.update((st: WhereverState) => ({...st, pendingSteering: []}));
2090
2376
  }
2091
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
+
2092
2396
  public joinSession(sessionFile: string, cwd?: string, model?: string) {
2093
2397
  this.stateStore.update((s: WhereverState) => ({
2094
2398
  ...s,
2095
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,
2096
2404
  sessionError: null,
2097
2405
  loadingSession: true,
2098
2406
  agentPending: false,
@@ -2132,6 +2440,8 @@ export class WhereverClient {
2132
2440
  activeModel: null,
2133
2441
  readOnly: false,
2134
2442
  folderConflict: null,
2443
+ folderMissing: null,
2444
+ restore: null,
2135
2445
  sessionError: null,
2136
2446
  notice: null,
2137
2447
  sudoPrompt: null,
@@ -2175,6 +2485,10 @@ export class WhereverClient {
2175
2485
  this.stateStore.update((s: WhereverState) => ({
2176
2486
  ...s,
2177
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,
2178
2492
  sessionError: null,
2179
2493
  creatingSession: true,
2180
2494
  loadingSession: false,
@@ -2221,6 +2535,8 @@ export class WhereverClient {
2221
2535
  activeCwd: null,
2222
2536
  activeModel: null,
2223
2537
  readOnly: false,
2538
+ folderMissing: null,
2539
+ restore: null,
2224
2540
  notice: null,
2225
2541
  sudoPrompt: null,
2226
2542
  creatingSession: false,
@@ -2237,6 +2553,88 @@ export class WhereverClient {
2237
2553
  this.resumeModel = undefined;
2238
2554
  }
2239
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
+
2240
2638
  // "Continue anyway" on the folder-conflict warning banner: ask the server to
2241
2639
  // lift read-only for this client's current session (both sessions in the
2242
2640
  // folder then run concurrently; the other is NOT aborted). Optimistically
@@ -2245,6 +2643,10 @@ export class WhereverClient {
2245
2643
  public continueFolderConflict() {
2246
2644
  const s = get(this.stateStore);
2247
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;
2248
2650
 
2249
2651
  this.send({
2250
2652
  type: 'folder_conflict_continue',