@qvac/core 0.3.5 → 0.4.1

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 (173) hide show
  1. package/CHANGELOG.md +177 -9
  2. package/README.md +19 -17
  3. package/dist-lib/lib/api/agents.d.ts +3 -3
  4. package/dist-lib/lib/api/agents.js +31 -20
  5. package/dist-lib/lib/api/approval-rules.d.ts +2 -2
  6. package/dist-lib/lib/api/approval-rules.js +2 -2
  7. package/dist-lib/lib/api/attachments.d.ts +2 -2
  8. package/dist-lib/lib/api/attachments.js +14 -25
  9. package/dist-lib/lib/api/chat-groups.d.ts +2 -2
  10. package/dist-lib/lib/api/chat-groups.js +9 -9
  11. package/dist-lib/lib/api/chat.d.ts +4 -2
  12. package/dist-lib/lib/api/chat.js +18 -18
  13. package/dist-lib/lib/api/chunks.d.ts +2 -2
  14. package/dist-lib/lib/api/chunks.js +27 -36
  15. package/dist-lib/lib/api/current-mesh.d.ts +7 -15
  16. package/dist-lib/lib/api/current-mesh.js +7 -22
  17. package/dist-lib/lib/api/devices.d.ts +4 -3
  18. package/dist-lib/lib/api/devices.js +18 -18
  19. package/dist-lib/lib/api/execution.d.ts +2 -2
  20. package/dist-lib/lib/api/execution.js +6 -6
  21. package/dist-lib/lib/api/files.d.ts +2 -2
  22. package/dist-lib/lib/api/files.js +4 -4
  23. package/dist-lib/lib/api/index.d.ts +12 -11
  24. package/dist-lib/lib/api/index.js +15 -13
  25. package/dist-lib/lib/api/inference-calls.d.ts +1 -1
  26. package/dist-lib/lib/api/inference-calls.js +2 -2
  27. package/dist-lib/lib/api/knowledge.d.ts +2 -2
  28. package/dist-lib/lib/api/knowledge.js +22 -11
  29. package/dist-lib/lib/api/local-files.d.ts +3 -0
  30. package/dist-lib/lib/api/local-files.js +23 -0
  31. package/dist-lib/lib/api/members.d.ts +6 -2
  32. package/dist-lib/lib/api/members.js +24 -17
  33. package/dist-lib/lib/api/mesh.d.ts +4 -5
  34. package/dist-lib/lib/api/mesh.js +7 -9
  35. package/dist-lib/lib/api/notifications.d.ts +2 -13
  36. package/dist-lib/lib/api/notifications.js +20 -52
  37. package/dist-lib/lib/api/rag.d.ts +2 -2
  38. package/dist-lib/lib/api/rag.js +4 -4
  39. package/dist-lib/lib/api/range.d.ts +11 -0
  40. package/dist-lib/lib/api/range.js +10 -0
  41. package/dist-lib/lib/api/sync.d.ts +2 -2
  42. package/dist-lib/lib/api/sync.js +3 -3
  43. package/dist-lib/lib/api/tool-activity.d.ts +2 -2
  44. package/dist-lib/lib/api/tool-activity.js +11 -10
  45. package/dist-lib/lib/api/tool-configs.d.ts +2 -2
  46. package/dist-lib/lib/api/tool-configs.js +6 -7
  47. package/dist-lib/lib/api/upload-frames.d.ts +9 -0
  48. package/dist-lib/lib/api/upload-frames.js +17 -0
  49. package/dist-lib/lib/api/watchable.d.ts +1 -6
  50. package/dist-lib/lib/api/watchable.js +4 -13
  51. package/dist-lib/lib/assistant/history.d.ts +3 -3
  52. package/dist-lib/lib/assistant-client.js +3 -2
  53. package/dist-lib/lib/assistant-tree.js +1 -1
  54. package/dist-lib/lib/assistant.d.ts +16 -14
  55. package/dist-lib/lib/assistant.js +166 -137
  56. package/dist-lib/lib/collabora/convert.js +1 -1
  57. package/dist-lib/lib/core/agent.d.ts +5 -7
  58. package/dist-lib/lib/core/agent.js +26 -6
  59. package/dist-lib/lib/core/archived-mesh.js +1 -0
  60. package/dist-lib/lib/core/chat-order.d.ts +20 -0
  61. package/dist-lib/lib/core/chat-order.js +96 -0
  62. package/dist-lib/lib/core/chat.d.ts +0 -5
  63. package/dist-lib/lib/core/chat.js +1 -3
  64. package/dist-lib/lib/core/chunk.d.ts +7 -14
  65. package/dist-lib/lib/core/chunk.js +17 -35
  66. package/dist-lib/lib/core/contract/agents.js +8 -0
  67. package/dist-lib/lib/core/contract/compute.d.ts +1 -1
  68. package/dist-lib/lib/core/contract/compute.js +1 -0
  69. package/dist-lib/lib/core/contract/joined-meshes.js +4 -3
  70. package/dist-lib/lib/core/contract/members.js +4 -3
  71. package/dist-lib/lib/core/contract/writers.js +5 -4
  72. package/dist-lib/lib/core/departures.js +5 -4
  73. package/dist-lib/lib/core/device-invites.js +2 -1
  74. package/dist-lib/lib/core/files/attachments.d.ts +8 -1
  75. package/dist-lib/lib/core/files/index.d.ts +4 -4
  76. package/dist-lib/lib/core/files/index.js +18 -8
  77. package/dist-lib/lib/core/files/local-index.d.ts +16 -0
  78. package/dist-lib/lib/core/files/local-index.js +38 -0
  79. package/dist-lib/lib/core/files/processing/document.js +2 -1
  80. package/dist-lib/lib/core/files/processing/ownership.js +6 -3
  81. package/dist-lib/lib/core/files/records/chunks.js +1 -0
  82. package/dist-lib/lib/core/files/records/reclaim.js +1 -0
  83. package/dist-lib/lib/core/files/records/routing.js +2 -1
  84. package/dist-lib/lib/core/files/store/blob.d.ts +1 -1
  85. package/dist-lib/lib/core/files/store/blob.js +6 -3
  86. package/dist-lib/lib/core/files/store/index.d.ts +1 -1
  87. package/dist-lib/lib/core/files/store/reference.js +4 -3
  88. package/dist-lib/lib/core/files/store/server.d.ts +8 -4
  89. package/dist-lib/lib/core/files/store/server.js +16 -12
  90. package/dist-lib/lib/core/files/store/sweep.js +2 -1
  91. package/dist-lib/lib/core/files/upload.d.ts +1 -1
  92. package/dist-lib/lib/core/hosted-agents.js +1 -1
  93. package/dist-lib/lib/core/image/cache-sweep.d.ts +1 -0
  94. package/dist-lib/lib/core/image/cache-sweep.js +7 -3
  95. package/dist-lib/lib/core/local/files.d.ts +24 -0
  96. package/dist-lib/lib/core/local/files.js +154 -0
  97. package/dist-lib/lib/core/local/index.d.ts +21 -5
  98. package/dist-lib/lib/core/local/index.js +75 -45
  99. package/dist-lib/lib/core/membership.d.ts +4 -1
  100. package/dist-lib/lib/core/membership.js +17 -2
  101. package/dist-lib/lib/core/mesh.d.ts +5 -0
  102. package/dist-lib/lib/core/mesh.js +10 -5
  103. package/dist-lib/lib/core/migrations/agent-indexes.d.ts +2 -0
  104. package/dist-lib/lib/core/migrations/agent-indexes.js +30 -0
  105. package/dist-lib/lib/core/migrations/file-index.d.ts +2 -0
  106. package/dist-lib/lib/core/migrations/file-index.js +27 -0
  107. package/dist-lib/lib/core/migrations/index.js +3 -1
  108. package/dist-lib/lib/core/notification.js +5 -5
  109. package/dist-lib/lib/core/range.d.ts +18 -0
  110. package/dist-lib/lib/core/range.js +17 -0
  111. package/dist-lib/lib/core/sync/index.js +39 -32
  112. package/dist-lib/lib/core/sync-status.js +3 -2
  113. package/dist-lib/lib/core/tool-activity.d.ts +2 -5
  114. package/dist-lib/lib/core/tool-activity.js +4 -7
  115. package/dist-lib/lib/core.d.ts +48 -29
  116. package/dist-lib/lib/core.js +465 -359
  117. package/dist-lib/lib/knowledge-search.d.ts +2 -2
  118. package/dist-lib/lib/kv-cache.js +1 -1
  119. package/dist-lib/lib/log.js +2 -3
  120. package/dist-lib/lib/mesh-scoped-engine.d.ts +8 -1
  121. package/dist-lib/lib/mesh-scoped-engine.js +62 -15
  122. package/dist-lib/lib/model-download.d.ts +14 -5
  123. package/dist-lib/lib/model-download.js +25 -17
  124. package/dist-lib/lib/oauth/browser-connect.d.ts +0 -14
  125. package/dist-lib/lib/oauth/browser-connect.js +1 -26
  126. package/dist-lib/lib/oauth/token-exchange.d.ts +1 -2
  127. package/dist-lib/lib/oauth/token-exchange.js +1 -4
  128. package/dist-lib/lib/run-transcript.d.ts +2 -2
  129. package/dist-lib/lib/run-transcript.js +3 -2
  130. package/dist-lib/lib/task.d.ts +1 -0
  131. package/dist-lib/lib/task.js +3 -2
  132. package/dist-lib/schema/build.js +4 -10
  133. package/dist-lib/schema/engine.js +261 -91
  134. package/dist-lib/schema/field-order.js +1 -4
  135. package/dist-lib/schema/helpers.d.ts +4 -0
  136. package/dist-lib/schema/helpers.js +20 -0
  137. package/dist-lib/schema/local.d.ts +1 -1
  138. package/dist-lib/schema/local.js +70 -2
  139. package/dist-lib/schema/qvac.js +30 -0
  140. package/dist-lib/spec/bind.js +20 -3
  141. package/dist-lib/spec/calls.js +19 -15
  142. package/dist-lib/spec/capabilities.d.ts +42 -34
  143. package/dist-lib/spec/hrpc/hrpc.json +82 -30
  144. package/dist-lib/spec/hrpc/index.js +106 -57
  145. package/dist-lib/spec/hrpc/messages.js +5420 -5019
  146. package/dist-lib/spec/hyperschema/index.js +5424 -5023
  147. package/dist-lib/spec/hyperschema/schema.json +3202 -2666
  148. package/dist-lib/spec/hyperschema/types.d.ts +455 -319
  149. package/dist-lib/spec/local/hyperdb/db.json +119 -1
  150. package/dist-lib/spec/local/hyperdb/index.js +414 -2
  151. package/dist-lib/spec/local/hyperdb/messages.js +505 -124
  152. package/dist-lib/spec/local/hyperschema/index.js +203 -5
  153. package/dist-lib/spec/local/hyperschema/schema.json +136 -1
  154. package/dist-lib/spec/local/hyperschema/types.d.ts +32 -1
  155. package/dist-lib/spec/mesh/hyperdb/db.json +55 -3
  156. package/dist-lib/spec/mesh/hyperdb/index.js +119 -3
  157. package/dist-lib/spec/mesh/hyperdb/messages.js +244 -172
  158. package/dist-lib/spec/mesh/hyperdispatch/dispatch.json +7 -1
  159. package/dist-lib/spec/mesh/hyperdispatch/index.js +18 -1
  160. package/dist-lib/spec/mesh/hyperdispatch/messages.js +74 -2
  161. package/dist-lib/spec/mesh/hyperschema/index.js +74 -2
  162. package/dist-lib/spec/mesh/hyperschema/schema.json +27 -1
  163. package/dist-lib/spec/mesh/hyperschema/types.d.ts +9 -1
  164. package/package.json +15 -9
  165. package/tui/app.mjs +376 -151
  166. package/tui/boot.mjs +2 -1
  167. package/tui/lib/busy-words.mjs +2 -1
  168. package/tui/lib/knowledge-command.mjs +11 -10
  169. package/tui/lib/knowledge-import.mjs +7 -5
  170. package/tui/lib/render.mjs +4 -3
  171. package/tui/lib/usage.mjs +2 -1
  172. package/tui/main.mjs +2 -1
  173. package/tui/lib/projection-env.mjs +0 -24
package/tui/app.mjs CHANGED
@@ -53,6 +53,8 @@ import {
53
53
  sidebarRows
54
54
  } from './lib/sidebar.mjs'
55
55
  import { UPLOAD_FRAME_BYTES, writeFrame } from './lib/upload-frames.mjs'
56
+ import { decodeMeshInvite } from '../dist-lib/lib/core/invite.js'
57
+ import b4a from 'b4a'
56
58
 
57
59
  const { batch, quit, key, textinput, tick, viewport, spinner, style } = tui
58
60
 
@@ -1067,21 +1069,21 @@ const COMPUTE_INVITE_DISCLOSURES = [
1067
1069
  // `/mesh use <n>` takes the same index.
1068
1070
  // `shared` is occupancy, not the registry marker: what the user wants to know is which of these
1069
1071
  // meshes has somebody else in it.
1070
- function formatMeshes(meshes) {
1072
+ function formatMeshes(meshes, current) {
1071
1073
  if (!meshes.length) return 'no meshes yet - this device is still opening its own'
1072
1074
  const rows = meshes.map((mesh, index) => {
1073
1075
  const tags = [
1074
- mesh.home ? 'account' : null,
1076
+ mesh.account ? 'account' : null,
1075
1077
  mesh.compute ? 'compute' : null,
1076
- !mesh.home && !mesh.compute && mesh.members > 1 ? 'shared' : null,
1078
+ !mesh.account && !mesh.compute && mesh.members > 1 ? 'shared' : null,
1077
1079
  mesh.open ? 'open' : 'closed'
1078
1080
  ]
1079
1081
  if (mesh.open) tags.push(mesh.writable ? 'writable' : 'read-only')
1080
- const marker = mesh.active ? '* ' : ' '
1082
+ const marker = mesh.meshId === current ? '* ' : ' '
1081
1083
  const name = mesh.label ? `${mesh.meshId.slice(0, 8)} "${mesh.label}"` : mesh.meshId.slice(0, 8)
1082
1084
  return `${marker}${index + 1}. ${name} · ${tags.filter(Boolean).join(' · ')}`
1083
1085
  })
1084
- return [...rows, '* = active · /mesh use <n|id> switches'].join('\n')
1086
+ return [...rows, '* = this window · /mesh use <n|id> switches'].join('\n')
1085
1087
  }
1086
1088
 
1087
1089
  // Same selector shape as /knowledge: a list number, a full id, or a unique prefix.
@@ -1110,8 +1112,8 @@ const ownDefault = (agents, deviceId) => agents.find((agent) => isOwnDefault(age
1110
1112
  // (agentsWatch fires on every change), no polling. This device mints one as a fallback if none
1111
1113
  // shows within the timeout: an unbounded wait here blocks the composer for good, and a mesh can
1112
1114
  // legitimately hold no agent - one nobody has reached yet, or one whose every agent was deleted.
1113
- async function firstAgent(engine, deviceId, modelName, remembered) {
1114
- const watch = engine.agentsWatch({})[Symbol.asyncIterator]()
1115
+ async function firstAgent(engine, meshId, deviceId, modelName, remembered) {
1116
+ const watch = engine.agentsWatch({ meshId })[Symbol.asyncIterator]()
1115
1117
  let timer
1116
1118
  const timeout = new Promise((resolve) => {
1117
1119
  timer = setTimeout(resolve, SEED_REPLICATION_MS, { done: true })
@@ -1136,19 +1138,22 @@ async function firstAgent(engine, deviceId, modelName, remembered) {
1136
1138
  // seeds a per-member default of its own and counts only defaults. Without it these two
1137
1139
  // seeders race the same gap with different bounds and the user ends up with two QV.ACs.
1138
1140
  return engine.createAgent({
1139
- name: 'QV.AC',
1140
- bio: 'You are a helpful local assistant. Be clear, practical, and concise.',
1141
- providerDeviceId: deviceId,
1142
- modelName: modelName || (await engine.deviceInfo({})).recommendedModelName,
1143
- isDefault: true
1141
+ meshId,
1142
+ config: {
1143
+ name: 'QV.AC',
1144
+ bio: 'You are a helpful local assistant. Be clear, practical, and concise.',
1145
+ providerDeviceId: deviceId,
1146
+ modelName: modelName || (await engine.deviceInfo({})).recommendedModelName,
1147
+ isDefault: true
1148
+ }
1144
1149
  })
1145
1150
  }
1146
1151
 
1147
1152
  // The birth op seeds a default chat too; a joiner waits for it to replicate -
1148
1153
  // watch-driven like firstAgent (chatsWatch), no polling. The provider mints one
1149
1154
  // as a fallback if none shows within the timeout.
1150
- async function firstChat(engine, agent, isProvider, remembered) {
1151
- const watch = engine.chatsWatch({})[Symbol.asyncIterator]()
1155
+ async function firstChat(engine, meshId, agent, isProvider, remembered) {
1156
+ const watch = engine.chatsWatch({ meshId })[Symbol.asyncIterator]()
1152
1157
  let timer
1153
1158
  const timeout = new Promise((resolve) => {
1154
1159
  timer = setTimeout(resolve, SEED_REPLICATION_MS, { done: true })
@@ -1165,24 +1170,36 @@ async function firstChat(engine, agent, isProvider, remembered) {
1165
1170
  clearTimeout(timer)
1166
1171
  await watch.return?.()
1167
1172
  }
1168
- if (isProvider) return engine.createChat({ agentId: agent.id, title: 'New Chat' })
1173
+ if (isProvider) {
1174
+ return engine.createChat({ meshId, agentId: agent.id, config: { title: 'New Chat' } })
1175
+ }
1169
1176
  throw new Error('no chat replicated before timeout')
1170
1177
  }
1171
1178
 
1172
- // A joiner's own writes need writer admission first; the replicated mesh status
1173
- // carries `writable`, so wait for the frame that flips it (a creator is writable
1174
- // as soon as its genesis drains, so this returns on the first frame).
1175
- async function firstWritable(engine) {
1176
- for await (const frame of engine.meshStatusWatch({})) {
1177
- if (frame.writable) return
1179
+ // the account, where a window starts; a kicked device has none until Core adopts or mints the next
1180
+ async function accountMeshId(engine) {
1181
+ for await (const account of engine.accountWatch({})) {
1182
+ if (account.meshId) return account.meshId
1183
+ }
1184
+ throw new Error('account stream ended before this device held an account')
1185
+ }
1186
+
1187
+ // A joiner's own writes need writer admission first; writability is per mesh, so wait for the
1188
+ // mesh list frame that flips it (a creator is writable as soon as its genesis drains, so this
1189
+ // returns on the first frame).
1190
+ async function firstWritable(engine, meshId) {
1191
+ for await (const frame of engine.meshesWatch({})) {
1192
+ const mesh = (frame.meshes ?? []).find((entry) => entry.meshId === meshId)
1193
+ if (mesh?.writable) return
1178
1194
  }
1179
- throw new Error('mesh status stream ended before this device became writable')
1195
+ throw new Error('mesh list stream ended before this device became writable')
1180
1196
  }
1181
1197
 
1182
1198
  export class ChatApp {
1183
1199
  constructor({
1184
1200
  engine = null,
1185
1201
  connect = null,
1202
+ meshId = null,
1186
1203
  agent = null,
1187
1204
  chatId = null,
1188
1205
  modelName = null,
@@ -1196,6 +1213,9 @@ export class ChatApp {
1196
1213
  skills
1197
1214
  }) {
1198
1215
  this.engine = engine
1216
+ // The mesh this window is looking at. Core no longer holds a selection, so the choice is the
1217
+ // client's: it starts on the account and `/mesh use` moves it. Every engine call names it.
1218
+ this.meshId = meshId || null
1199
1219
  this._skills = skills || null
1200
1220
  this.agent = agent
1201
1221
  this.chatId = chatId
@@ -1253,10 +1273,11 @@ export class ChatApp {
1253
1273
  this.modelState = null // last 'model' event from the harness (loading/downloading/ready/unloading)
1254
1274
  this.status = ''
1255
1275
  this.notice = null // last /command output, rendered as a trailing transcript block
1256
- this.gen = 0 // shared stale-guard for the status/devices/diagnostics watches (never bumped today)
1276
+ this.gen = 0 // shared stale-guard for the status/diagnostics watches (never bumped today)
1277
+ this._meshGen = 0 // bumped on every mesh move, so a frame from the mesh left behind is dropped
1257
1278
  // chunk-watch-only generation: a chat switch tears down the chunk stream and re-arms it on the
1258
1279
  // new chatId, so a stale frame from the old chat must be dropped. Separate from `gen` so it never
1259
- // stalls the status/devices/diagnostics loops, which share `gen` and re-arm on every frame.
1280
+ // stalls the status/diagnostics loops, which share `gen` and re-arm on every frame.
1260
1281
  this._chunkGen = 0
1261
1282
  this._chunkIterator = null
1262
1283
  this._files = []
@@ -1293,6 +1314,8 @@ export class ChatApp {
1293
1314
  this._groups = []
1294
1315
  this._chatsIterator = null
1295
1316
  this._ownDefaultIterator = null
1317
+ this._meshesIterator = null
1318
+ this._meshIds = null // the ids the last meshesWatch frame listed, to notice this window's going
1296
1319
  this._turns = [] // last rendered turns — re-combined with the busy line on every render
1297
1320
  // Derived from _turns on every _setTranscript, not bridged in from the
1298
1321
  // harness — approval state lives entirely in the chunk stream (see
@@ -1325,20 +1348,33 @@ export class ChatApp {
1325
1348
  return batch(...this._engineWatches(), this.spin.init())
1326
1349
  }
1327
1350
 
1328
- // The engine-backed watch loops. The chunk watch is deferred until a chatId
1329
- // exists (see _bootstrap); the mesh/devices/diagnostics watches run from the
1330
- // first frame so the header narrates live progress while the mesh converges.
1351
+ // device-wide watches run from the first frame so the header narrates boot; mesh ones wait for a mesh
1331
1352
  _engineWatches() {
1332
1353
  return [
1333
- this.chatId ? this._watchNext() : this._bootstrap(),
1334
- this.chatId ? this._watchNextFiles() : null,
1335
1354
  this._watchNextStatus(),
1336
- this._watchNextDevices(),
1337
1355
  this._watchNextDiagnostics(),
1338
- this._watchNextChats()
1356
+ this._watchNextMeshes(),
1357
+ this._enterMesh()
1339
1358
  ].filter(Boolean)
1340
1359
  }
1341
1360
 
1361
+ // every mesh-scoped route needs a meshId, so nothing here arms before the window has one
1362
+ _enterMesh() {
1363
+ if (!this.meshId) return this._resolveAccount()
1364
+ const chat = this.chatId ? [this._watchNext(), this._watchNextFiles()] : [this._bootstrap()]
1365
+ return batch(this._watchNextDevices(), this._watchNextChats(), ...chat)
1366
+ }
1367
+
1368
+ _resolveAccount() {
1369
+ return async () => {
1370
+ try {
1371
+ return { type: 'mesh.account', meshId: await accountMeshId(this.engine) }
1372
+ } catch (error) {
1373
+ return { type: 'boot-error', error }
1374
+ }
1375
+ }
1376
+ }
1377
+
1342
1378
  // init()'s first command when connecting: bring the engine up inside the TUI
1343
1379
  // and hand the results to the 'connected' message.
1344
1380
  _connectCmd() {
@@ -1358,11 +1394,12 @@ export class ChatApp {
1358
1394
  _bootstrap() {
1359
1395
  return async () => {
1360
1396
  try {
1361
- await firstWritable(this.engine)
1397
+ await firstWritable(this.engine, this.meshId)
1362
1398
  // the pick the last session persisted; null on a fake engine that has no config
1363
1399
  const config = this.engine.getConfig ? await this.engine.getConfig({}) : null
1364
1400
  let agent = await firstAgent(
1365
1401
  this.engine,
1402
+ this.meshId,
1366
1403
  this.originDeviceId,
1367
1404
  this._modelName,
1368
1405
  config?.activeAgentId
@@ -1370,16 +1407,28 @@ export class ChatApp {
1370
1407
  const isProvider = agent.providerDeviceId?.equals(this.originDeviceId) ?? false
1371
1408
  if (isProvider && this._modelName) {
1372
1409
  // Only set the model — scopes stay as the shared seed left them
1373
- agent = await this.engine.updateAgent({ id: agent.id, modelName: this._modelName })
1410
+ agent = await this.engine.updateAgent({
1411
+ meshId: this.meshId,
1412
+ agentId: agent.id,
1413
+ config: { modelName: this._modelName }
1414
+ })
1374
1415
  }
1375
- const chat = await firstChat(this.engine, agent, isProvider, config?.activeChatId)
1416
+ const chat = await firstChat(
1417
+ this.engine,
1418
+ this.meshId,
1419
+ agent,
1420
+ isProvider,
1421
+ config?.activeChatId
1422
+ )
1376
1423
  const agentRemembered = agent.id === config?.activeAgentId
1377
1424
  const chatRemembered = chat.id === config?.activeChatId
1378
1425
  // a remembered agent drives whichever chat it was left on (/agent use keeps the chat);
1379
1426
  // without one, the resumed chat runs under its own agent, as any switch does (_agentFor)
1380
1427
  if (chatRemembered && !agentRemembered && chat.agentId !== agent.id) {
1381
1428
  // getAgent throws for a deleted agent; the seed drives the chat then, as _agentFor does
1382
- agent = await this.engine.getAgent({ id: chat.agentId }).catch(() => agent)
1429
+ agent = await this.engine
1430
+ .getAgent({ meshId: this.meshId, agentId: chat.agentId })
1431
+ .catch(() => agent)
1383
1432
  }
1384
1433
  return { type: 'booted', agent, chat, remembered: agentRemembered || chatRemembered }
1385
1434
  } catch (error) {
@@ -1404,7 +1453,9 @@ export class ChatApp {
1404
1453
 
1405
1454
  _iterator() {
1406
1455
  if (!this._chunkIterator) {
1407
- this._chunkIterator = this.engine.chunksWatch({ chatId: this.chatId })[Symbol.asyncIterator]()
1456
+ this._chunkIterator = this.engine
1457
+ .chunksWatch({ meshId: this.meshId, chatId: this.chatId })
1458
+ [Symbol.asyncIterator]()
1408
1459
  }
1409
1460
  return this._chunkIterator
1410
1461
  }
@@ -1415,7 +1466,7 @@ export class ChatApp {
1415
1466
  const gen = this._chunkGen
1416
1467
  if (!this._filesIterator) {
1417
1468
  this._filesIterator = this.engine
1418
- .fileStatusWatch({ chatId: this.chatId })
1469
+ .fileStatusWatch({ meshId: this.meshId, chatId: this.chatId })
1419
1470
  [Symbol.asyncIterator]()
1420
1471
  }
1421
1472
  const it = this._filesIterator
@@ -1446,9 +1497,9 @@ export class ChatApp {
1446
1497
  // other watches, so a chat created or moved on any device redraws the pane.
1447
1498
  _watchNextChats() {
1448
1499
  if (!this.engine.chatsWatch) return null
1449
- const gen = this.gen
1500
+ const gen = this._meshGen
1450
1501
  if (!this._chatsIterator) {
1451
- this._chatsIterator = this.engine.chatsWatch({})[Symbol.asyncIterator]()
1502
+ this._chatsIterator = this.engine.chatsWatch({ meshId: this.meshId })[Symbol.asyncIterator]()
1452
1503
  }
1453
1504
  const it = this._chatsIterator
1454
1505
  return async () => {
@@ -1461,9 +1512,9 @@ export class ChatApp {
1461
1512
  // a joiner boots onto whatever agent the room holds; its own default is seeded after the join
1462
1513
  _watchOwnDefault() {
1463
1514
  if (!this.engine.agentsWatch || isOwnDefault(this.agent, this.originDeviceId)) return null
1464
- const gen = this.gen
1515
+ const gen = this._meshGen
1465
1516
  const booted = this.agent?.id
1466
- const it = this.engine.agentsWatch({})[Symbol.asyncIterator]()
1517
+ const it = this.engine.agentsWatch({ meshId: this.meshId })[Symbol.asyncIterator]()
1467
1518
  this._ownDefaultIterator = it
1468
1519
  return async () => {
1469
1520
  while (true) {
@@ -1482,10 +1533,10 @@ export class ChatApp {
1482
1533
  // shape as the other watch loops. Null when the engine lacks the
1483
1534
  // capability (e.g. a headless test fake).
1484
1535
  _refreshMembersCmd() {
1485
- const gen = this.gen
1536
+ const gen = this._meshGen
1486
1537
  return async () => {
1487
1538
  try {
1488
- const res = await this.engine.listMembers({})
1539
+ const res = await this.engine.listMembers({ meshId: this.meshId })
1489
1540
  return { type: 'members.frame', gen, members: res.members ?? [] }
1490
1541
  } catch {
1491
1542
  return { type: 'members.frame', gen, members: [] }
@@ -1505,9 +1556,11 @@ export class ChatApp {
1505
1556
 
1506
1557
  _watchNextDevices() {
1507
1558
  if (!this.engine.devicesWatch) return null
1508
- const gen = this.gen
1559
+ const gen = this._meshGen
1509
1560
  if (!this._devicesIterator) {
1510
- this._devicesIterator = this.engine.devicesWatch({})[Symbol.asyncIterator]()
1561
+ this._devicesIterator = this.engine
1562
+ .devicesWatch({ meshId: this.meshId })
1563
+ [Symbol.asyncIterator]()
1511
1564
  }
1512
1565
  const it = this._devicesIterator
1513
1566
  return async () => {
@@ -1517,6 +1570,20 @@ export class ChatApp {
1517
1570
  }
1518
1571
  }
1519
1572
 
1573
+ // the window's mesh can go without the window doing anything: a kick retires the account
1574
+ _watchNextMeshes() {
1575
+ if (!this.engine.meshesWatch) return null
1576
+ if (!this._meshesIterator) {
1577
+ this._meshesIterator = this.engine.meshesWatch({})[Symbol.asyncIterator]()
1578
+ }
1579
+ const it = this._meshesIterator
1580
+ return async () => {
1581
+ const { value, done } = await it.next()
1582
+ if (done) return { type: 'meshes.done' }
1583
+ return { type: 'meshes', meshes: value.meshes ?? [] }
1584
+ }
1585
+ }
1586
+
1520
1587
  // The mesh-status counterpart to _watchNext — same re-arm/stale-guard
1521
1588
  // shape, its own iterator (meshStatusWatch frames arrive independently of
1522
1589
  // chunk frames).
@@ -1577,7 +1644,7 @@ export class ChatApp {
1577
1644
  const { text, on } = busyStatus(this.modelState, runTurn, Date.now() - this._busySince)
1578
1645
  const where =
1579
1646
  on === 'local'
1580
- ? this._deviceName(this.originDeviceId?.toString('hex'))
1647
+ ? this._deviceName(this.originDeviceId && b4a.toHex(this.originDeviceId))
1581
1648
  : on === 'host'
1582
1649
  ? this._deviceName(runTurn?.statusDeviceId)
1583
1650
  : null
@@ -1776,9 +1843,13 @@ export class ChatApp {
1776
1843
  if (rawArgs.trim()) return notice('usage: /compact')
1777
1844
  if (this.busy) return notice('a run is in flight — /compact once it has finished')
1778
1845
  return run(async () => {
1779
- const result = await engine.compactChat({ id: this.chatId })
1846
+ const result = await engine.compactChat({ meshId: this.meshId, chatId: this.chatId })
1780
1847
  if (!result.compacted) return `not compacted: ${result.reason ?? 'unknown reason'}`
1781
- const { chunks } = await engine.listChunks({ chatId: this.chatId, type: 'compaction' })
1848
+ const { chunks } = await engine.listChunks({
1849
+ meshId: this.meshId,
1850
+ chatId: this.chatId,
1851
+ type: 'compaction'
1852
+ })
1782
1853
  const summary = chunks?.at(-1)?.compaction?.summary ?? ''
1783
1854
  return `compacted ${result.foldedTurns} turn(s) into:\n${summary}`
1784
1855
  })
@@ -1822,7 +1893,7 @@ export class ChatApp {
1822
1893
  'usage: /image [model <sd2|sdxl|flux2-klein> | steps <1..100> | size <WxH> | reset]'
1823
1894
  if (!field) {
1824
1895
  return run(async () => {
1825
- const a = await engine.getAgent({ id: agent.id })
1896
+ const a = await engine.getAgent({ meshId: this.meshId, agentId: agent.id })
1826
1897
  const size =
1827
1898
  a.imageWidth || a.imageHeight
1828
1899
  ? `${a.imageWidth || 512}x${a.imageHeight || 512}`
@@ -1838,7 +1909,11 @@ export class ChatApp {
1838
1909
  if (field === 'model') {
1839
1910
  if (!['sd2', 'sdxl', 'flux2-klein'].includes(value)) return notice(USAGE)
1840
1911
  return run(async () => {
1841
- await engine.updateAgent({ id: agent.id, imageModelChoice: value })
1912
+ await engine.updateAgent({
1913
+ meshId: this.meshId,
1914
+ agentId: agent.id,
1915
+ config: { imageModelChoice: value }
1916
+ })
1842
1917
  return `image model set to ${value}`
1843
1918
  })
1844
1919
  }
@@ -1846,13 +1921,21 @@ export class ChatApp {
1846
1921
  const steps = Number(value)
1847
1922
  if (!Number.isInteger(steps) || steps < 1 || steps > 100) return notice(USAGE)
1848
1923
  return run(async () => {
1849
- await engine.updateAgent({ id: agent.id, imageSteps: steps })
1924
+ await engine.updateAgent({
1925
+ meshId: this.meshId,
1926
+ agentId: agent.id,
1927
+ config: { imageSteps: steps }
1928
+ })
1850
1929
  return `image steps set to ${steps}`
1851
1930
  })
1852
1931
  }
1853
1932
  if (field === 'reset') {
1854
1933
  return run(async () => {
1855
- await engine.updateAgent({ id: agent.id, clearImageSettings: true })
1934
+ await engine.updateAgent({
1935
+ meshId: this.meshId,
1936
+ agentId: agent.id,
1937
+ config: { clearImageSettings: true }
1938
+ })
1856
1939
  return 'image defaults reset (device default model, model-default steps, 512x512)'
1857
1940
  })
1858
1941
  }
@@ -1865,7 +1948,11 @@ export class ChatApp {
1865
1948
  const width = settingsDimension(Number(match[1]))
1866
1949
  const height = settingsDimension(Number(match[2]))
1867
1950
  if (!width || !height) return USAGE
1868
- await engine.updateAgent({ id: agent.id, imageWidth: width, imageHeight: height })
1951
+ await engine.updateAgent({
1952
+ meshId: this.meshId,
1953
+ agentId: agent.id,
1954
+ config: { imageWidth: width, imageHeight: height }
1955
+ })
1869
1956
  return `image size set to ${width}x${height}`
1870
1957
  })
1871
1958
  }
@@ -1877,16 +1964,16 @@ export class ChatApp {
1877
1964
  const arg = nameParts.join(' ')
1878
1965
  if (!action) {
1879
1966
  return run(async () => {
1880
- const a = await engine.getAgent({ id: agent.id })
1967
+ const a = await engine.getAgent({ meshId: this.meshId, agentId: agent.id })
1881
1968
  const lender = a.lenderDeviceId
1882
- ? ` · model borrowed from ${a.lenderDeviceId.toString('hex').slice(0, 8)}`
1969
+ ? ` · model borrowed from ${b4a.toHex(a.lenderDeviceId).slice(0, 8)}`
1883
1970
  : ''
1884
1971
  return `agent ${a.name} (${a.id.slice(0, 8)}) · skills=${a.skillsScope ?? 'all'} tools=${a.toolsScope ?? 'all'}${lender}`
1885
1972
  })
1886
1973
  }
1887
1974
  if (action === 'list') {
1888
1975
  return run(async () => {
1889
- const { agents } = await engine.listAgents({})
1976
+ const { agents } = await engine.listAgents({ meshId: this.meshId })
1890
1977
  return agents
1891
1978
  .map((a) => `${a.id === agent.id ? '*' : ' '}${a.name} (${a.id.slice(0, 8)})`)
1892
1979
  .join('\n')
@@ -1896,10 +1983,13 @@ export class ChatApp {
1896
1983
  if (!arg) return notice('usage: /agent new <name>')
1897
1984
  return run(async () => {
1898
1985
  const created = await engine.createAgent({
1899
- name: arg,
1900
- bio: `${arg} — test agent`,
1901
- providerDeviceId: this.originDeviceId,
1902
- modelName: agent.modelName
1986
+ meshId: this.meshId,
1987
+ config: {
1988
+ name: arg,
1989
+ bio: `${arg} — test agent`,
1990
+ providerDeviceId: this.originDeviceId,
1991
+ modelName: agent.modelName
1992
+ }
1903
1993
  })
1904
1994
  this.agent = created
1905
1995
  await this._persistSelection()
@@ -1909,14 +1999,22 @@ export class ChatApp {
1909
1999
  if (action === 'rename') {
1910
2000
  if (!arg) return notice('usage: /agent rename <name>')
1911
2001
  return run(async () => {
1912
- this.agent = await engine.updateAgent({ id: agent.id, name: arg })
2002
+ this.agent = await engine.updateAgent({
2003
+ meshId: this.meshId,
2004
+ agentId: agent.id,
2005
+ config: { name: arg }
2006
+ })
1913
2007
  return `renamed to ${this.agent.name} (${this.agent.id.slice(0, 8)})`
1914
2008
  })
1915
2009
  }
1916
2010
  if (action === 'borrow') {
1917
2011
  return run(async () => {
1918
2012
  if (arg === 'none') {
1919
- this.agent = await engine.updateAgent({ id: agent.id, clearLenderDeviceId: true })
2013
+ this.agent = await engine.updateAgent({
2014
+ meshId: this.meshId,
2015
+ agentId: agent.id,
2016
+ config: { clearLenderDeviceId: true }
2017
+ })
1920
2018
  return `${this.agent.name} answers on this device again`
1921
2019
  }
1922
2020
  if (arg) return 'usage: /agent borrow · /agent borrow none'
@@ -1924,14 +2022,18 @@ export class ChatApp {
1924
2022
  if (!computeLenderId) {
1925
2023
  return 'no single device to borrow from - /mesh new compute lends one, and two lenders is no choice'
1926
2024
  }
1927
- this.agent = await engine.updateAgent({ id: agent.id, lenderDeviceId: computeLenderId })
1928
- return `${this.agent.name} borrows its model from ${computeLenderId.toString('hex').slice(0, 8)}`
2025
+ this.agent = await engine.updateAgent({
2026
+ meshId: this.meshId,
2027
+ agentId: agent.id,
2028
+ config: { lenderDeviceId: computeLenderId }
2029
+ })
2030
+ return `${this.agent.name} borrows its model from ${b4a.toHex(computeLenderId).slice(0, 8)}`
1929
2031
  })
1930
2032
  }
1931
2033
  if (action === 'use') {
1932
2034
  if (!arg) return notice('usage: /agent use <name|id>')
1933
2035
  return run(async () => {
1934
- const { agents } = await engine.listAgents({})
2036
+ const { agents } = await engine.listAgents({ meshId: this.meshId })
1935
2037
  const found = agents.find((a) => a.id === arg || a.id.startsWith(arg) || a.name === arg)
1936
2038
  if (!found) return `no agent matching: ${arg}`
1937
2039
  this.agent = found
@@ -1944,7 +2046,11 @@ export class ChatApp {
1944
2046
 
1945
2047
  if (cmd === 'activity') {
1946
2048
  return run(async () => {
1947
- const { activities } = await engine.listToolActivity({ agentId: agent.id, limit: 30 })
2049
+ const { activities } = await engine.listToolActivity({
2050
+ meshId: this.meshId,
2051
+ agentId: agent.id,
2052
+ limit: 30
2053
+ })
1948
2054
  if (!activities || activities.length === 0) {
1949
2055
  return 'no tool activity yet for this agent'
1950
2056
  }
@@ -1971,14 +2077,14 @@ export class ChatApp {
1971
2077
  const field = cmd === 'skill' ? 'enabledSkills' : 'enabledTools'
1972
2078
  const scopeField = cmd === 'skill' ? 'skillsScope' : 'toolsScope'
1973
2079
  return run(async () => {
1974
- const fresh = await engine.getAgent({ id: agent.id })
2080
+ const fresh = await engine.getAgent({ meshId: this.meshId, agentId: agent.id })
1975
2081
  const set = new Set(fresh[field] ?? [])
1976
2082
  if (action === 'on') set.add(name)
1977
2083
  else set.delete(name)
1978
2084
  const updated = await engine.updateAgent({
1979
- id: agent.id,
1980
- [field]: [...set],
1981
- [scopeField]: 'selected'
2085
+ meshId: this.meshId,
2086
+ agentId: agent.id,
2087
+ config: { [field]: [...set], [scopeField]: 'selected' }
1982
2088
  })
1983
2089
  this.agent = updated
1984
2090
  const line = `${cmd} ${name} ${action} · ${field}=[${[...set].join(', ')}] scope=selected`
@@ -1996,7 +2102,11 @@ export class ChatApp {
1996
2102
  }
1997
2103
  const scopeField = which === 'skills' ? 'skillsScope' : 'toolsScope'
1998
2104
  return run(async () => {
1999
- const updated = await engine.updateAgent({ id: agent.id, [scopeField]: value })
2105
+ const updated = await engine.updateAgent({
2106
+ meshId: this.meshId,
2107
+ agentId: agent.id,
2108
+ config: { [scopeField]: value }
2109
+ })
2000
2110
  this.agent = updated
2001
2111
  return `${which} scope=${value}`
2002
2112
  })
@@ -2033,7 +2143,9 @@ export class ChatApp {
2033
2143
  return notice('usage: /export [n] — the last n runs (default 1)')
2034
2144
  }
2035
2145
  return run(async () => {
2036
- const chat = engine.getChat ? await engine.getChat({ id: this.chatId }) : null
2146
+ const chat = engine.getChat
2147
+ ? await engine.getChat({ meshId: this.meshId, chatId: this.chatId })
2148
+ : null
2037
2149
  const markdown = exportMarkdown(this._turns, runs, {
2038
2150
  title: chat?.title ?? 'Chat',
2039
2151
  chatId: this.chatId,
@@ -2059,7 +2171,11 @@ export class ChatApp {
2059
2171
  if (cmd === 'save') {
2060
2172
  // blobs are encrypted at rest — the only viewable copy is a fresh download
2061
2173
  return run(async () => {
2062
- const { chunks } = await engine.listChunks({ chatId: this.chatId, type: 'attachment' })
2174
+ const { chunks } = await engine.listChunks({
2175
+ meshId: this.meshId,
2176
+ chatId: this.chatId,
2177
+ type: 'attachment'
2178
+ })
2063
2179
  const all = chunks ?? []
2064
2180
  if (!all.length) return 'no attachments in this chat'
2065
2181
  const picked = rest[0] ? all[Number(rest[0]) - 1] : all[all.length - 1]
@@ -2068,7 +2184,10 @@ export class ChatApp {
2068
2184
  if (!att) return `attachment chunk ${picked.id} has no attachment payload`
2069
2185
  if (att.deletedAt) return `${att.fileName} was deleted`
2070
2186
  const pieces = []
2071
- for await (const frame of engine.downloadAttachment({ blobId: att.blobId })) {
2187
+ for await (const frame of engine.downloadAttachment({
2188
+ meshId: this.meshId,
2189
+ blobId: att.blobId
2190
+ })) {
2072
2191
  if (frame.data) pieces.push(frame.data)
2073
2192
  }
2074
2193
  const bytes = Buffer.concat(pieces)
@@ -2088,7 +2207,12 @@ export class ChatApp {
2088
2207
  if (cmd === 'knowledge') {
2089
2208
  return [
2090
2209
  this,
2091
- () => knowledgeCommand(engine, { chatId: this.chatId, saveDir: this._saveDir }, rawArgs)
2210
+ () =>
2211
+ knowledgeCommand(
2212
+ engine,
2213
+ { chatId: this.chatId, meshId: this.meshId, saveDir: this._saveDir },
2214
+ rawArgs
2215
+ )
2092
2216
  ]
2093
2217
  }
2094
2218
 
@@ -2200,7 +2324,7 @@ export class ChatApp {
2200
2324
  return run(async () => {
2201
2325
  let skills
2202
2326
  try {
2203
- skills = this._skills ? await this._skills(agent.id, agent.modelName) : []
2327
+ skills = this._skills ? await this._skills(agent.id, agent.modelName, this.meshId) : []
2204
2328
  } catch (error) {
2205
2329
  return `could not read the skill catalog: ${error?.message ?? error}`
2206
2330
  }
@@ -2305,11 +2429,7 @@ export class ChatApp {
2305
2429
  })
2306
2430
  }
2307
2431
 
2308
- // Moving mesh is a Core-side transition: it retires this device's mesh and
2309
- // admits it to the invited one, so every agent and chat the TUI is holding
2310
- // becomes stale. Block sending for its duration and re-resolve both from
2311
- // the joined mesh afterwards (see the 'mesh.joined' handler). A join parks
2312
- // until the inviting device admits it — /join cancel gives that a way out.
2432
+ // sending blocks for the join, since everything held goes stale once the window lands on the joined mesh
2313
2433
  if (cmd === 'join') {
2314
2434
  const arg = rawArgs.trim()
2315
2435
  if (!arg) return notice('usage: /join <qvac://mesh/…> · /join cancel')
@@ -2329,8 +2449,11 @@ export class ChatApp {
2329
2449
  async () => {
2330
2450
  try {
2331
2451
  await engine.joinMesh({ invite })
2332
- const next = await engine.meshInvite({}).catch(noop)
2333
- return { type: 'mesh.joined', invite: next?.invite ?? null }
2452
+ const joined = decodeMeshInvite(invite)
2453
+ const meshId = b4a.toHex(joined.baseKey)
2454
+ if (joined.compute) return { type: 'mesh.joined', compute: meshId }
2455
+ const next = await engine.meshInvite({ meshId }).catch(noop)
2456
+ return { type: 'mesh.joined', meshId, invite: next?.invite ?? null }
2334
2457
  } catch (error) {
2335
2458
  return { type: 'mesh.joined', error }
2336
2459
  }
@@ -2349,7 +2472,7 @@ export class ChatApp {
2349
2472
  this,
2350
2473
  async () => {
2351
2474
  try {
2352
- await engine.leaveMesh({})
2475
+ await engine.leaveMesh({ meshId: this.meshId })
2353
2476
  const next = await engine.meshInvite({}).catch(noop)
2354
2477
  return { type: 'mesh.left', invite: next?.invite ?? null }
2355
2478
  } catch (error) {
@@ -2393,18 +2516,18 @@ export class ChatApp {
2393
2516
  if (cmd === 'members') {
2394
2517
  return run(async () => {
2395
2518
  const [membersRes, devicesRes] = await Promise.all([
2396
- engine.listMembers({}),
2397
- engine.listDevices({})
2519
+ engine.listMembers({ meshId: this.meshId }),
2520
+ engine.listDevices({ meshId: this.meshId })
2398
2521
  ])
2399
2522
  const members = membersRes.members ?? []
2400
2523
  const devices = devicesRes.devices ?? []
2401
2524
  if (!members.length) return 'no members yet — the mesh is still settling'
2402
2525
  const lines = []
2403
2526
  for (const m of members) {
2404
- const hex = m.id.toString('hex')
2527
+ const hex = b4a.toHex(m.id)
2405
2528
  lines.push(`${m.name} (${hex.slice(0, 8)})${m.removed ? ' (removed)' : ''}`)
2406
2529
  for (const d of devices) {
2407
- if (d.memberId?.toString('hex') !== hex) continue
2530
+ if (!d.memberId || b4a.toHex(d.memberId) !== hex) continue
2408
2531
  lines.push(` · ${d.name}${d.revoked ? ' (revoked)' : ''}`)
2409
2532
  }
2410
2533
  }
@@ -2420,7 +2543,7 @@ export class ChatApp {
2420
2543
  if (cmd === 'meshes') {
2421
2544
  return run(async () => {
2422
2545
  const { meshes } = await engine.listMeshes({})
2423
- return formatMeshes(meshes ?? [])
2546
+ return formatMeshes(meshes ?? [], this.meshId)
2424
2547
  })
2425
2548
  }
2426
2549
 
@@ -2433,7 +2556,7 @@ export class ChatApp {
2433
2556
  if (action === 'new') {
2434
2557
  const compute = target === 'compute'
2435
2558
  return run(async () => {
2436
- const { meshId } = await engine.createRoom({ compute })
2559
+ const { meshId } = await engine.createRoom({ config: { compute } })
2437
2560
  const invite = '/invite member <n|id> invites someone into it'
2438
2561
  return `${await this._roomHeading(meshId)}\n${invite}`
2439
2562
  })
@@ -2463,7 +2586,7 @@ export class ChatApp {
2463
2586
  const arg = argParts.join(' ')
2464
2587
  if (!action) {
2465
2588
  return run(async () => {
2466
- const c = await engine.getChat({ id: this.chatId })
2589
+ const c = await engine.getChat({ meshId: this.meshId, chatId: this.chatId })
2467
2590
  return `chat "${c.title}" (${c.id.slice(0, 8)}) · web=${c.webSearchEnabled ? 'on' : 'off'}`
2468
2591
  })
2469
2592
  }
@@ -2479,7 +2602,11 @@ export class ChatApp {
2479
2602
  if (action === 'rename') {
2480
2603
  if (!arg) return notice('usage: /chat rename <title>')
2481
2604
  return run(async () => {
2482
- const c = await engine.renameChat({ id: this.chatId, title: arg })
2605
+ const c = await engine.renameChat({
2606
+ meshId: this.meshId,
2607
+ chatId: this.chatId,
2608
+ config: { title: arg }
2609
+ })
2483
2610
  return `renamed to "${c.title}"`
2484
2611
  })
2485
2612
  }
@@ -2488,8 +2615,8 @@ export class ChatApp {
2488
2615
  if (state !== 'on' && state !== 'off') return notice(`usage: /chat ${action} on|off`)
2489
2616
  const enabled = state === 'on'
2490
2617
  return run(async () => {
2491
- if (action === 'rag') await engine.setChatRagEnabled({ id: this.chatId, enabled })
2492
- else await engine.setChatWebSearchEnabled({ id: this.chatId, enabled })
2618
+ const set = action === 'rag' ? engine.setChatRagEnabled : engine.setChatWebSearchEnabled
2619
+ await set.call(engine, { meshId: this.meshId, chatId: this.chatId, enabled })
2493
2620
  return `${action === 'rag' ? 'RAG' : 'web search'} ${state} for this chat`
2494
2621
  })
2495
2622
  }
@@ -2515,7 +2642,7 @@ export class ChatApp {
2515
2642
  const name = argParts.join(' ')
2516
2643
  if (!name) return notice('usage: /group new <name>')
2517
2644
  return run(async () => {
2518
- const group = await engine.createChatGroup({ name })
2645
+ const group = await engine.createChatGroup({ meshId: this.meshId, config: { name } })
2519
2646
  return `created group "${group.name}" (${group.id.slice(0, 8)})`
2520
2647
  })
2521
2648
  }
@@ -2558,10 +2685,15 @@ export class ChatApp {
2558
2685
  const at = await anchor()
2559
2686
  if (at.miss) return at.miss
2560
2687
  if (anchorNeedle === null) {
2561
- await engine.setChatGroup({ id, groupId })
2688
+ await engine.setChatGroup({ meshId: this.meshId, chatId: id, groupId })
2562
2689
  return groupId ? `moved ${what} to ${into}` : `${what} is ungrouped`
2563
2690
  }
2564
- await engine.moveChat({ id, groupId, afterId: at.afterId })
2691
+ await engine.moveChat({
2692
+ meshId: this.meshId,
2693
+ chatId: id,
2694
+ groupId,
2695
+ afterId: at.afterId
2696
+ })
2565
2697
  return `moved ${what} to ${into}${at.placed}`
2566
2698
  }
2567
2699
  if (groupNeedle === '-') return run(() => place(undefined, 'the ungrouped list'))
@@ -2576,13 +2708,17 @@ export class ChatApp {
2576
2708
  }
2577
2709
  return withGroup(needle, async (group) => {
2578
2710
  if (anchorNeedle === 'first') {
2579
- await engine.moveChatGroup({ id: group.id })
2711
+ await engine.moveChatGroup({ meshId: this.meshId, groupId: group.id })
2580
2712
  return `moved "${group.name}" first`
2581
2713
  }
2582
2714
  const { group: anchor, ambiguous } = await this._resolveGroup(anchorNeedle)
2583
2715
  if (ambiguous) return `"${anchorNeedle}" matches ${ambiguous} groups — be specific`
2584
2716
  if (!anchor) return `no group matching "${anchorNeedle}"`
2585
- await engine.moveChatGroup({ id: group.id, afterId: anchor.id })
2717
+ await engine.moveChatGroup({
2718
+ meshId: this.meshId,
2719
+ groupId: group.id,
2720
+ afterId: anchor.id
2721
+ })
2586
2722
  return `moved "${group.name}" after "${anchor.name}"`
2587
2723
  })
2588
2724
  }
@@ -2596,7 +2732,11 @@ export class ChatApp {
2596
2732
  )
2597
2733
  }
2598
2734
  return withGroup(needle, async (group) => {
2599
- const renamed = await engine.renameChatGroup({ id: group.id, name })
2735
+ const renamed = await engine.renameChatGroup({
2736
+ meshId: this.meshId,
2737
+ groupId: group.id,
2738
+ config: { name }
2739
+ })
2600
2740
  return `renamed "${group.name}" to "${renamed.name}"`
2601
2741
  })
2602
2742
  }
@@ -2604,7 +2744,7 @@ export class ChatApp {
2604
2744
  const needle = argParts.join(' ')
2605
2745
  if (!needle) return notice('usage: /group del <group>')
2606
2746
  return withGroup(needle, async (group) => {
2607
- await engine.deleteChatGroup({ id: group.id })
2747
+ await engine.deleteChatGroup({ meshId: this.meshId, groupId: group.id })
2608
2748
  return `deleted "${group.name}" — its chats are now ungrouped`
2609
2749
  })
2610
2750
  }
@@ -2619,7 +2759,7 @@ export class ChatApp {
2619
2759
  // Exact id wins; otherwise a prefix must be UNIQUE — an ambiguous prefix is reported, never
2620
2760
  // silently resolved to whichever chat sorts first. Returns { chat } | { ambiguous: n } | {}.
2621
2761
  async _resolveChat(needle) {
2622
- const { chats } = await this.engine.listChats({})
2762
+ const { chats } = await this.engine.listChats({ meshId: this.meshId })
2623
2763
  const live = (chats ?? []).filter((c) => !c.deletedAt)
2624
2764
  const lower = needle.toLowerCase()
2625
2765
  // id first so a needle that is a real id can never be shadowed by a chat titled the same
@@ -2636,7 +2776,7 @@ export class ChatApp {
2636
2776
  // exact id, exact name, then a UNIQUE prefix of either — an ambiguous needle is reported,
2637
2777
  // never resolved to whichever group happens to sort first
2638
2778
  async _resolveGroup(needle) {
2639
- const { groups } = await this.engine.listChatGroups({})
2779
+ const { groups } = await this.engine.listChatGroups({ meshId: this.meshId })
2640
2780
  const live = groups ?? []
2641
2781
  const lower = needle.toLowerCase()
2642
2782
  const exact =
@@ -2656,7 +2796,7 @@ export class ChatApp {
2656
2796
  this,
2657
2797
  async () => {
2658
2798
  try {
2659
- const { chats, groups } = await engine.listChats({})
2799
+ const { chats, groups } = await engine.listChats({ meshId: this.meshId })
2660
2800
  const live = [...(chats ?? [])].reverse()
2661
2801
  const ago = (chat) =>
2662
2802
  `${Math.round((Date.now() - (chat.lastActivityAt || chat.createdAt)) / 1000)}s ago`
@@ -2689,7 +2829,7 @@ export class ChatApp {
2689
2829
  // Any surviving chat other than `excludeId` — the delete-active fallback. Deliberately not prefix
2690
2830
  // resolution: an empty needle must not read as an ambiguous match.
2691
2831
  async _anyLiveChat(excludeId) {
2692
- const { chats } = await this.engine.listChats({})
2832
+ const { chats } = await this.engine.listChats({ meshId: this.meshId })
2693
2833
  return (chats ?? []).find((c) => !c.deletedAt && c.id !== excludeId) ?? null
2694
2834
  }
2695
2835
 
@@ -2698,7 +2838,9 @@ export class ChatApp {
2698
2838
  async _agentFor(chat) {
2699
2839
  if (chat.agentId === this.agent.id) return this.agent
2700
2840
  // getAgent throws for a deleted agent; the active one drives the chat then
2701
- return this.engine.getAgent({ id: chat.agentId }).catch(() => this.agent)
2841
+ return this.engine
2842
+ .getAgent({ meshId: this.meshId, agentId: chat.agentId })
2843
+ .catch(() => this.agent)
2702
2844
  }
2703
2845
 
2704
2846
  _newChat(title) {
@@ -2706,7 +2848,11 @@ export class ChatApp {
2706
2848
  this,
2707
2849
  async () => {
2708
2850
  try {
2709
- const chat = await this.engine.createChat({ agentId: this.agent.id, title })
2851
+ const chat = await this.engine.createChat({
2852
+ meshId: this.meshId,
2853
+ agentId: this.agent.id,
2854
+ config: { title }
2855
+ })
2710
2856
  return { type: 'chat.switch', chat, agent: this.agent }
2711
2857
  } catch (error) {
2712
2858
  return { type: 'run.error', error }
@@ -2749,14 +2895,18 @@ export class ChatApp {
2749
2895
  }
2750
2896
  }
2751
2897
  if (!chat) return { type: 'notice', text: `no chat matching "${needle}"` }
2752
- await this.engine.deleteChat({ id: chat.id })
2898
+ await this.engine.deleteChat({ meshId: this.meshId, chatId: chat.id })
2753
2899
  if (chat.id !== this.chatId) {
2754
2900
  return { type: 'notice', text: `deleted "${chat.title}" (${chat.id.slice(0, 8)})` }
2755
2901
  }
2756
2902
  // deleted the active chat — switch to any survivor, else a fresh one
2757
2903
  const next =
2758
2904
  (await this._anyLiveChat(chat.id)) ??
2759
- (await this.engine.createChat({ agentId: this.agent.id, title: 'New Chat' }))
2905
+ (await this.engine.createChat({
2906
+ meshId: this.meshId,
2907
+ agentId: this.agent.id,
2908
+ config: { title: 'New Chat' }
2909
+ }))
2760
2910
  return { type: 'chat.switch', chat: next, agent: await this._agentFor(next) }
2761
2911
  } catch (error) {
2762
2912
  return { type: 'run.error', error }
@@ -2781,8 +2931,13 @@ export class ChatApp {
2781
2931
  _resetMeshWatches() {
2782
2932
  this._devicesIterator?.return?.().catch(() => {})
2783
2933
  this._devicesIterator = null
2934
+ this._chatsIterator?.return?.().catch(() => {})
2935
+ this._chatsIterator = null
2784
2936
  this._ownDefaultIterator?.return?.().catch(() => {})
2785
2937
  this._ownDefaultIterator = null
2938
+ this._meshGen += 1
2939
+ this._chats = []
2940
+ this._groups = []
2786
2941
  this.deviceLabels = new Map()
2787
2942
  this.deviceMembers = new Map()
2788
2943
  this.memberNames = new Map()
@@ -2801,11 +2956,12 @@ export class ChatApp {
2801
2956
  const { meshes } = await this.engine.listMeshes({})
2802
2957
  const { mesh, error } = resolveMesh(meshes ?? [], target)
2803
2958
  if (error) return { type: 'mesh.selected', text: error }
2804
- if (mesh.active) {
2959
+ if (mesh.meshId === this.meshId) {
2805
2960
  return { type: 'mesh.selected', text: `already on mesh ${mesh.meshId.slice(0, 8)}` }
2806
2961
  }
2807
- await this.engine.selectMesh({ meshId: mesh.meshId })
2808
- const next = await this.engine.meshInvite({}).catch(noop)
2962
+ // the pool keeps it loaded; nothing in Core moves, so the window moves itself
2963
+ if (!mesh.open) await this.engine.openMesh({ meshId: mesh.meshId })
2964
+ const next = await this.engine.meshInvite({ meshId: mesh.meshId }).catch(noop)
2809
2965
  return { type: 'mesh.selected', meshId: mesh.meshId, invite: next?.invite ?? null }
2810
2966
  } catch (error) {
2811
2967
  return { type: 'mesh.selected', error }
@@ -2831,7 +2987,16 @@ export class ChatApp {
2831
2987
  this.status = ''
2832
2988
  this.notice = notice
2833
2989
  this._render()
2834
- return batch(...[this._watchNextDevices(), this._bootstrap()].filter(Boolean))
2990
+ return this._enterMesh()
2991
+ }
2992
+
2993
+ // the list went on without the window's mesh, so the window lands where a boot would
2994
+ _lostMesh(meshId) {
2995
+ this._booting = true
2996
+ return async () => {
2997
+ const next = await this.engine.meshInvite({}).catch(noop)
2998
+ return { type: 'mesh.lost', meshId, invite: next?.invite ?? null }
2999
+ }
2835
3000
  }
2836
3001
 
2837
3002
  // The pick outlives the session in Core's device-local config — the same record the desktop
@@ -2988,9 +3153,9 @@ export class ChatApp {
2988
3153
  async () => {
2989
3154
  try {
2990
3155
  const [statuses, folds, chat] = await Promise.all([
2991
- engine.listChunks({ chatId, type: 'run-status' }),
2992
- engine.listChunks({ chatId, type: 'compaction' }),
2993
- engine.getChat({ id: chatId })
3156
+ engine.listChunks({ meshId: this.meshId, chatId, type: 'run-status' }),
3157
+ engine.listChunks({ meshId: this.meshId, chatId, type: 'compaction' }),
3158
+ engine.getChat({ meshId: this.meshId, chatId })
2994
3159
  ])
2995
3160
  const report = usageReport(statuses.chunks ?? [], folds.chunks ?? [])
2996
3161
  return { type: 'usage.result', report, title: chat.title }
@@ -3026,9 +3191,9 @@ export class ChatApp {
3026
3191
  // The provider device's advertised inventory — the installed skills/tools
3027
3192
  // the active agent may enable (empty when the provider is offline).
3028
3193
  async _providerCaps() {
3029
- const { devices } = await this.engine.listDevices({})
3030
- const hex = this.agent.providerDeviceId?.toString('hex')
3031
- const dev = devices.find((d) => d.id.toString('hex') === hex)
3194
+ const { devices } = await this.engine.listDevices({ meshId: this.meshId })
3195
+ const hex = this.agent.providerDeviceId && b4a.toHex(this.agent.providerDeviceId)
3196
+ const dev = devices.find((d) => b4a.toHex(d.id) === hex)
3032
3197
  return { skills: dev?.installedSkillNames ?? [], tools: dev?.installedToolNames ?? [] }
3033
3198
  }
3034
3199
 
@@ -3041,7 +3206,7 @@ export class ChatApp {
3041
3206
  this,
3042
3207
  async () => {
3043
3208
  try {
3044
- const fresh = await engine.getAgent({ id: agent.id })
3209
+ const fresh = await engine.getAgent({ meshId: this.meshId, agentId: agent.id })
3045
3210
  const caps = await this._providerCaps()
3046
3211
  const scope = (kind === 'skills' ? fresh.skillsScope : fresh.toolsScope) ?? 'selected'
3047
3212
  const enabled = (kind === 'skills' ? fresh.enabledSkills : fresh.enabledTools) ?? []
@@ -3058,7 +3223,9 @@ export class ChatApp {
3058
3223
  // (pre-upgrade provider) — the selector then renders as it always did.
3059
3224
  async _skillDetail() {
3060
3225
  if (!this._skills) return null
3061
- const skills = await this._skills(this.agent?.id, this.agent?.modelName).catch(noop)
3226
+ const skills = await this._skills(this.agent?.id, this.agent?.modelName, this.meshId).catch(
3227
+ noop
3228
+ )
3062
3229
  return skills ? new Map(skills.map((skill) => [skill.name, skill])) : null
3063
3230
  }
3064
3231
 
@@ -3069,7 +3236,7 @@ export class ChatApp {
3069
3236
  this,
3070
3237
  async () => {
3071
3238
  try {
3072
- const fresh = await engine.getAgent({ id: agent.id })
3239
+ const fresh = await engine.getAgent({ meshId: this.meshId, agentId: agent.id })
3073
3240
  const model = fresh.modelName ?? ''
3074
3241
  return {
3075
3242
  type: 'ctx.result',
@@ -3094,7 +3261,11 @@ export class ChatApp {
3094
3261
  this,
3095
3262
  async () => {
3096
3263
  try {
3097
- this.agent = await engine.updateAgent({ id: agent.id, ...patch })
3264
+ this.agent = await engine.updateAgent({
3265
+ meshId: this.meshId,
3266
+ agentId: agent.id,
3267
+ config: patch
3268
+ })
3098
3269
  return { type: 'notice', text: contextSizeNotice(this.agent, size) }
3099
3270
  } catch (error) {
3100
3271
  return { type: 'run.error', error }
@@ -3120,7 +3291,7 @@ export class ChatApp {
3120
3291
  this,
3121
3292
  async () => {
3122
3293
  try {
3123
- const fresh = await engine.getAgent({ id: agent.id })
3294
+ const fresh = await engine.getAgent({ meshId: this.meshId, agentId: agent.id })
3124
3295
  return {
3125
3296
  type: 'permissions.result',
3126
3297
  mode: fresh.approvalMode === 'skip-all' ? 'skip-all' : 'ask',
@@ -3313,7 +3484,7 @@ export class ChatApp {
3313
3484
  this,
3314
3485
  async () => {
3315
3486
  try {
3316
- const { agents } = await engine.listAgents({})
3487
+ const { agents } = await engine.listAgents({ meshId: this.meshId })
3317
3488
  const list = agents ?? []
3318
3489
  const active = this.agent?.id
3319
3490
  const entries = list.length
@@ -3351,7 +3522,7 @@ export class ChatApp {
3351
3522
  this,
3352
3523
  async () => {
3353
3524
  try {
3354
- const { chats, groups } = await engine.listChats({})
3525
+ const { chats, groups } = await engine.listChats({ meshId: this.meshId })
3355
3526
  const live = [...(chats ?? [])].reverse().filter((c) => !c.deletedAt)
3356
3527
  const active = this.chatId
3357
3528
  // reversed for the same reason as /group: core's list is oldest-activity first
@@ -3552,7 +3723,11 @@ export class ChatApp {
3552
3723
  this,
3553
3724
  async () => {
3554
3725
  try {
3555
- this.agent = await engine.updateAgent({ id: agent.id, modelName: row.name })
3726
+ this.agent = await engine.updateAgent({
3727
+ meshId: this.meshId,
3728
+ agentId: agent.id,
3729
+ config: { modelName: row.name }
3730
+ })
3556
3731
  return {
3557
3732
  type: 'notice',
3558
3733
  text: `${agent.name} now uses ${row.name} — downloads on next run`
@@ -3586,9 +3761,9 @@ export class ChatApp {
3586
3761
  async () => {
3587
3762
  try {
3588
3763
  this.agent = await engine.updateAgent({
3589
- id: agent.id,
3590
- [field]: enabled,
3591
- [scopeField]: 'selected'
3764
+ meshId: this.meshId,
3765
+ agentId: agent.id,
3766
+ config: { [field]: enabled, [scopeField]: 'selected' }
3592
3767
  })
3593
3768
  return { type: 'selector.saved' }
3594
3769
  } catch (error) {
@@ -3698,7 +3873,7 @@ export class ChatApp {
3698
3873
  this,
3699
3874
  async () => {
3700
3875
  try {
3701
- await engine.moveChat({ id: chat.id, groupId, afterId })
3876
+ await engine.moveChat({ meshId: this.meshId, chatId: chat.id, groupId, afterId })
3702
3877
  return { type: 'transient-status', token, text: `moved ${delta < 0 ? 'up' : 'down'}` }
3703
3878
  } catch (error) {
3704
3879
  return { type: 'run.error', error }
@@ -3728,7 +3903,11 @@ export class ChatApp {
3728
3903
  this,
3729
3904
  async () => {
3730
3905
  try {
3731
- await engine.setChatGroup({ id: chatId, groupId: row.groupId ?? undefined })
3906
+ await engine.setChatGroup({
3907
+ meshId: this.meshId,
3908
+ chatId,
3909
+ groupId: row.groupId ?? undefined
3910
+ })
3732
3911
  return { type: 'transient-status', token, text: `moved to ${row.label}` }
3733
3912
  } catch (error) {
3734
3913
  return { type: 'run.error', error }
@@ -3779,7 +3958,11 @@ export class ChatApp {
3779
3958
  this,
3780
3959
  async () => {
3781
3960
  try {
3782
- this.agent = await engine.updateAgent({ id: agent.id, ...patch })
3961
+ this.agent = await engine.updateAgent({
3962
+ meshId: this.meshId,
3963
+ agentId: agent.id,
3964
+ config: patch
3965
+ })
3783
3966
  return { type: 'selector.saved' }
3784
3967
  } catch (error) {
3785
3968
  return { type: 'run.error', error }
@@ -3862,7 +4045,9 @@ export class ChatApp {
3862
4045
  state.speaking = false
3863
4046
  state.turnBusy = false
3864
4047
  if (state.runId) {
3865
- void this.engine.stopRun({ chatId: this.chatId, runId: state.runId }).catch(() => {})
4048
+ void this.engine
4049
+ .stopRun({ meshId: this.meshId, chatId: this.chatId, runId: state.runId })
4050
+ .catch(() => {})
3866
4051
  }
3867
4052
  try {
3868
4053
  state.player?.kill('SIGKILL')
@@ -3910,6 +4095,7 @@ export class ChatApp {
3910
4095
  // sendMessage names the run it just enqueued, so the producer below can
3911
4096
  // follow that exact turn instead of diffing against a pre-turn snapshot
3912
4097
  const { runId } = await this.engine.sendMessage({
4098
+ meshId: this.meshId,
3913
4099
  chatId: this.chatId,
3914
4100
  agentId: this.agent.id,
3915
4101
  text: clean
@@ -3950,7 +4136,9 @@ export class ChatApp {
3950
4136
  } catch {}
3951
4137
  }
3952
4138
 
3953
- const watch = this.engine.chunksWatch({ chatId: this.chatId })[Symbol.asyncIterator]()
4139
+ const watch = this.engine
4140
+ .chunksWatch({ meshId: this.meshId, chatId: this.chatId })
4141
+ [Symbol.asyncIterator]()
3954
4142
  state.chunkWatch = watch
3955
4143
  state.runId = runId // for barge-in stopRun, armed before the turn materializes
3956
4144
  const producer = (async () => {
@@ -4058,7 +4246,7 @@ export class ChatApp {
4058
4246
  // single drain, so no peer can see the request before the message it
4059
4247
  // answers. No device id either — the executing Core stamps every
4060
4248
  // chunk with its own key; the host identity is never caller-supplied.
4061
- await engine.sendMessage({ chatId, agentId: agent.id, text })
4249
+ await engine.sendMessage({ meshId: this.meshId, chatId, agentId: agent.id, text })
4062
4250
  return { type: 'run.done' }
4063
4251
  } catch (error) {
4064
4252
  return { type: 'run.error', error }
@@ -4081,7 +4269,12 @@ export class ChatApp {
4081
4269
  this,
4082
4270
  async () => {
4083
4271
  try {
4084
- await engine.resolveApproval({ id, approved: status === 'approved', scope })
4272
+ await engine.resolveApproval({
4273
+ meshId: this.meshId,
4274
+ chunkId: id,
4275
+ approved: status === 'approved',
4276
+ scope
4277
+ })
4085
4278
  return { type: 'approval.done' }
4086
4279
  } catch (error) {
4087
4280
  return { type: 'run.error', error }
@@ -4104,7 +4297,7 @@ export class ChatApp {
4104
4297
  this,
4105
4298
  async () => {
4106
4299
  try {
4107
- await engine.stopRun({ chatId, runId })
4300
+ await engine.stopRun({ meshId: this.meshId, chatId, runId })
4108
4301
  return { type: 'transient-status', token, text: 'run stopped' }
4109
4302
  } catch (error) {
4110
4303
  return { type: 'run.error', error }
@@ -4176,6 +4369,13 @@ export class ChatApp {
4176
4369
  this._render()
4177
4370
  return [this, null]
4178
4371
  }
4372
+ if (msg.compute) {
4373
+ this._booting = false
4374
+ this.notice = `joined compute mesh ${msg.compute.slice(0, 8)} - it carries no chats, so this window stays here`
4375
+ this._render()
4376
+ return [this, null]
4377
+ }
4378
+ this.meshId = msg.meshId
4179
4379
  return [this, this._adoptMesh(msg.invite, 'joined — resolving the mesh’s agent and chat…')]
4180
4380
  }
4181
4381
 
@@ -4186,12 +4386,35 @@ export class ChatApp {
4186
4386
  this._render()
4187
4387
  return [this, null]
4188
4388
  }
4389
+ // the mesh this window named is the one that just went; the bootstrap resolves where
4390
+ // the device landed
4391
+ this.meshId = null
4189
4392
  return [
4190
4393
  this,
4191
4394
  this._adoptMesh(msg.invite, 'left — resolving the landing mesh’s agent and chat…')
4192
4395
  ]
4193
4396
  }
4194
4397
 
4398
+ if (msg.type === 'mesh.lost') {
4399
+ this.meshId = null
4400
+ const notice = `mesh ${msg.meshId.slice(0, 8)} is gone from this device - resolving the account’s agent and chat…`
4401
+ return [this, this._adoptMesh(msg.invite, notice)]
4402
+ }
4403
+
4404
+ if (msg.type === 'mesh.account') {
4405
+ this.meshId = msg.meshId
4406
+ return [this, this._enterMesh()]
4407
+ }
4408
+
4409
+ if (msg.type === 'meshes') {
4410
+ const ids = new Set(msg.meshes.map((mesh) => mesh.meshId))
4411
+ // a mesh transition in flight moves the window itself
4412
+ const lost = !this._booting && this._meshIds?.has(this.meshId) && !ids.has(this.meshId)
4413
+ this._meshIds = ids
4414
+ return [this, batch(this._watchNextMeshes(), lost ? this._lostMesh(this.meshId) : null)]
4415
+ }
4416
+ if (msg.type === 'meshes.done') return [this, null]
4417
+
4195
4418
  // /mesh use settled. Same landing as a join, minus the admission: the target
4196
4419
  // mesh was already ours, so only the agent, chat and roster have to catch up.
4197
4420
  if (msg.type === 'mesh.selected') {
@@ -4202,6 +4425,7 @@ export class ChatApp {
4202
4425
  this._render()
4203
4426
  return [this, null]
4204
4427
  }
4428
+ this.meshId = msg.meshId
4205
4429
  const settling = `switched to mesh ${msg.meshId.slice(0, 8)} - resolving its agent and chat…`
4206
4430
  return [this, this._adoptMesh(msg.invite, settling)]
4207
4431
  }
@@ -4241,7 +4465,7 @@ export class ChatApp {
4241
4465
  }
4242
4466
  if (msg.type === 'own-default') {
4243
4467
  // a stale one-shot must not clear the field a newer watch owns
4244
- if (msg.gen !== this.gen) return [this, null]
4468
+ if (msg.gen !== this._meshGen) return [this, null]
4245
4469
  this._ownDefaultIterator = null
4246
4470
  if (!msg.agent) return [this, null]
4247
4471
  // the seed lands whenever it replicates, and a /agent pick since the watch armed outranks it
@@ -4264,13 +4488,11 @@ export class ChatApp {
4264
4488
  }
4265
4489
 
4266
4490
  if (msg.type === 'devices') {
4267
- if (msg.gen !== this.gen) return [this, null]
4491
+ if (msg.gen !== this._meshGen) return [this, null]
4268
4492
  const devices = msg.frame.devices ?? []
4269
- this.deviceLabels = new Map(devices.map((d) => [d.id.toString('hex'), d.name]))
4493
+ this.deviceLabels = new Map(devices.map((d) => [b4a.toHex(d.id), d.name]))
4270
4494
  this.deviceMembers = new Map(
4271
- devices
4272
- .filter((d) => d.memberId)
4273
- .map((d) => [d.id.toString('hex'), d.memberId.toString('hex')])
4495
+ devices.filter((d) => d.memberId).map((d) => [b4a.toHex(d.id), b4a.toHex(d.memberId)])
4274
4496
  )
4275
4497
  this._render()
4276
4498
  const unnamed = [...this.deviceMembers.values()].some((id) => !this.memberNames.has(id))
@@ -4284,8 +4506,8 @@ export class ChatApp {
4284
4506
  if (msg.type === 'devices.done') return [this, null]
4285
4507
 
4286
4508
  if (msg.type === 'members.frame') {
4287
- if (msg.gen !== this.gen) return [this, null]
4288
- for (const m of msg.members) this.memberNames.set(m.id.toString('hex'), m.name)
4509
+ if (msg.gen !== this._meshGen) return [this, null]
4510
+ for (const m of msg.members) this.memberNames.set(b4a.toHex(m.id), m.name)
4289
4511
  this._render()
4290
4512
  return [this, null]
4291
4513
  }
@@ -4448,6 +4670,7 @@ export class ChatApp {
4448
4670
  }
4449
4671
 
4450
4672
  if (msg.type === 'chats') {
4673
+ if (msg.gen !== this._meshGen) return [this, null]
4451
4674
  this._chats = msg.frame.chats ?? []
4452
4675
  this._groups = msg.frame.groups ?? []
4453
4676
  if (this._sidebar) this._render()
@@ -4754,19 +4977,19 @@ export class ChatApp {
4754
4977
  return error ? { error } : { meshId: mesh.meshId }
4755
4978
  }
4756
4979
 
4757
- // Which room, and how to get to it: a room is opened beside the active mesh and never
4758
- // selected, so the user has to be told it exists and told how to go there.
4980
+ // Which room, and how to get to it: a room is opened beside the account and this window
4981
+ // stays where it is, so the user has to be told it exists and told how to go there.
4759
4982
  async _roomHeading(meshId) {
4760
4983
  if (!meshId) return 'shared room'
4761
4984
  const { meshes } = await this.engine.listMeshes({}).catch(() => ({ meshes: [] }))
4762
4985
  const index = (meshes ?? []).findIndex((mesh) => mesh.meshId === meshId)
4763
4986
  const where = index < 0 ? '/meshes lists it' : `/mesh use ${index + 1} to open it`
4764
- // a compute mesh is not a room to talk in: there is nothing to select into, so saying
4765
- // "shared room" of one would promise a place to work that it deliberately is not
4987
+ // a compute mesh is not a room to talk in: there is nothing to go to, so saying "shared
4988
+ // room" of one would promise a place to work that it deliberately is not
4766
4989
  if ((meshes ?? [])[index]?.compute) {
4767
4990
  return `compute mesh ${meshId.slice(0, 8)} - lends this device, carries nothing`
4768
4991
  }
4769
- return `shared room ${meshId.slice(0, 8)} - not selected, ${where}`
4992
+ return `shared room ${meshId.slice(0, 8)} - this window is elsewhere, ${where}`
4770
4993
  }
4771
4994
 
4772
4995
  // A clipboard that isn't there (or fails) must not fail the thing that wanted it.
@@ -4824,7 +5047,9 @@ export class ChatApp {
4824
5047
 
4825
5048
  async _uploadAttachment({ fileName, mimeType, data }) {
4826
5049
  const duplex = this.engine.uploadAttachment()
5050
+ // the first frame names the mesh; the rest carry bytes
4827
5051
  await writeFrame(duplex, {
5052
+ meshId: this.meshId,
4828
5053
  chatId: this.chatId,
4829
5054
  originDeviceId: this.originDeviceId,
4830
5055
  fileName,