@wherever-dev/client 0.5.4 → 0.7.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':
@@ -1139,6 +1218,17 @@ export class WhereverClient {
1139
1218
  this.send({ type: 'skills_request', sessionId: sid });
1140
1219
  }
1141
1220
  break;
1221
+ case 'session_reloading':
1222
+ // A `/reload` was accepted (by us or another viewer): the live agent is
1223
+ // being rebuilt. Block the composer exactly like a cold load; the
1224
+ // session_ready (or session_error) that ends the reload clears it and
1225
+ // re-requests the skill list. Ignore a frame for a session we left.
1226
+ this.stateStore.update((s) => {
1227
+ if (s.sessionId && msg.sessionId && s.sessionId !== msg.sessionId)
1228
+ return s;
1229
+ return { ...s, agentPending: true };
1230
+ });
1231
+ break;
1142
1232
  case 'skills_list':
1143
1233
  // The set of `/skill:<name>` commands for the active session. Replace
1144
1234
  // outright; ignore a list for a session we already switched away from.
@@ -1195,6 +1285,8 @@ export class WhereverClient {
1195
1285
  activeModel: null,
1196
1286
  loadingSession: false,
1197
1287
  agentPending: false,
1288
+ folderMissing: null,
1289
+ restore: null,
1198
1290
  notice: null,
1199
1291
  sudoPrompt: null,
1200
1292
  };
@@ -1216,6 +1308,116 @@ export class WhereverClient {
1216
1308
  agentPending: false,
1217
1309
  }));
1218
1310
  break;
1311
+ case 'folder_missing':
1312
+ // The server states, authoritatively, that this session's working folder
1313
+ // is not usable -- it does not exist on this machine, or a restore is
1314
+ // still materialising it -- and names the absolute path. No session_ready
1315
+ // is coming (no agent was built), so this is also the end of the load:
1316
+ // read-only, with an explanation. Ignore a frame for a session we already
1317
+ // switched away from.
1318
+ //
1319
+ // `job` is any restore the server is ALREADY running for that path, so a
1320
+ // reconnect or a second device paints the running clone from this one
1321
+ // frame. With no job the panel simply offers to start one; either way the
1322
+ // restore state exists from here on, so a job another device starts is
1323
+ // painted by the progress frames that follow.
1324
+ this.stateStore.update((s) => {
1325
+ if (s.sessionId && msg.sessionId && s.sessionId !== msg.sessionId)
1326
+ return s;
1327
+ return {
1328
+ ...s,
1329
+ readOnly: true,
1330
+ folderMissing: { cwd: msg.cwd },
1331
+ restore: {
1332
+ targetPath: msg.cwd,
1333
+ job: msg.job ?? null,
1334
+ joined: false,
1335
+ rejection: null,
1336
+ },
1337
+ };
1338
+ });
1339
+ break;
1340
+ case 'restore_started': {
1341
+ // The answer to OUR restore_start. `outcome: 'joined'` means a job was
1342
+ // already running for this path and we coalesced onto it, so `job.url` is
1343
+ // the url really in flight -- which the panel must show when it differs
1344
+ // from the one this client asked for, rather than pretending the edited
1345
+ // url was accepted.
1346
+ //
1347
+ // It is ALSO the answer to a `session_new` that chose to CLONE an
1348
+ // existing remote. That create has no restore state yet (no session, so
1349
+ // no folder-missing frame ever created one), so the job is ADOPTED here
1350
+ // as the create's own: the blocking "Creating session..." overlay gives
1351
+ // way to the same progress the restore panel renders, and the create
1352
+ // watchdog -- which fires long before a large repository finishes -- is
1353
+ // disarmed, because a watched job is no longer something to time out.
1354
+ const before = get(this.stateStore);
1355
+ if (before.creatingSession && !before.restore) {
1356
+ this.clearCreateWatchdog();
1357
+ this.stateStore.update((s) => ({
1358
+ ...s,
1359
+ creatingSession: false,
1360
+ restore: {
1361
+ targetPath: msg.targetPath,
1362
+ job: msg.job,
1363
+ joined: msg.outcome === 'joined',
1364
+ rejection: null,
1365
+ forSessionCreate: true,
1366
+ },
1367
+ }));
1368
+ break;
1369
+ }
1370
+ this.stateStore.update((s) => this.withRestore(s, msg.targetPath, (r) => ({
1371
+ ...r,
1372
+ job: msg.job,
1373
+ joined: msg.outcome === 'joined',
1374
+ rejection: null,
1375
+ })));
1376
+ break;
1377
+ }
1378
+ case 'restore_rejected':
1379
+ // Refused before anything was spawned: no job, no completion coming. Keep
1380
+ // whatever job state we had (a rejection answers OUR request, it does not
1381
+ // touch a job someone else is running) and surface the reason.
1382
+ this.stateStore.update((s) => this.withRestore(s, msg.targetPath, (r) => ({
1383
+ ...r,
1384
+ rejection: { reason: msg.reason, message: msg.message },
1385
+ })));
1386
+ break;
1387
+ case 'restore_progress':
1388
+ case 'restore_complete': {
1389
+ // Broadcast frames: the server sends them to every client whose folder
1390
+ // matches the job path, so they arrive whether or not THIS client started
1391
+ // the restore (a second device, or a reconnect mid-clone). Each carries
1392
+ // the whole job snapshot, so one frame is enough to repaint.
1393
+ //
1394
+ // The new-session clone ends differently from the panel's: there is
1395
+ // nothing to reload, so a job that SUCCEEDED hands the screen straight
1396
+ // back to the create the server is already continuing with (overlay +
1397
+ // watchdog re-armed for that last, ordinary step). A failed or cancelled
1398
+ // one ends the create; the server's session_error, carrying the mapped
1399
+ // cause, arrives beside this frame.
1400
+ const current = get(this.stateStore).restore;
1401
+ if (msg.type === 'restore_complete' &&
1402
+ current?.forSessionCreate &&
1403
+ current.targetPath === msg.targetPath) {
1404
+ const cloned = msg.job.state === 'done';
1405
+ this.stateStore.update((s) => ({
1406
+ ...s,
1407
+ restore: null,
1408
+ creatingSession: cloned,
1409
+ }));
1410
+ if (cloned)
1411
+ this.armCreateWatchdog();
1412
+ break;
1413
+ }
1414
+ this.stateStore.update((s) => this.withRestore(s, msg.targetPath, (r) => ({
1415
+ ...r,
1416
+ job: msg.job,
1417
+ rejection: null,
1418
+ })));
1419
+ break;
1420
+ }
1219
1421
  case 'folder_conflict':
1220
1422
  // Live update of whether another active session still exists in this
1221
1423
  // client's folder. The banner appears when a second session shows up in
@@ -1226,15 +1428,25 @@ export class WhereverClient {
1226
1428
  return s;
1227
1429
  if (s.activeCwd && msg.cwd !== s.activeCwd)
1228
1430
  return s;
1431
+ // The server re-evaluates this client's read-only state on every
1432
+ // conflict update, so mirror it when reported. This is what releases
1433
+ // the composer once the conflict resolves (the banner alone cannot: it
1434
+ // disappears, taking its "Continue anyway" button with it) and what
1435
+ // keeps a hard sessions.readOnly folder locked. Older servers omit the
1436
+ // field, leaving read-only untouched as before.
1437
+ const readOnly = msg.readOnly ?? s.readOnly;
1229
1438
  if (!msg.active) {
1230
1439
  // No other session remains: fully resolved, drop the banner.
1231
- return s.folderConflict ? { ...s, folderConflict: null } : s;
1440
+ return s.folderConflict || readOnly !== s.readOnly
1441
+ ? { ...s, folderConflict: null, readOnly }
1442
+ : s;
1232
1443
  }
1233
1444
  if (s.folderConflict) {
1234
1445
  // Already showing: just refresh, preserving the user's `continued`
1235
1446
  // choice (so we don't re-disable a composer they already enabled).
1236
1447
  return {
1237
1448
  ...s,
1449
+ readOnly,
1238
1450
  folderConflict: { ...s.folderConflict, cwd: msg.cwd, active: true },
1239
1451
  };
1240
1452
  }
@@ -1244,6 +1456,7 @@ export class WhereverClient {
1244
1456
  // than yanking the composer into read-only underneath the user.
1245
1457
  return {
1246
1458
  ...s,
1459
+ readOnly,
1247
1460
  folderConflict: { cwd: msg.cwd, active: true, continued: true },
1248
1461
  };
1249
1462
  });
@@ -1733,6 +1946,50 @@ export class WhereverClient {
1733
1946
  this.persistPending(s.sessionId);
1734
1947
  return true;
1735
1948
  }
1949
+ // Re-materialize queued steers the message list does not have. A queued
1950
+ // message lives ONLY in the agent's memory until pi injects it at the next
1951
+ // step: it is not in the session file, so message_history cannot contain it.
1952
+ // On attach (a reload, or a second device) the server sends the queue as a
1953
+ // snapshot; without this the text would be invisible until it was delivered,
1954
+ // even though it was still going to be sent. Any queued entry with no matching
1955
+ // user message is appended so the UI can render it with the "Queued" badge and
1956
+ // the session-level cancel.
1957
+ //
1958
+ // Matching is by CONTENT, because the queue is a list of strings (pi exposes
1959
+ // no per-entry id). Occurrences are COUNTED, so a text queued twice restores
1960
+ // two bubbles, and a locally-sent (optimistic) steer already on screen is not
1961
+ // duplicated by the snapshot that follows it.
1962
+ withRestoredQueuedMessages(messages, steering) {
1963
+ if (steering.length === 0)
1964
+ return messages;
1965
+ const have = new Map();
1966
+ for (const m of messages) {
1967
+ if (m.role !== 'user')
1968
+ continue;
1969
+ have.set(m.content, (have.get(m.content) ?? 0) + 1);
1970
+ }
1971
+ const restored = [];
1972
+ for (const text of steering) {
1973
+ const remaining = have.get(text) ?? 0;
1974
+ if (remaining > 0) {
1975
+ have.set(text, remaining - 1);
1976
+ continue;
1977
+ }
1978
+ restored.push({
1979
+ id: this.generateId(),
1980
+ role: 'user',
1981
+ content: text,
1982
+ timestamp: Date.now(),
1983
+ isStreaming: false,
1984
+ restoredFromQueue: true,
1985
+ // NOT delivery-tracked: the server already holds this message, so it is
1986
+ // delivered as far as we are concerned. Tagging it pending would arm a
1987
+ // confirmation watchdog and wrongly offer "Retry" for a message that is
1988
+ // queued and will be sent.
1989
+ });
1990
+ }
1991
+ return restored.length > 0 ? [...messages, ...restored] : messages;
1992
+ }
1736
1993
  // ==========================================================================
1737
1994
  // Outbound-message delivery confirmation + recovery.
1738
1995
  //
@@ -1931,6 +2188,17 @@ export class WhereverClient {
1931
2188
  return;
1932
2189
  this.send({ type: 'abort', sessionId: s.sessionId });
1933
2190
  }
2191
+ // The web `/reload`: ask the server to rebuild the active session's agent so
2192
+ // it re-reads settings, extensions, skills, prompts and context files. Nothing
2193
+ // is changed locally: the server answers session_reloading (block the
2194
+ // composer), then session_ready, or a session_notice when it refuses (the
2195
+ // agent is busy, a CLI bridge owns the session, read-only).
2196
+ reloadResources() {
2197
+ const s = get(this.stateStore);
2198
+ if (!s.sessionId)
2199
+ return;
2200
+ this.send({ type: 'session_reload', sessionId: s.sessionId });
2201
+ }
1934
2202
  // Cancel the queued mid-stream steer messages for the active session without
1935
2203
  // aborting the in-flight turn. Optimistically clears our local pending-steer
1936
2204
  // set so the "Cancel" affordance disappears immediately; the server's fresh
@@ -1942,10 +2210,28 @@ export class WhereverClient {
1942
2210
  this.send({ type: 'cancel_steer', sessionId: s.sessionId });
1943
2211
  this.stateStore.update((st) => ({ ...st, pendingSteering: [] }));
1944
2212
  }
2213
+ /**
2214
+ * Apply `mutate` to the restore state for `targetPath`, or ignore the frame.
2215
+ *
2216
+ * Restore frames are addressed by PATH (the server's job key) rather than by
2217
+ * session id, because the server derives who gets them from a path match. This
2218
+ * is where a frame for a folder this client is no longer looking at is dropped
2219
+ * -- the one still in flight when the user switched sessions.
2220
+ */
2221
+ withRestore(s, targetPath, mutate) {
2222
+ const current = s.restore;
2223
+ if (!current || current.targetPath !== targetPath)
2224
+ return s;
2225
+ return { ...s, restore: mutate(current) };
2226
+ }
1945
2227
  joinSession(sessionFile, cwd, model) {
1946
2228
  this.stateStore.update((s) => ({
1947
2229
  ...s,
1948
2230
  folderConflict: null,
2231
+ // Both folder verdicts belong to the session being left; the load we are
2232
+ // starting re-states its own (the server re-checks on every load).
2233
+ folderMissing: null,
2234
+ restore: null,
1949
2235
  sessionError: null,
1950
2236
  loadingSession: true,
1951
2237
  agentPending: false,
@@ -1984,6 +2270,8 @@ export class WhereverClient {
1984
2270
  activeModel: null,
1985
2271
  readOnly: false,
1986
2272
  folderConflict: null,
2273
+ folderMissing: null,
2274
+ restore: null,
1987
2275
  sessionError: null,
1988
2276
  notice: null,
1989
2277
  sudoPrompt: null,
@@ -2019,6 +2307,10 @@ export class WhereverClient {
2019
2307
  this.stateStore.update((s) => ({
2020
2308
  ...s,
2021
2309
  folderConflict: null,
2310
+ // Creating a session creates its folder, so no missing-folder lock can
2311
+ // survive into it.
2312
+ folderMissing: null,
2313
+ restore: null,
2022
2314
  sessionError: null,
2023
2315
  creatingSession: true,
2024
2316
  loadingSession: false,
@@ -2064,6 +2356,8 @@ export class WhereverClient {
2064
2356
  activeCwd: null,
2065
2357
  activeModel: null,
2066
2358
  readOnly: false,
2359
+ folderMissing: null,
2360
+ restore: null,
2067
2361
  notice: null,
2068
2362
  sudoPrompt: null,
2069
2363
  creatingSession: false,
@@ -2079,6 +2373,84 @@ export class WhereverClient {
2079
2373
  this.resumeCwd = undefined;
2080
2374
  this.resumeModel = undefined;
2081
2375
  }
2376
+ // --- RESTORE: materialise the active session's missing working folder -----
2377
+ //
2378
+ // "Restore" here means making the missing FOLDER exist again (clone it back,
2379
+ // or create it), never the unrelated re-materialising of queued steers/drafts
2380
+ // after a reload. See CONTEXT.md; the whole family is namespaced `restore*`.
2381
+ /**
2382
+ * Ask the server to restore the folder of the folder-missing session this
2383
+ * client is looking at: CLONE `url` into it, or CREATE it.
2384
+ *
2385
+ * The job is server-owned and keyed by that path, so this may well JOIN a job
2386
+ * another device (or this client's previous, dropped socket) already started;
2387
+ * the server's `restore_started` says which, and carries the url really in
2388
+ * flight. Returns false when there is no missing folder to restore, or when a
2389
+ * clone was asked for with no url.
2390
+ */
2391
+ startRestore(action, url, gitInit) {
2392
+ const s = get(this.stateStore);
2393
+ const targetPath = s.restore?.targetPath ?? s.folderMissing?.cwd;
2394
+ if (!targetPath)
2395
+ return false;
2396
+ const trimmedUrl = url?.trim();
2397
+ if (action === 'clone' && !trimmedUrl)
2398
+ return false;
2399
+ // Record what WE asked for before the answer lands, so the panel can compare
2400
+ // it with the url the (possibly joined) job is really cloning.
2401
+ this.stateStore.update((st) => {
2402
+ const previous = st.restore?.targetPath === targetPath ? st.restore.job : null;
2403
+ return {
2404
+ ...st,
2405
+ restore: {
2406
+ targetPath,
2407
+ // A RUNNING job is the one this request will join, so it stays on
2408
+ // screen. A terminal one belonged to the attempt being retried: drop
2409
+ // it, so the panel shows this request in flight rather than the
2410
+ // previous failure until the server answers.
2411
+ job: previous && previous.state === 'running' ? previous : null,
2412
+ joined: false,
2413
+ requestedUrl: trimmedUrl,
2414
+ rejection: null,
2415
+ },
2416
+ };
2417
+ });
2418
+ return this.send({
2419
+ type: 'restore_start',
2420
+ targetPath,
2421
+ action,
2422
+ ...(trimmedUrl ? { url: trimmedUrl } : {}),
2423
+ ...(gitInit !== undefined ? { gitInit } : {}),
2424
+ });
2425
+ }
2426
+ /**
2427
+ * Cancel the restore running for this session's folder. The server settles the
2428
+ * job authoritatively and broadcasts the `cancelled` completion to every client
2429
+ * watching that folder (this one included), so no state is guessed here.
2430
+ */
2431
+ cancelRestore() {
2432
+ const s = get(this.stateStore);
2433
+ const targetPath = s.restore?.targetPath;
2434
+ if (!targetPath)
2435
+ return false;
2436
+ return this.send({ type: 'restore_cancel', targetPath });
2437
+ }
2438
+ /**
2439
+ * Re-load the active session file.
2440
+ *
2441
+ * This is how a completed restore goes LIVE: whether a session has a live agent
2442
+ * is a load-time decision, and the load that found the folder missing
2443
+ * deliberately built none. Re-loading is therefore the honest way to get one,
2444
+ * not a refresh hint. Returns false when there is no active session file.
2445
+ */
2446
+ reloadSession() {
2447
+ const s = get(this.stateStore);
2448
+ const sessionFile = s.activeSessionFile;
2449
+ if (!sessionFile)
2450
+ return false;
2451
+ this.joinSession(sessionFile, s.activeCwd ?? undefined);
2452
+ return true;
2453
+ }
2082
2454
  // "Continue anyway" on the folder-conflict warning banner: ask the server to
2083
2455
  // lift read-only for this client's current session (both sessions in the
2084
2456
  // folder then run concurrently; the other is NOT aborted). Optimistically
@@ -2088,6 +2460,11 @@ export class WhereverClient {
2088
2460
  const s = get(this.stateStore);
2089
2461
  if (!s.folderConflict || !s.sessionId)
2090
2462
  return;
2463
+ // "Continue anyway" answers a folder CONFLICT only. A missing folder is a
2464
+ // hard lock (there is nothing to drive, and no agent was built), and the
2465
+ // server refuses to lift it, so do not flash an enabled composer here.
2466
+ if (s.folderMissing)
2467
+ return;
2091
2468
  this.send({
2092
2469
  type: 'folder_conflict_continue',
2093
2470
  sessionId: s.sessionId,