wherever-dev 0.10.14 → 0.10.15

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.
Files changed (28) hide show
  1. package/dist/index.js +251 -28
  2. package/dist/index.js.map +1 -1
  3. package/dist/protocol.d.ts +3 -0
  4. package/dist/protocol.d.ts.map +1 -1
  5. package/package.json +1 -1
  6. package/public/_app/immutable/chunks/Dma3J3qQ.js +2 -0
  7. package/public/_app/immutable/chunks/{CDbw105l.js.map → Dma3J3qQ.js.map} +1 -1
  8. package/public/_app/immutable/chunks/{BzFqVyJ_.js → L93I-H4j.js} +2 -2
  9. package/public/_app/immutable/chunks/{BzFqVyJ_.js.map → L93I-H4j.js.map} +1 -1
  10. package/public/_app/immutable/chunks/{ClTMu0mO.js → vpatnBE2.js} +2 -2
  11. package/public/_app/immutable/chunks/{ClTMu0mO.js.map → vpatnBE2.js.map} +1 -1
  12. package/public/_app/immutable/entry/{app.CqLyltZH.js → app.CqtGQvSV.js} +3 -3
  13. package/public/_app/immutable/entry/{app.CqLyltZH.js.map → app.CqtGQvSV.js.map} +1 -1
  14. package/public/_app/immutable/entry/start.C2OvHZ6Z.js +2 -0
  15. package/public/_app/immutable/entry/start.C2OvHZ6Z.js.map +1 -0
  16. package/public/_app/immutable/nodes/{0.D_7-7cgp.js → 0.6DAAbCKP.js} +2 -2
  17. package/public/_app/immutable/nodes/{0.D_7-7cgp.js.map → 0.6DAAbCKP.js.map} +1 -1
  18. package/public/_app/immutable/nodes/{1.CDxNOU-Q.js → 1.Y9ZXDXG1.js} +2 -2
  19. package/public/_app/immutable/nodes/{1.CDxNOU-Q.js.map → 1.Y9ZXDXG1.js.map} +1 -1
  20. package/public/_app/immutable/nodes/{2.D1gQZgOb.js → 2.CNwl77oM.js} +31 -31
  21. package/public/_app/immutable/nodes/2.CNwl77oM.js.map +1 -0
  22. package/public/_app/version.json +1 -1
  23. package/public/index.html +10 -10
  24. package/public/service-worker.js +1 -1
  25. package/public/_app/immutable/chunks/CDbw105l.js +0 -2
  26. package/public/_app/immutable/entry/start.CQ4WvoOm.js +0 -2
  27. package/public/_app/immutable/entry/start.CQ4WvoOm.js.map +0 -1
  28. package/public/_app/immutable/nodes/2.D1gQZgOb.js.map +0 -1
package/dist/index.js CHANGED
@@ -276,6 +276,37 @@ function serveStaticFile(reqPath, res) {
276
276
  }
277
277
  });
278
278
  }
279
+ // Retire any still-registered VIEWER connection carrying the same clientKey: it
280
+ // is the SAME viewer's superseded socket (a reconnect), not a second viewer.
281
+ // Detach it from its session synchronously so the very next message on the new
282
+ // socket sees an accurate client count, then terminate the dead socket.
283
+ //
284
+ // CLI bridges are deliberately left ALONE: their re-registration is already
285
+ // handled by registerCliSession/unregisterCliSession, and tearing one down here
286
+ // would race a cli_register arriving on the new socket against the old socket's
287
+ // async close teardown, which could unregister the session that was just
288
+ // re-registered.
289
+ function evictPreviousConnection(clientKey, clients, pool, onSessionsUpdated) {
290
+ for (const prev of Array.from(clients.values())) {
291
+ if (prev.clientKey !== clientKey || prev.isCliBridge)
292
+ continue;
293
+ if (prev.sessionId) {
294
+ pool.removeClient(prev.sessionId, prev.id);
295
+ prev.sessionId = null;
296
+ }
297
+ clearConflictState(prev);
298
+ clients.delete(prev.id);
299
+ // Tell the superseded connection WHY it is going away, and only then kill it.
300
+ // If it is in fact alive (two tabs that ended up sharing a key, e.g. a
301
+ // duplicated tab cloning sessionStorage), it regenerates its key and comes
302
+ // back as a distinct viewer instead of evicting the other one right back in
303
+ // an endless ping-pong. Losing this frame would restore exactly that
304
+ // ping-pong, with no backstop, so it must not be discarded by the teardown.
305
+ // A genuinely dead socket never reads it and is reaped on the flush timeout.
306
+ sendThenTerminate(prev.ws, { type: 'connection_superseded' });
307
+ onSessionsUpdated();
308
+ }
309
+ }
279
310
  function generateId() {
280
311
  return Math.random().toString(36).substring(2) + Date.now().toString(36);
281
312
  }
@@ -408,6 +439,46 @@ function sendWS(ws, msg) {
408
439
  }
409
440
  }
410
441
  }
442
+ // Send a final message and THEN kill the socket, without losing the message.
443
+ // terminate() destroys the socket and discards whatever is still buffered; over
444
+ // TLS (this server's default) a small frame is frequently still buffered when
445
+ // the send call returns, so terminating in the same tick can drop it. Wait for
446
+ // the write callback, with a timer so a socket that never flushes (the usual
447
+ // case here: the peer is gone) is still reaped promptly.
448
+ function sendThenTerminate(ws, msg, flushTimeoutMs = 1_000) {
449
+ let done = false;
450
+ const kill = () => {
451
+ if (done)
452
+ return;
453
+ done = true;
454
+ try {
455
+ // terminate() (not close()) because a superseded socket is typically
456
+ // half-open: a close handshake would never complete.
457
+ if (typeof ws.terminate === 'function')
458
+ ws.terminate();
459
+ else
460
+ ws.close();
461
+ }
462
+ catch { }
463
+ };
464
+ const timer = setTimeout(kill, flushTimeoutMs);
465
+ timer.unref?.();
466
+ if (ws.readyState !== WebSocket.OPEN) {
467
+ clearTimeout(timer);
468
+ kill();
469
+ return;
470
+ }
471
+ try {
472
+ ws.send(JSON.stringify(msg), () => {
473
+ clearTimeout(timer);
474
+ kill();
475
+ });
476
+ }
477
+ catch (err) {
478
+ clearTimeout(timer);
479
+ kill();
480
+ }
481
+ }
411
482
  async function main() {
412
483
  const { port, host, token, idleTimeout, sslKey, sslCert, noSsl, httpLocalhostFallbackPort, debug } = parseArgs();
413
484
  debugEnabled = debug;
@@ -491,24 +562,10 @@ async function main() {
491
562
  // gone. Sent on every session-set change (open/leave/create/destroy). CLI
492
563
  // bridge connections are skipped (they have no banner UI).
493
564
  function broadcastFolderConflicts() {
565
+ // readOnly rides along every time so the client's composer mirrors the
566
+ // server's authority rather than inferring it from `active`.
494
567
  for (const c of clients.values()) {
495
- if (c.isCliBridge)
496
- continue;
497
- if (!c.sessionId)
498
- continue;
499
- const mine = sessionPool.getSession(c.sessionId);
500
- if (!mine)
501
- continue;
502
- let active = false;
503
- for (const s of sessionPool.getAllSessions()) {
504
- if (s.sessionFile === mine.sessionFile)
505
- continue;
506
- if (s.cwd === mine.cwd && s.clients.size > 0) {
507
- active = true;
508
- break;
509
- }
510
- }
511
- sendWS(c.ws, { type: 'folder_conflict', cwd: mine.cwd, active });
568
+ sendFolderConflict(c, sessionPool);
512
569
  }
513
570
  }
514
571
  function broadcastAgentEvent(sessionFile, event) {
@@ -1043,6 +1100,8 @@ async function main() {
1043
1100
  sendWS(c.ws, wsMsg);
1044
1101
  c.sessionId = null;
1045
1102
  c.readOnly = false;
1103
+ // The conflict decision belonged to the session that just went away.
1104
+ clearConflictState(c);
1046
1105
  }
1047
1106
  }
1048
1107
  }
@@ -1093,6 +1152,8 @@ async function main() {
1093
1152
  sendWS(c.ws, wsMsg);
1094
1153
  c.sessionId = null;
1095
1154
  c.readOnly = false;
1155
+ // The conflict decision belonged to the session that just went away.
1156
+ clearConflictState(c);
1096
1157
  }
1097
1158
  }
1098
1159
  sessionPool.destroySession(tracked.sessionFile, 'deleted');
@@ -1394,13 +1455,43 @@ async function main() {
1394
1455
  if (httpServer) {
1395
1456
  httpServer.on('upgrade', upgradeHandler);
1396
1457
  }
1397
- wss.on('connection', (ws) => {
1458
+ wss.on('connection', (ws, req) => {
1398
1459
  const clientId = generateId();
1460
+ // Stable per-viewer identity (see WhereverClientConfig.clientKey). A client
1461
+ // that lost its socket silently (half-open TCP: phone sleep, network switch)
1462
+ // reconnects on a NEW socket while the old record still sits in the pool
1463
+ // until the heartbeat reaper notices, up to 2x HEARTBEAT_MS later. That
1464
+ // phantom counted as "another viewer", which silently turned an explicit
1465
+ // "New Session Here" into a folder conflict (read-only attach to the folder's
1466
+ // existing session). Retiring the same key's previous connection HERE, before
1467
+ // any session traffic on the new socket, closes that window. Keys are scoped
1468
+ // per tab by the web client, so two real tabs remain two distinct viewers.
1469
+ let clientKey;
1470
+ try {
1471
+ const url = new URL(req?.url || '', `http://${req?.headers?.host || 'localhost'}`);
1472
+ const raw = url.searchParams.get('clientKey');
1473
+ // Bounded: this is client-supplied text retained for the life of the
1474
+ // connection. Anything longer than a generated key is not one. Refuse it
1475
+ // rather than truncating (two distinct long keys must not collapse into one
1476
+ // identity and start evicting each other), and say so: the connection
1477
+ // silently loses supersede protection otherwise.
1478
+ if (raw && raw.length > 128) {
1479
+ console.warn(`[wherever] ignoring oversized clientKey (${raw.length} chars) from ${req?.socket?.remoteAddress ?? 'unknown'}`);
1480
+ }
1481
+ else if (raw) {
1482
+ clientKey = raw;
1483
+ }
1484
+ }
1485
+ catch { }
1486
+ if (clientKey) {
1487
+ evictPreviousConnection(clientKey, clients, sessionPool, broadcastSessionsUpdated);
1488
+ }
1399
1489
  const client = {
1400
1490
  id: clientId,
1401
1491
  ws,
1402
1492
  sessionId: null,
1403
1493
  readOnly: false,
1494
+ clientKey,
1404
1495
  };
1405
1496
  clients.set(clientId, client);
1406
1497
  // Liveness: assume alive on connect; any pong (reply to the heartbeat ping
@@ -1546,11 +1637,84 @@ This encrypts all network traffic securely and enables safe, private remote acce
1546
1637
  process.on('SIGTERM', shutdown);
1547
1638
  process.on('SIGINT', shutdown);
1548
1639
  }
1640
+ // The conflict decision belongs to the PAIRING of this client with one session.
1641
+ // Clear every part of it together whenever that pairing ends, so no half-state
1642
+ // (an observer flag without its continue, a cwd from a session we left) can be
1643
+ // read by the next attach.
1644
+ function clearConflictState(client) {
1645
+ client.conflictObserver = false;
1646
+ client.conflictContinued = false;
1647
+ client.pendingCwd = undefined;
1648
+ }
1649
+ // Recompute ONE client's folder-conflict state and settle the read-only it
1650
+ // imposed: releasing it once the conflict no longer holds is part of resolving,
1651
+ // not a side effect the callers could skip. Shared by the live broadcast, the
1652
+ // cold attach and the "Continue anyway" reply so all three speak with one
1653
+ // authority. Returns null for connections the banner does not apply to (CLI
1654
+ // bridges, clients not attached to a session).
1655
+ function resolveFolderConflictState(c, pool) {
1656
+ if (c.isCliBridge || !c.sessionId)
1657
+ return null;
1658
+ const mine = pool.getSession(c.sessionId);
1659
+ if (!mine)
1660
+ return null;
1661
+ let active = false;
1662
+ for (const s of pool.getAllSessions()) {
1663
+ if (s.sessionFile === mine.sessionFile)
1664
+ continue;
1665
+ if (s.cwd === mine.cwd && s.clients.size > 0) {
1666
+ active = true;
1667
+ break;
1668
+ }
1669
+ }
1670
+ // A conflict OBSERVER shares the occupant's session file (session_new attaches
1671
+ // it there read-only), so the scan above -- which skips this very file -- can
1672
+ // never see its conflict. Its conflict lasts exactly as long as someone else is
1673
+ // still on that session.
1674
+ if (!active && c.conflictObserver) {
1675
+ for (const cid of mine.clients) {
1676
+ if (cid !== c.id) {
1677
+ active = true;
1678
+ break;
1679
+ }
1680
+ }
1681
+ }
1682
+ // The conflict resolved (the other party left the folder/session): release the
1683
+ // read-only state it imposed, otherwise the client keeps an observe-only
1684
+ // composer forever with no banner left to lift it. A configured
1685
+ // sessions.readOnly folder is a hard rule and is never lifted here.
1686
+ if (c.conflictObserver && !active) {
1687
+ c.conflictObserver = false;
1688
+ if (!pool.isReadOnlyCwd(mine.cwd))
1689
+ c.readOnly = false;
1690
+ }
1691
+ return { cwd: mine.cwd, active };
1692
+ }
1693
+ // Resolve and report in one step. Every folder_conflict frame goes out through
1694
+ // here, so the `readOnly` it carries can never drift from the authority that
1695
+ // produced `active`.
1696
+ function sendFolderConflict(client, pool) {
1697
+ const verdict = resolveFolderConflictState(client, pool);
1698
+ if (!verdict)
1699
+ return;
1700
+ sendWS(client.ws, {
1701
+ type: 'folder_conflict',
1702
+ cwd: verdict.cwd,
1703
+ active: verdict.active,
1704
+ readOnly: client.readOnly,
1705
+ });
1706
+ }
1549
1707
  function switchClientSession(client, newSessionFile, pool, onSessionsUpdated) {
1550
1708
  if (client.sessionId && client.sessionId !== newSessionFile) {
1551
1709
  pool.removeClient(client.sessionId, client.id);
1552
1710
  }
1553
1711
  client.sessionId = newSessionFile;
1712
+ // Detaching ends the pairing the conflict decision belonged to. (An ATTACH must
1713
+ // not clear it: a "Continue anyway" clicked during a cold load is recorded
1714
+ // before this call and has to survive it.)
1715
+ if (newSessionFile === null) {
1716
+ clearConflictState(client);
1717
+ }
1554
1718
  if (onSessionsUpdated) {
1555
1719
  onSessionsUpdated();
1556
1720
  }
@@ -1663,6 +1827,10 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
1663
1827
  // 2. Build the live agent (createAgentSession -> extension/MCP load, the
1664
1828
  // seconds-long part) ASYNC, then signal session_ready so the composer
1665
1829
  // enables. Sending needs the live agent; reading does not.
1830
+ // A new load is a new decision: any earlier "Continue anyway" belongs to the
1831
+ // session we are leaving. Reset BEFORE the first await, so a continue that
1832
+ // races this load is recorded against the load, never wiped by it.
1833
+ client.conflictContinued = false;
1666
1834
  const meta = await pool.readSessionMeta(msg.sessionFile, INITIAL_HISTORY_LIMIT, msg.model);
1667
1835
  if ('error' in meta) {
1668
1836
  sendWS(client.ws, { type: 'session_error', error: meta.error });
@@ -1680,6 +1848,8 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
1680
1848
  // A folder conflict also starts the client read-only until they continue.
1681
1849
  const forcedReadOnly = meta.readOnly || folderConflict;
1682
1850
  client.readOnly = forcedReadOnly;
1851
+ client.conflictObserver = folderConflict;
1852
+ client.pendingCwd = meta.cwd;
1683
1853
  // Paint immediately. `pending` is true when the live agent is not resident
1684
1854
  // yet, so the client keeps the composer disabled (with a "preparing
1685
1855
  // agent..." hint) until session_ready, while reading/scrolling work now.
@@ -1739,10 +1909,17 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
1739
1909
  }
1740
1910
  pool.addClient(result.tracked.sessionFile, client.id);
1741
1911
  switchClientSession(client, result.tracked.sessionFile, pool, onSessionsUpdated);
1742
- // Preserve the folder-conflict read-only: a forced-read-only (config or
1743
- // folder conflict) client must stay read-only until it explicitly
1744
- // continues, so don't clobber it with the cwd-glob check alone.
1745
- client.readOnly = forcedReadOnly || pool.isReadOnlyCwd(result.tracked.cwd);
1912
+ // Re-derive read-only from the CURRENT decision rather than from
1913
+ // `forcedReadOnly` captured before the build: while the agent was building
1914
+ // the user may have clicked "Continue anyway" (conflictContinued), and
1915
+ // re-imposing the stale value re-locked them with no banner left to lift
1916
+ // it, while `message` dropped their sends in silence. The conflict having
1917
+ // RESOLVED during the build is handled just below by the verdict, which
1918
+ // re-scans and releases read-only.
1919
+ client.readOnly =
1920
+ meta.readOnly ||
1921
+ pool.isReadOnlyCwd(result.tracked.cwd) ||
1922
+ (client.conflictObserver === true && !client.conflictContinued);
1746
1923
  sendWS(client.ws, {
1747
1924
  type: 'session_ready',
1748
1925
  sessionId: result.tracked.sessionId,
@@ -1755,6 +1932,11 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
1755
1932
  // taken over by another client mid-build; send the authoritative snapshot
1756
1933
  // for the same reason as the warm path above.
1757
1934
  sendQueueSnapshot(client, result.tracked.sessionFile, result.tracked.sessionId, pool);
1935
+ // State may have moved during the build (the conflict resolved, or the
1936
+ // user continued through it). session_ready carries no readOnly, and the
1937
+ // periodic conflict broadcast is throttled, so state the verdict here
1938
+ // explicitly rather than leaving the composer to guess for up to 2s.
1939
+ sendFolderConflict(client, pool);
1758
1940
  })();
1759
1941
  break;
1760
1942
  }
@@ -1803,9 +1985,12 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
1803
1985
  // existing one), so attach to that existing session as a read-only
1804
1986
  // observer and raise the warning banner. "Continue anyway"
1805
1987
  // (folder_conflict_continue) lifts read-only so both can send.
1806
- client.readOnly = true;
1807
1988
  pool.addClient(existing.sessionFile, client.id);
1808
1989
  switchClientSession(client, existing.sessionFile, pool, onSessionsUpdated);
1990
+ client.readOnly = true;
1991
+ clearConflictState(client);
1992
+ client.conflictObserver = true;
1993
+ client.pendingCwd = existing.cwd;
1809
1994
  sendWS(client.ws, {
1810
1995
  type: 'session_created',
1811
1996
  sessionId: existing.sessionId,
@@ -1840,6 +2025,8 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
1840
2025
  pool.addClient(result.tracked.sessionFile, client.id);
1841
2026
  switchClientSession(client, result.tracked.sessionFile, pool, onSessionsUpdated);
1842
2027
  client.readOnly = false;
2028
+ clearConflictState(client);
2029
+ client.pendingCwd = result.tracked.cwd;
1843
2030
  sendWS(client.ws, {
1844
2031
  type: 'session_created',
1845
2032
  sessionId: result.tracked.sessionId,
@@ -1893,19 +2080,55 @@ async function handleWSMessage(msg, client, pool, clients, broadcast, onSessions
1893
2080
  // run concurrently from here on. Guard: never lift read-only for a session
1894
2081
  // whose cwd is a configured sessions.readOnly folder (that is a hard
1895
2082
  // observe-only rule, not a dismissible warning).
2083
+ // The cwd may come from an attached session or, during a cold load's agent
2084
+ // build, from the load in progress: the user can click Continue on the
2085
+ // painted-but-not-yet-attached conversation, and dropping that click left
2086
+ // them read-only with the button already gone.
1896
2087
  const tracked = client.sessionId ? pool.getSession(client.sessionId) : null;
1897
- if (!tracked)
1898
- return;
1899
- if (pool.isReadOnlyCwd(tracked.cwd))
2088
+ const cwd = tracked?.cwd ?? client.pendingCwd;
2089
+ if (!cwd)
1900
2090
  return;
1901
- client.readOnly = false;
2091
+ // The client stamps the session it was looking at. If that resolves to a
2092
+ // DIFFERENT folder, the session changed under the click (a switch racing the
2093
+ // tap): honouring it would continue through a conflict the user never saw.
2094
+ // An unresolvable id means the target is not resident (the cold-load case
2095
+ // this continue exists for), which the cwd check above already covers.
2096
+ if (msg.sessionId) {
2097
+ const target = pool.getSession(msg.sessionId);
2098
+ if (target && target.cwd !== cwd)
2099
+ return;
2100
+ }
2101
+ // Durable intent: honoured at attach even if the click landed before this
2102
+ // client had a session to lift read-only on.
2103
+ client.conflictContinued = true;
2104
+ if (!pool.isReadOnlyCwd(cwd))
2105
+ client.readOnly = false;
2106
+ // Reply with this client's authoritative conflict state, ALWAYS (including
2107
+ // when the lift was refused for a sessions.readOnly folder). Same-socket
2108
+ // ordering guarantees this lands after any folder_conflict broadcast that
2109
+ // was already in flight when the continue was sent, so an in-flight update
2110
+ // carrying the pre-continue readOnly:true cannot leave the composer
2111
+ // disabled with the banner's button already gone.
2112
+ sendFolderConflict(client, pool);
1902
2113
  break;
1903
2114
  }
1904
2115
  case 'message': {
1905
2116
  if (!client.sessionId)
1906
2117
  return;
1907
- if (client.readOnly)
2118
+ if (client.readOnly) {
2119
+ // Never swallow a send. This is a legitimate refusal for an observe-only
2120
+ // session (a sessions.readOnly folder, or a folder conflict not continued
2121
+ // through), but the client only hides its composer when it AGREES it is
2122
+ // read-only -- so any future desync of that agreement used to show up as
2123
+ // text vanishing into the void. Answering makes it a visible, retryable
2124
+ // failure instead (the client surfaces session_error with a Retry).
2125
+ sendWS(client.ws, {
2126
+ type: 'session_error',
2127
+ sessionId: msg.sessionId,
2128
+ error: 'This session is read-only from here, so the message was not delivered. Use "Continue anyway" on the folder-conflict banner, or open the session that owns this folder.',
2129
+ });
1908
2130
  return;
2131
+ }
1909
2132
  // The client stamps every send with the sessionId of the session it is
1910
2133
  // actually viewing. Treat that as AUTHORITATIVE: if it does not resolve to
1911
2134
  // the same tracked session this connection is attached to, REFUSE rather