@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/dist/client.js CHANGED
@@ -1,5 +1,10 @@
1
1
  import { writable, get } from "sveltore";
2
- import { skillInvocationIdentity } from "./types.js";
2
+ import { skillInvocationIdentity, } from "./types.js";
3
+ // Per-instance fallback identity: stable for the lifetime of this client object,
4
+ // which is exactly the lifetime across which reconnects happen.
5
+ function generateClientKey() {
6
+ return `ck-${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`;
7
+ }
3
8
  const defaultState = {
4
9
  connected: false,
5
10
  connecting: false,
@@ -13,7 +18,10 @@ const defaultState = {
13
18
  isStreaming: false,
14
19
  messages: [],
15
20
  clientId: null,
21
+ serverVersion: null,
16
22
  folderConflict: null,
23
+ folderMissing: null,
24
+ restore: null,
17
25
  isInterrupted: false,
18
26
  notice: null,
19
27
  sudoPrompt: null,
@@ -34,6 +42,10 @@ const defaultState = {
34
42
  export class WhereverClient {
35
43
  ws = null;
36
44
  config;
45
+ // Identity sent on every connect so the server can retire this viewer's own
46
+ // stale/phantom connection instead of counting it as a second viewer. Replaced
47
+ // (once) if the server reports it as superseded by another live connection.
48
+ clientKey;
37
49
  stateStore;
38
50
  reconnectTimer = null;
39
51
  agentEndTimeout = null;
@@ -118,6 +130,7 @@ export class WhereverClient {
118
130
  secure: true,
119
131
  ...config
120
132
  };
133
+ this.clientKey = this.config.clientKey || generateClientKey();
121
134
  this.stateStore = writable({
122
135
  ...defaultState,
123
136
  hideThinking: !!this.config.hideThinking,
@@ -148,8 +161,14 @@ export class WhereverClient {
148
161
  const host = this.config.host.startsWith('http')
149
162
  ? this.config.host.replace(/^https?:\/\//, '')
150
163
  : this.config.host;
151
- const tokenQuery = this.config.token ? `?token=${encodeURIComponent(this.config.token)}` : "";
152
- const wsUrl = `${protocol}://${host}:${this.config.port}/ws${tokenQuery}`;
164
+ // clientKey rides on the URL (not a post-connect frame) so the server can
165
+ // evict this viewer's previous connection BEFORE any session traffic is
166
+ // handled, closing the phantom-viewer window entirely.
167
+ const params = [];
168
+ if (this.config.token)
169
+ params.push(`token=${encodeURIComponent(this.config.token)}`);
170
+ params.push(`clientKey=${encodeURIComponent(this.clientKey)}`);
171
+ const wsUrl = `${protocol}://${host}:${this.config.port}/ws?${params.join('&')}`;
153
172
  const WebSocketImpl = this.config.WebSocketCtor || (typeof globalThis !== 'undefined' ? globalThis.WebSocket : null);
154
173
  if (!WebSocketImpl) {
155
174
  this.stateStore.update(s => ({
@@ -657,9 +676,25 @@ export class WhereverClient {
657
676
  connected: true,
658
677
  connecting: false,
659
678
  clientId: msg.clientId,
679
+ serverVersion: msg.serverVersion ?? null,
660
680
  error: null,
661
681
  }));
662
682
  break;
683
+ case 'connection_superseded':
684
+ // A newer connection arrived carrying OUR clientKey, so the server is
685
+ // retiring this socket as a superseded duplicate. Receiving this proves we
686
+ // are alive, i.e. the key is being shared by accident (a duplicated tab
687
+ // clones sessionStorage). Take a fresh identity BEFORE the reconnect the
688
+ // imminent close will schedule, so the two connections stop evicting each
689
+ // other; the owner of the key keeps it and we come back as our own viewer.
690
+ this.clientKey = generateClientKey();
691
+ try {
692
+ this.config.onClientKeyChange?.(this.clientKey);
693
+ }
694
+ catch (err) {
695
+ console.error('onClientKeyChange failed:', err);
696
+ }
697
+ break;
663
698
  case 'file_uploaded': {
664
699
  const pending = this.pendingUploads.get(msg.uploadId);
665
700
  if (pending) {
@@ -741,17 +776,22 @@ export class WhereverClient {
741
776
  this.confirmDeliveredByContent(msg.content);
742
777
  }
743
778
  break;
744
- case 'queue_update':
779
+ case 'queue_update': {
745
780
  // The server relayed pi's current steer queue. Replace our pending-steer
746
781
  // set outright (it is the full queue): a message whose content is still
747
782
  // in this set is a queued steer that has NOT yet been injected, so the
748
783
  // UI can offer to cancel it. When a queued steer is delivered or
749
784
  // cancelled, a fresh queue_update arrives with it removed.
785
+ const steering = Array.isArray(msg.steering)
786
+ ? [...msg.steering]
787
+ : [];
750
788
  this.stateStore.update((s) => ({
751
789
  ...s,
752
- pendingSteering: Array.isArray(msg.steering) ? [...msg.steering] : [],
790
+ pendingSteering: steering,
791
+ messages: this.withRestoredQueuedMessages(s.messages, steering),
753
792
  }));
754
793
  break;
794
+ }
755
795
  case 'message_end':
756
796
  this.stateStore.update((s) => {
757
797
  let newMessages = s.messages;
@@ -786,6 +826,21 @@ export class WhereverClient {
786
826
  // Re-read: confirmDeliveredByContent already updated the store.
787
827
  return get(this.stateStore);
788
828
  }
829
+ // A steer we restored from the queue snapshot has now been injected:
830
+ // this echo IS that bubble, so reconcile onto it (drop the marker)
831
+ // rather than appending a duplicate. Oldest first, since pi delivers
832
+ // the queue in order.
833
+ const restoredQueued = newMessages.find((m) => m.role === 'user' &&
834
+ m.restoredFromQueue &&
835
+ m.content === msg.content);
836
+ if (restoredQueued) {
837
+ return {
838
+ ...s,
839
+ messages: newMessages.map((m) => m.id === restoredQueued.id
840
+ ? { ...m, restoredFromQueue: undefined }
841
+ : m),
842
+ };
843
+ }
789
844
  }
790
845
  // Skill invocations arrive TWICE from the server: first the RAW
791
846
  // `/skill:<name> <args>` (as the immediate message_ack, which already
@@ -1060,7 +1115,11 @@ export class WhereverClient {
1060
1115
  // late session_created for the abandoned load must not clobber what the
1061
1116
  // user is now looking at. A session_created is accepted only when it is
1062
1117
  // the reply we are actually waiting on:
1063
- // - a session_load we issued -> matches pendingLoadFile, OR
1118
+ // - a session_load we issued -> matches pendingLoadFile, by FILE or by
1119
+ // ID (a load may be requested by session ID, e.g. the URL-hash deep
1120
+ // link `/#<sessionId>`; the server resolves it and always replies
1121
+ // with the resolved FILE, so a file-only comparison would reject the
1122
+ // load's own reply and hang the "Loading session..." spinner), OR
1064
1123
  // - a session_new we issued -> creatingSession is true (its target
1065
1124
  // file is unknown until this reply, so pendingLoadFile is null).
1066
1125
  // Anything else (pendingLoadFile set but a different file; or no pending
@@ -1071,7 +1130,8 @@ export class WhereverClient {
1071
1130
  {
1072
1131
  const st = get(this.stateStore);
1073
1132
  const matchesPendingLoad = this.pendingLoadFile !== null &&
1074
- msg.sessionFile === this.pendingLoadFile;
1133
+ (msg.sessionFile === this.pendingLoadFile ||
1134
+ msg.sessionId === this.pendingLoadFile);
1075
1135
  const isRequestedCreate = this.pendingLoadFile === null && st.creatingSession;
1076
1136
  if (!matchesPendingLoad && !isRequestedCreate) {
1077
1137
  break;
@@ -1100,6 +1160,15 @@ export class WhereverClient {
1100
1160
  folderConflict: msg.folderConflict
1101
1161
  ? { cwd: msg.cwd, active: true, continued: false }
1102
1162
  : null,
1163
+ // The session's working folder is gone from this machine: the server
1164
+ // built no agent and refuses every send, so the composer is replaced
1165
+ // by a notice naming the path. Hard (no "Continue anyway"); the
1166
+ // authoritative `folder_missing` frame follows with the same cwd.
1167
+ folderMissing: msg.folderMissing ? { cwd: msg.cwd } : null,
1168
+ // The restore panel's state belongs to the folder we are leaving; the
1169
+ // authoritative `folder_missing` frame below re-creates it for this
1170
+ // session (carrying any job already running for its path).
1171
+ restore: null,
1103
1172
  // pending -> the history is painted now but the live agent is still
1104
1173
  // building; keep the composer disabled (agentPending) until
1105
1174
  // session_ready. A non-pending create (new session, warm reload) is
@@ -1109,9 +1178,19 @@ export class WhereverClient {
1109
1178
  // live updates arrive via 'context_usage').
1110
1179
  contextUsage: msg.contextUsage ?? null,
1111
1180
  // Reset skill-command autocomplete for the newly attached session; the
1112
- // authoritative list is (re-)requested on session_ready.
1181
+ // authoritative list is (re-)requested just below (already-live
1182
+ // session) or on session_ready (cold, still-building agent).
1113
1183
  skills: [],
1114
1184
  }));
1185
+ // A session that is ALREADY live -- a brand-new session (session_new) or
1186
+ // a warm attach -- has its agent (and resource loader) right now, but a
1187
+ // brand-new session never emits session_ready, so waiting for that alone
1188
+ // left `/skill:` autocomplete empty on a fresh session. Request the list
1189
+ // here whenever the agent is not pending; re-requesting is safe (the
1190
+ // server always replies with the full list).
1191
+ if (msg.pending !== true && msg.sessionId) {
1192
+ this.send({ type: 'skills_request', sessionId: msg.sessionId });
1193
+ }
1115
1194
  break;
1116
1195
  }
1117
1196
  case 'session_ready':
@@ -1195,6 +1274,8 @@ export class WhereverClient {
1195
1274
  activeModel: null,
1196
1275
  loadingSession: false,
1197
1276
  agentPending: false,
1277
+ folderMissing: null,
1278
+ restore: null,
1198
1279
  notice: null,
1199
1280
  sudoPrompt: null,
1200
1281
  };
@@ -1216,6 +1297,116 @@ export class WhereverClient {
1216
1297
  agentPending: false,
1217
1298
  }));
1218
1299
  break;
1300
+ case 'folder_missing':
1301
+ // The server states, authoritatively, that this session's working folder
1302
+ // is not usable -- it does not exist on this machine, or a restore is
1303
+ // still materialising it -- and names the absolute path. No session_ready
1304
+ // is coming (no agent was built), so this is also the end of the load:
1305
+ // read-only, with an explanation. Ignore a frame for a session we already
1306
+ // switched away from.
1307
+ //
1308
+ // `job` is any restore the server is ALREADY running for that path, so a
1309
+ // reconnect or a second device paints the running clone from this one
1310
+ // frame. With no job the panel simply offers to start one; either way the
1311
+ // restore state exists from here on, so a job another device starts is
1312
+ // painted by the progress frames that follow.
1313
+ this.stateStore.update((s) => {
1314
+ if (s.sessionId && msg.sessionId && s.sessionId !== msg.sessionId)
1315
+ return s;
1316
+ return {
1317
+ ...s,
1318
+ readOnly: true,
1319
+ folderMissing: { cwd: msg.cwd },
1320
+ restore: {
1321
+ targetPath: msg.cwd,
1322
+ job: msg.job ?? null,
1323
+ joined: false,
1324
+ rejection: null,
1325
+ },
1326
+ };
1327
+ });
1328
+ break;
1329
+ case 'restore_started': {
1330
+ // The answer to OUR restore_start. `outcome: 'joined'` means a job was
1331
+ // already running for this path and we coalesced onto it, so `job.url` is
1332
+ // the url really in flight -- which the panel must show when it differs
1333
+ // from the one this client asked for, rather than pretending the edited
1334
+ // url was accepted.
1335
+ //
1336
+ // It is ALSO the answer to a `session_new` that chose to CLONE an
1337
+ // existing remote. That create has no restore state yet (no session, so
1338
+ // no folder-missing frame ever created one), so the job is ADOPTED here
1339
+ // as the create's own: the blocking "Creating session..." overlay gives
1340
+ // way to the same progress the restore panel renders, and the create
1341
+ // watchdog -- which fires long before a large repository finishes -- is
1342
+ // disarmed, because a watched job is no longer something to time out.
1343
+ const before = get(this.stateStore);
1344
+ if (before.creatingSession && !before.restore) {
1345
+ this.clearCreateWatchdog();
1346
+ this.stateStore.update((s) => ({
1347
+ ...s,
1348
+ creatingSession: false,
1349
+ restore: {
1350
+ targetPath: msg.targetPath,
1351
+ job: msg.job,
1352
+ joined: msg.outcome === 'joined',
1353
+ rejection: null,
1354
+ forSessionCreate: true,
1355
+ },
1356
+ }));
1357
+ break;
1358
+ }
1359
+ this.stateStore.update((s) => this.withRestore(s, msg.targetPath, (r) => ({
1360
+ ...r,
1361
+ job: msg.job,
1362
+ joined: msg.outcome === 'joined',
1363
+ rejection: null,
1364
+ })));
1365
+ break;
1366
+ }
1367
+ case 'restore_rejected':
1368
+ // Refused before anything was spawned: no job, no completion coming. Keep
1369
+ // whatever job state we had (a rejection answers OUR request, it does not
1370
+ // touch a job someone else is running) and surface the reason.
1371
+ this.stateStore.update((s) => this.withRestore(s, msg.targetPath, (r) => ({
1372
+ ...r,
1373
+ rejection: { reason: msg.reason, message: msg.message },
1374
+ })));
1375
+ break;
1376
+ case 'restore_progress':
1377
+ case 'restore_complete': {
1378
+ // Broadcast frames: the server sends them to every client whose folder
1379
+ // matches the job path, so they arrive whether or not THIS client started
1380
+ // the restore (a second device, or a reconnect mid-clone). Each carries
1381
+ // the whole job snapshot, so one frame is enough to repaint.
1382
+ //
1383
+ // The new-session clone ends differently from the panel's: there is
1384
+ // nothing to reload, so a job that SUCCEEDED hands the screen straight
1385
+ // back to the create the server is already continuing with (overlay +
1386
+ // watchdog re-armed for that last, ordinary step). A failed or cancelled
1387
+ // one ends the create; the server's session_error, carrying the mapped
1388
+ // cause, arrives beside this frame.
1389
+ const current = get(this.stateStore).restore;
1390
+ if (msg.type === 'restore_complete' &&
1391
+ current?.forSessionCreate &&
1392
+ current.targetPath === msg.targetPath) {
1393
+ const cloned = msg.job.state === 'done';
1394
+ this.stateStore.update((s) => ({
1395
+ ...s,
1396
+ restore: null,
1397
+ creatingSession: cloned,
1398
+ }));
1399
+ if (cloned)
1400
+ this.armCreateWatchdog();
1401
+ break;
1402
+ }
1403
+ this.stateStore.update((s) => this.withRestore(s, msg.targetPath, (r) => ({
1404
+ ...r,
1405
+ job: msg.job,
1406
+ rejection: null,
1407
+ })));
1408
+ break;
1409
+ }
1219
1410
  case 'folder_conflict':
1220
1411
  // Live update of whether another active session still exists in this
1221
1412
  // client's folder. The banner appears when a second session shows up in
@@ -1226,15 +1417,25 @@ export class WhereverClient {
1226
1417
  return s;
1227
1418
  if (s.activeCwd && msg.cwd !== s.activeCwd)
1228
1419
  return s;
1420
+ // The server re-evaluates this client's read-only state on every
1421
+ // conflict update, so mirror it when reported. This is what releases
1422
+ // the composer once the conflict resolves (the banner alone cannot: it
1423
+ // disappears, taking its "Continue anyway" button with it) and what
1424
+ // keeps a hard sessions.readOnly folder locked. Older servers omit the
1425
+ // field, leaving read-only untouched as before.
1426
+ const readOnly = msg.readOnly ?? s.readOnly;
1229
1427
  if (!msg.active) {
1230
1428
  // No other session remains: fully resolved, drop the banner.
1231
- return s.folderConflict ? { ...s, folderConflict: null } : s;
1429
+ return s.folderConflict || readOnly !== s.readOnly
1430
+ ? { ...s, folderConflict: null, readOnly }
1431
+ : s;
1232
1432
  }
1233
1433
  if (s.folderConflict) {
1234
1434
  // Already showing: just refresh, preserving the user's `continued`
1235
1435
  // choice (so we don't re-disable a composer they already enabled).
1236
1436
  return {
1237
1437
  ...s,
1438
+ readOnly,
1238
1439
  folderConflict: { ...s.folderConflict, cwd: msg.cwd, active: true },
1239
1440
  };
1240
1441
  }
@@ -1244,6 +1445,7 @@ export class WhereverClient {
1244
1445
  // than yanking the composer into read-only underneath the user.
1245
1446
  return {
1246
1447
  ...s,
1448
+ readOnly,
1247
1449
  folderConflict: { cwd: msg.cwd, active: true, continued: true },
1248
1450
  };
1249
1451
  });
@@ -1600,10 +1802,26 @@ export class WhereverClient {
1600
1802
  }
1601
1803
  return false;
1602
1804
  }
1805
+ // Build the outbound `message` frame. The optional conversationMode flag is the
1806
+ // per-turn spoken-conversation SIGNAL: it is a FIELD on this existing payload
1807
+ // (no new message type), and it is OMITTED when off so a normal send is
1808
+ // byte-identical to before and an older server simply ignores it.
1809
+ messageFrame(text, sessionId, options) {
1810
+ return {
1811
+ type: 'message',
1812
+ message: text,
1813
+ sessionId,
1814
+ ...(options?.conversationMode ? { conversationMode: true } : {}),
1815
+ };
1816
+ }
1603
1817
  // Returns true only if the message actually went out over an OPEN socket.
1604
1818
  // Callers MUST use the return value to decide whether to clear the input:
1605
1819
  // clearing on a false return is what loses the user's text on a dropped send.
1606
- sendMessage(text) {
1820
+ //
1821
+ // `options.conversationMode` tells the agent, for this turn only, that a spoken
1822
+ // conversation is active (so it also emits a short `say` reply). The caller owns
1823
+ // that decision: the web app stamps it from its conversation-mode knobs.
1824
+ sendMessage(text, options) {
1607
1825
  const s = get(this.stateStore);
1608
1826
  if (!s.sessionId)
1609
1827
  return false;
@@ -1639,7 +1857,7 @@ export class WhereverClient {
1639
1857
  // the frame is confirmed handed to an OPEN socket. This way a send that
1640
1858
  // fails (a narrow race between the readyState check and send) leaves no
1641
1859
  // phantom local message and keeps the input intact for the caller to retry.
1642
- const ok = this.send({ type: 'message', message: text, sessionId: s.sessionId });
1860
+ const ok = this.send(this.messageFrame(text, s.sessionId, options));
1643
1861
  if (!ok) {
1644
1862
  this.stateStore.update((st) => ({
1645
1863
  ...st,
@@ -1717,6 +1935,50 @@ export class WhereverClient {
1717
1935
  this.persistPending(s.sessionId);
1718
1936
  return true;
1719
1937
  }
1938
+ // Re-materialize queued steers the message list does not have. A queued
1939
+ // message lives ONLY in the agent's memory until pi injects it at the next
1940
+ // step: it is not in the session file, so message_history cannot contain it.
1941
+ // On attach (a reload, or a second device) the server sends the queue as a
1942
+ // snapshot; without this the text would be invisible until it was delivered,
1943
+ // even though it was still going to be sent. Any queued entry with no matching
1944
+ // user message is appended so the UI can render it with the "Queued" badge and
1945
+ // the session-level cancel.
1946
+ //
1947
+ // Matching is by CONTENT, because the queue is a list of strings (pi exposes
1948
+ // no per-entry id). Occurrences are COUNTED, so a text queued twice restores
1949
+ // two bubbles, and a locally-sent (optimistic) steer already on screen is not
1950
+ // duplicated by the snapshot that follows it.
1951
+ withRestoredQueuedMessages(messages, steering) {
1952
+ if (steering.length === 0)
1953
+ return messages;
1954
+ const have = new Map();
1955
+ for (const m of messages) {
1956
+ if (m.role !== 'user')
1957
+ continue;
1958
+ have.set(m.content, (have.get(m.content) ?? 0) + 1);
1959
+ }
1960
+ const restored = [];
1961
+ for (const text of steering) {
1962
+ const remaining = have.get(text) ?? 0;
1963
+ if (remaining > 0) {
1964
+ have.set(text, remaining - 1);
1965
+ continue;
1966
+ }
1967
+ restored.push({
1968
+ id: this.generateId(),
1969
+ role: 'user',
1970
+ content: text,
1971
+ timestamp: Date.now(),
1972
+ isStreaming: false,
1973
+ restoredFromQueue: true,
1974
+ // NOT delivery-tracked: the server already holds this message, so it is
1975
+ // delivered as far as we are concerned. Tagging it pending would arm a
1976
+ // confirmation watchdog and wrongly offer "Retry" for a message that is
1977
+ // queued and will be sent.
1978
+ });
1979
+ }
1980
+ return restored.length > 0 ? [...messages, ...restored] : messages;
1981
+ }
1720
1982
  // ==========================================================================
1721
1983
  // Outbound-message delivery confirmation + recovery.
1722
1984
  //
@@ -1868,7 +2130,11 @@ export class WhereverClient {
1868
2130
  // Retry a failed (or sending) outbound message: re-send its frame and re-arm
1869
2131
  // confirmation. Returns false if it could not be handed to an OPEN socket (the
1870
2132
  // message stays failed/recoverable).
1871
- resendMessage(messageId) {
2133
+ //
2134
+ // A resend starts a FRESH turn, so the caller re-stamps the per-turn
2135
+ // conversation-mode signal from the knobs as they are NOW (the mode may have
2136
+ // been flipped since the original send).
2137
+ resendMessage(messageId, options) {
1872
2138
  const s = get(this.stateStore);
1873
2139
  const m = s.messages.find((x) => x.id === messageId && x.role === 'user');
1874
2140
  if (!m || !s.sessionId)
@@ -1878,7 +2144,7 @@ export class WhereverClient {
1878
2144
  this.scheduleReconnect();
1879
2145
  return false;
1880
2146
  }
1881
- const ok = this.send({ type: 'message', message: m.content, sessionId: s.sessionId });
2147
+ const ok = this.send(this.messageFrame(m.content, s.sessionId, options));
1882
2148
  if (!ok)
1883
2149
  return false;
1884
2150
  this.stateStore.update((st) => ({
@@ -1922,10 +2188,28 @@ export class WhereverClient {
1922
2188
  this.send({ type: 'cancel_steer', sessionId: s.sessionId });
1923
2189
  this.stateStore.update((st) => ({ ...st, pendingSteering: [] }));
1924
2190
  }
2191
+ /**
2192
+ * Apply `mutate` to the restore state for `targetPath`, or ignore the frame.
2193
+ *
2194
+ * Restore frames are addressed by PATH (the server's job key) rather than by
2195
+ * session id, because the server derives who gets them from a path match. This
2196
+ * is where a frame for a folder this client is no longer looking at is dropped
2197
+ * -- the one still in flight when the user switched sessions.
2198
+ */
2199
+ withRestore(s, targetPath, mutate) {
2200
+ const current = s.restore;
2201
+ if (!current || current.targetPath !== targetPath)
2202
+ return s;
2203
+ return { ...s, restore: mutate(current) };
2204
+ }
1925
2205
  joinSession(sessionFile, cwd, model) {
1926
2206
  this.stateStore.update((s) => ({
1927
2207
  ...s,
1928
2208
  folderConflict: null,
2209
+ // Both folder verdicts belong to the session being left; the load we are
2210
+ // starting re-states its own (the server re-checks on every load).
2211
+ folderMissing: null,
2212
+ restore: null,
1929
2213
  sessionError: null,
1930
2214
  loadingSession: true,
1931
2215
  agentPending: false,
@@ -1964,6 +2248,8 @@ export class WhereverClient {
1964
2248
  activeModel: null,
1965
2249
  readOnly: false,
1966
2250
  folderConflict: null,
2251
+ folderMissing: null,
2252
+ restore: null,
1967
2253
  sessionError: null,
1968
2254
  notice: null,
1969
2255
  sudoPrompt: null,
@@ -1999,6 +2285,10 @@ export class WhereverClient {
1999
2285
  this.stateStore.update((s) => ({
2000
2286
  ...s,
2001
2287
  folderConflict: null,
2288
+ // Creating a session creates its folder, so no missing-folder lock can
2289
+ // survive into it.
2290
+ folderMissing: null,
2291
+ restore: null,
2002
2292
  sessionError: null,
2003
2293
  creatingSession: true,
2004
2294
  loadingSession: false,
@@ -2044,6 +2334,8 @@ export class WhereverClient {
2044
2334
  activeCwd: null,
2045
2335
  activeModel: null,
2046
2336
  readOnly: false,
2337
+ folderMissing: null,
2338
+ restore: null,
2047
2339
  notice: null,
2048
2340
  sudoPrompt: null,
2049
2341
  creatingSession: false,
@@ -2059,6 +2351,84 @@ export class WhereverClient {
2059
2351
  this.resumeCwd = undefined;
2060
2352
  this.resumeModel = undefined;
2061
2353
  }
2354
+ // --- RESTORE: materialise the active session's missing working folder -----
2355
+ //
2356
+ // "Restore" here means making the missing FOLDER exist again (clone it back,
2357
+ // or create it), never the unrelated re-materialising of queued steers/drafts
2358
+ // after a reload. See CONTEXT.md; the whole family is namespaced `restore*`.
2359
+ /**
2360
+ * Ask the server to restore the folder of the folder-missing session this
2361
+ * client is looking at: CLONE `url` into it, or CREATE it.
2362
+ *
2363
+ * The job is server-owned and keyed by that path, so this may well JOIN a job
2364
+ * another device (or this client's previous, dropped socket) already started;
2365
+ * the server's `restore_started` says which, and carries the url really in
2366
+ * flight. Returns false when there is no missing folder to restore, or when a
2367
+ * clone was asked for with no url.
2368
+ */
2369
+ startRestore(action, url, gitInit) {
2370
+ const s = get(this.stateStore);
2371
+ const targetPath = s.restore?.targetPath ?? s.folderMissing?.cwd;
2372
+ if (!targetPath)
2373
+ return false;
2374
+ const trimmedUrl = url?.trim();
2375
+ if (action === 'clone' && !trimmedUrl)
2376
+ return false;
2377
+ // Record what WE asked for before the answer lands, so the panel can compare
2378
+ // it with the url the (possibly joined) job is really cloning.
2379
+ this.stateStore.update((st) => {
2380
+ const previous = st.restore?.targetPath === targetPath ? st.restore.job : null;
2381
+ return {
2382
+ ...st,
2383
+ restore: {
2384
+ targetPath,
2385
+ // A RUNNING job is the one this request will join, so it stays on
2386
+ // screen. A terminal one belonged to the attempt being retried: drop
2387
+ // it, so the panel shows this request in flight rather than the
2388
+ // previous failure until the server answers.
2389
+ job: previous && previous.state === 'running' ? previous : null,
2390
+ joined: false,
2391
+ requestedUrl: trimmedUrl,
2392
+ rejection: null,
2393
+ },
2394
+ };
2395
+ });
2396
+ return this.send({
2397
+ type: 'restore_start',
2398
+ targetPath,
2399
+ action,
2400
+ ...(trimmedUrl ? { url: trimmedUrl } : {}),
2401
+ ...(gitInit !== undefined ? { gitInit } : {}),
2402
+ });
2403
+ }
2404
+ /**
2405
+ * Cancel the restore running for this session's folder. The server settles the
2406
+ * job authoritatively and broadcasts the `cancelled` completion to every client
2407
+ * watching that folder (this one included), so no state is guessed here.
2408
+ */
2409
+ cancelRestore() {
2410
+ const s = get(this.stateStore);
2411
+ const targetPath = s.restore?.targetPath;
2412
+ if (!targetPath)
2413
+ return false;
2414
+ return this.send({ type: 'restore_cancel', targetPath });
2415
+ }
2416
+ /**
2417
+ * Re-load the active session file.
2418
+ *
2419
+ * This is how a completed restore goes LIVE: whether a session has a live agent
2420
+ * is a load-time decision, and the load that found the folder missing
2421
+ * deliberately built none. Re-loading is therefore the honest way to get one,
2422
+ * not a refresh hint. Returns false when there is no active session file.
2423
+ */
2424
+ reloadSession() {
2425
+ const s = get(this.stateStore);
2426
+ const sessionFile = s.activeSessionFile;
2427
+ if (!sessionFile)
2428
+ return false;
2429
+ this.joinSession(sessionFile, s.activeCwd ?? undefined);
2430
+ return true;
2431
+ }
2062
2432
  // "Continue anyway" on the folder-conflict warning banner: ask the server to
2063
2433
  // lift read-only for this client's current session (both sessions in the
2064
2434
  // folder then run concurrently; the other is NOT aborted). Optimistically
@@ -2068,6 +2438,11 @@ export class WhereverClient {
2068
2438
  const s = get(this.stateStore);
2069
2439
  if (!s.folderConflict || !s.sessionId)
2070
2440
  return;
2441
+ // "Continue anyway" answers a folder CONFLICT only. A missing folder is a
2442
+ // hard lock (there is nothing to drive, and no agent was built), and the
2443
+ // server refuses to lift it, so do not flash an enabled composer here.
2444
+ if (s.folderMissing)
2445
+ return;
2071
2446
  this.send({
2072
2447
  type: 'folder_conflict_continue',
2073
2448
  sessionId: s.sessionId,