local-operator-ui 0.50.9 → 0.50.11

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 (95) hide show
  1. package/out/main/index.js +1041 -26
  2. package/out/preload/index.js +44 -0
  3. package/out/renderer/assets/{_basePickBy-CK7k-8t8.js → _basePickBy-BLy0hAlE.js} +1 -1
  4. package/out/renderer/assets/{_baseUniq-DbkdeZ5I.js → _baseUniq-BlUN8jcK.js} +1 -1
  5. package/out/renderer/assets/{agent-details-page-DjErNg4V.js → agent-details-page-zixz-_vD.js} +1 -1
  6. package/out/renderer/assets/{agent-hub-page-CDj2ePx4.js → agent-hub-page-P_sP_k41.js} +1 -1
  7. package/out/renderer/assets/{agents-page-CPNecte8.js → agents-page-DPOxT5wB.js} +3 -3
  8. package/out/renderer/assets/{appearance-FPCt2M7X.js → appearance-Qga5xSRf.js} +35 -35
  9. package/out/renderer/assets/{arc-DKZFwAVQ.js → arc-CKz4vCBx.js} +1 -1
  10. package/out/renderer/assets/{architectureDiagram-IEHRJDOE-CKIVGEQl.js → architectureDiagram-IEHRJDOE-DDmEvrZz.js} +1 -1
  11. package/out/renderer/assets/{avatar-cropper-DSxQRufn.js → avatar-cropper-B3O2UQ4z.js} +1 -1
  12. package/out/renderer/assets/{blockDiagram-JOT3LUYC-BoVvIPu4.js → blockDiagram-JOT3LUYC-kK7lzVNf.js} +1 -1
  13. package/out/renderer/assets/{book-open-CO55dhr_.js → book-open-D_8LQHNl.js} +1 -1
  14. package/out/renderer/assets/browser-page-Djb1cs7X.js +1 -0
  15. package/out/renderer/assets/{browser-webauthn-prompt-CBfoTZae.js → browser-webauthn-prompt-sbqb2NuE.js} +1 -1
  16. package/out/renderer/assets/{building-2-B1ChbvPG.js → building-2-tIpP_TRE.js} +1 -1
  17. package/out/renderer/assets/{c4Diagram-VJAJSXHY-Ow3eVdx-.js → c4Diagram-VJAJSXHY-B13qzZI6.js} +1 -1
  18. package/out/renderer/assets/channel-OAMn7bvt.js +1 -0
  19. package/out/renderer/assets/{chunk-4BMEZGHF-D8N1MkDz.js → chunk-4BMEZGHF-KQ6Ich_0.js} +1 -1
  20. package/out/renderer/assets/{chunk-A2AXSNBT-mBI7bx2x.js → chunk-A2AXSNBT-BOSW6JNN.js} +1 -1
  21. package/out/renderer/assets/{chunk-AEK57VVT-oKin4dgE.js → chunk-AEK57VVT-BFiOlLeI.js} +1 -1
  22. package/out/renderer/assets/{chunk-D6G4REZN-OXIdmutS.js → chunk-D6G4REZN-Duqv7Gtd.js} +1 -1
  23. package/out/renderer/assets/{chunk-RZ5BOZE2-PTzKX_s5.js → chunk-RZ5BOZE2-CxQXd5a3.js} +1 -1
  24. package/out/renderer/assets/{chunk-XZIHB7SX-BD3TxXOb.js → chunk-XZIHB7SX-BvHuOcY9.js} +1 -1
  25. package/out/renderer/assets/classDiagram-GIVACNV2-B4BAeQra.js +1 -0
  26. package/out/renderer/assets/classDiagram-v2-COTLJTTW-B4BAeQra.js +1 -0
  27. package/out/renderer/assets/clone-fvWkTbP4.js +1 -0
  28. package/out/renderer/assets/{console-mirror-Cfo171WO.js → console-mirror-UuPaWNT9.js} +1 -1
  29. package/out/renderer/assets/{consoleCapture-B4MoEIVB.js → consoleCapture-DxgVtQTa.js} +1 -1
  30. package/out/renderer/assets/{conversation-input-sync-i_C7ofzH.js → conversation-input-sync-Bgr8dwlL.js} +5 -5
  31. package/out/renderer/assets/{dagre-OKDRZEBW-BjTmaOCh.js → dagre-OKDRZEBW-bct7NIzI.js} +1 -1
  32. package/out/renderer/assets/{diagram-SSKATNLV-DG0fLstS.js → diagram-SSKATNLV-CboqZw4Q.js} +1 -1
  33. package/out/renderer/assets/{diagram-VNBRO52H-DrhfS6bI.js → diagram-VNBRO52H-BWcPI7Vj.js} +1 -1
  34. package/out/renderer/assets/{erDiagram-Q7BY3M3F-D7ITF-Tz.js → erDiagram-Q7BY3M3F-aMzdjVpu.js} +1 -1
  35. package/out/renderer/assets/{error-boundary-BT9Xcv3G.js → error-boundary-DlgiXR_W.js} +1 -1
  36. package/out/renderer/assets/{flowDiagram-4HSFHLVR-CgzPZRno.js → flowDiagram-4HSFHLVR-B5nx2Zz_.js} +1 -1
  37. package/out/renderer/assets/{ganttDiagram-APWFNJXF-uExlIIUv.js → ganttDiagram-APWFNJXF-D7iAjZPD.js} +1 -1
  38. package/out/renderer/assets/{gitGraphDiagram-7IBYFJ6S-Cko9Q-aC.js → gitGraphDiagram-7IBYFJ6S-CAO-egov.js} +1 -1
  39. package/out/renderer/assets/{graph-DmzJqCaR.js → graph-BwZqKwz1.js} +1 -1
  40. package/out/renderer/assets/{heart-Du6t7fA8.js → heart-BCK87brK.js} +1 -1
  41. package/out/renderer/assets/{index-dKP_CxJ2.js → index-BBh_v05R.js} +1 -1
  42. package/out/renderer/assets/{index-Dt0CdFyK.js → index-BHTIrrxr.js} +4 -4
  43. package/out/renderer/assets/{index-BjvpVpdL.js → index-BMeH2cyS.js} +1 -1
  44. package/out/renderer/assets/{index-Dbpqzc5r.css → index-BiKEZgcN.css} +1 -1
  45. package/out/renderer/assets/infoDiagram-PH2N3AL5-DcXivpas.js +2 -0
  46. package/out/renderer/assets/{installer-BGIMNCRt.js → installer-B0kiahjw.js} +1 -1
  47. package/out/renderer/assets/{journeyDiagram-U35MCT3I-BQCXdZ-3.js → journeyDiagram-U35MCT3I-QVb22GnB.js} +1 -1
  48. package/out/renderer/assets/{kanban-definition-NDS4AKOZ-B5yBMDqT.js → kanban-definition-NDS4AKOZ-Bp0ZUbAp.js} +1 -1
  49. package/out/renderer/assets/{layout-D8OGIjVg.js → layout-DUnvuTZc.js} +1 -1
  50. package/out/renderer/assets/{legacy-agents-page-CJmIHpNr.js → legacy-agents-page-c2t8MEkp.js} +1 -1
  51. package/out/renderer/assets/{library-page-ByQtyJGb.js → library-page-F7ADbfmd.js} +3 -3
  52. package/out/renderer/assets/{log-in-IHg-V1QW.js → log-in-CCynzL3t.js} +1 -1
  53. package/out/renderer/assets/{mermaid.core-BvHUA0Sv.js → mermaid.core-BfNYlkXX.js} +5 -5
  54. package/out/renderer/assets/{mesh-page-B6BJS0D9.js → mesh-page-CvIbs7-5.js} +1 -1
  55. package/out/renderer/assets/{mindmap-definition-ALO5MXBD-DrRcOKJM.js → mindmap-definition-ALO5MXBD-3NA6_2Ql.js} +1 -1
  56. package/out/renderer/assets/{mini-BYjymniT.js → mini-BL2LzBx5.js} +1 -1
  57. package/out/renderer/assets/{notebook-pen-Dq3Ce4GV.js → notebook-pen-CVBxcim-.js} +1 -1
  58. package/out/renderer/assets/{notifications-page-D9kRe44g.js → notifications-page-BgURqgB7.js} +1 -1
  59. package/out/renderer/assets/{org-access-BHNV56VI.js → org-access-yiseHO4_.js} +1 -1
  60. package/out/renderer/assets/{org-surface-gate-Bl6YOlRr.js → org-surface-gate-DdlWGcie.js} +1 -1
  61. package/out/renderer/assets/{page-header-7BKVN9Ka.js → page-header-BxwBWZTf.js} +1 -1
  62. package/out/renderer/assets/{pieDiagram-IB7DONF6-Cic5pY5b.js → pieDiagram-IB7DONF6-7pP_uvEZ.js} +1 -1
  63. package/out/renderer/assets/{project-markdown-Drvuh5k5.js → project-markdown-D7sDv_F9.js} +1 -1
  64. package/out/renderer/assets/{projects-page-CrHJuViD.js → projects-page-BzIoEJ4J.js} +1 -1
  65. package/out/renderer/assets/{publication-validation-D7rpMxE5.js → publication-validation-Q2TXU7EB.js} +1 -1
  66. package/out/renderer/assets/{quadrantDiagram-7GDLP6J5-CHbW_AiG.js → quadrantDiagram-7GDLP6J5-CBq_sdux.js} +1 -1
  67. package/out/renderer/assets/{radar-MK3ICKWK-BpyT5iGG.js → radar-MK3ICKWK-Bljpe7MY.js} +1 -1
  68. package/out/renderer/assets/{radient-auth-buttons-CN8oqK4A.js → radient-auth-buttons-BoSljNKo.js} +1 -1
  69. package/out/renderer/assets/{requirementDiagram-KVF5MWMF-ikDDEJ4-.js → requirementDiagram-KVF5MWMF-CmlCCtjU.js} +1 -1
  70. package/out/renderer/assets/{sankeyDiagram-QLVOVGJD-UnP25y7D.js → sankeyDiagram-QLVOVGJD-Do-Nnqcd.js} +1 -1
  71. package/out/renderer/assets/{schedules-page-DzWZalKV.js → schedules-page-NLQ_Mrfi.js} +1 -1
  72. package/out/renderer/assets/{sequenceDiagram-X6HHIX6F-rwXWNUMl.js → sequenceDiagram-X6HHIX6F-mgHxN5Et.js} +1 -1
  73. package/out/renderer/assets/{settings-page-DXNsYjGy.js → settings-page-DOpmbZPP.js} +1 -1
  74. package/out/renderer/assets/{smartart-C-8WB509.js → smartart-DG_SI8w4.js} +1 -1
  75. package/out/renderer/assets/{stateDiagram-DGXRK772-CNCl-s2V.js → stateDiagram-DGXRK772-Djmv2Wqx.js} +1 -1
  76. package/out/renderer/assets/stateDiagram-v2-YXO3MK2T-C2e3f6R2.js +1 -0
  77. package/out/renderer/assets/{team-bridge-page-B0fHlTDH.js → team-bridge-page-Da-0rKFD.js} +9 -9
  78. package/out/renderer/assets/{team-bridge-scope-preference-D6GzCkKj.js → team-bridge-scope-preference-DPQ0LEA3.js} +1 -1
  79. package/out/renderer/assets/{timeline-definition-BDJGKUSR-1Mk5xG5m.js → timeline-definition-BDJGKUSR-DDf_IruO.js} +1 -1
  80. package/out/renderer/assets/{use-download-agent-mutation-BKPiEJXY.js → use-download-agent-mutation-H9VyjHin.js} +1 -1
  81. package/out/renderer/assets/{use-session-snapshot-CRkLYuFg.js → use-session-snapshot-CSozG8-n.js} +1 -1
  82. package/out/renderer/assets/{xychartDiagram-VJFVF3MP-Ccin3hTp.js → xychartDiagram-VJFVF3MP-fubriRGW.js} +1 -1
  83. package/out/renderer/console-capture.html +5 -5
  84. package/out/renderer/index.html +7 -7
  85. package/out/renderer/installer.html +4 -4
  86. package/out/renderer/mini.html +7 -7
  87. package/package.json +1 -1
  88. package/out/renderer/assets/browser-page-YmXc_nwx.js +0 -1
  89. package/out/renderer/assets/channel-B7o7f1r6.js +0 -1
  90. package/out/renderer/assets/classDiagram-GIVACNV2-cS2unNQH.js +0 -1
  91. package/out/renderer/assets/classDiagram-v2-COTLJTTW-cS2unNQH.js +0 -1
  92. package/out/renderer/assets/clone-CVHWytU8.js +0 -1
  93. package/out/renderer/assets/infoDiagram-PH2N3AL5-BKS5cXNq.js +0 -2
  94. package/out/renderer/assets/stateDiagram-v2-YXO3MK2T-DqG9Gq4-.js +0 -1
  95. /package/out/renderer/assets/{index-C2Ke3e-9.js → index-B_QzzAzx.js} +0 -0
package/out/main/index.js CHANGED
@@ -11,9 +11,9 @@ const node_child_process = require("node:child_process");
11
11
  const node_crypto = require("node:crypto");
12
12
  const os = require("node:os");
13
13
  const node_util = require("node:util");
14
+ const promises = require("node:fs/promises");
14
15
  const dotenv = require("dotenv");
15
16
  const electronLog = require("electron-log");
16
- const promises = require("node:fs/promises");
17
17
  const node_net = require("node:net");
18
18
  const require$$0 = require("node:process");
19
19
  const require$$0$1 = require("node:buffer");
@@ -69606,6 +69606,11 @@ function appendJournalOrderIds(query2, path2, ids) {
69606
69606
  }
69607
69607
  return selected;
69608
69608
  }
69609
+ const LINK_PREVIEW_MAX_URL_CHARS = 4096;
69610
+ const LINK_PREVIEW_ACCOUNT_MAX_CHARS = 128;
69611
+ const LINK_PREVIEW_ARTIFACT_ID = /^[0-9a-f]{32}$/;
69612
+ const LINK_PREVIEW_RESOLVE_CHANNEL = "link-preview:resolve";
69613
+ const LINK_PREVIEW_ARTIFACT_CHANNEL = "link-preview:artifact";
69609
69614
  const DOT_ONLY_VARIABLE_KEY = /^\.+$/;
69610
69615
  const PUBLICATION_FORMAT_POINT = /\p{Cf}/u;
69611
69616
  const PUBLICATION_PATH_SEPARATOR = /[/\\:]/;
@@ -72390,6 +72395,27 @@ const desktopRequestUnion = zod.z.discriminatedUnion("op", [
72390
72395
  op: zod.z.literal("team_bridge.status"),
72391
72396
  boundary: agentMessagesBoundarySchema.optional()
72392
72397
  }).strict(),
72398
+ /*
72399
+ * THE LINK-PREVIEW RESOLVE PROXY (`features`-free: core owns the capability, and
72400
+ * a resolve that is refused answers a STATE, never an error of this plane).
72401
+ *
72402
+ * The URL is length-bounded at core's own ceiling (`MAX_URL_CHARS` in
72403
+ * `server/routes/desktop_link_preview.py`), so a renderer value can never make
72404
+ * main serialize a body core refuses on size alone. `index` has a lower bound
72405
+ * and no upper one, deliberately mirroring the route: a position past the
72406
+ * per-message cap is the `cap` answer, not a shape error.
72407
+ *
72408
+ * `expectedAccountId` is the RECEIPT every Team Bridge op already carries. Main
72409
+ * holds no signed-in identity of its own to substitute, and core compares the
72410
+ * string against the identity the install actually holds and refuses a mismatch
72411
+ * (409), so forwarding it grants nothing.
72412
+ */
72413
+ zod.z.object({
72414
+ op: zod.z.literal("team_bridge.link_preview.resolve"),
72415
+ url: zod.z.string().min(1).max(LINK_PREVIEW_MAX_URL_CHARS),
72416
+ index: zod.z.number().int().nonnegative(),
72417
+ expectedAccountId: id$1
72418
+ }).strict(),
72393
72419
  zod.z.object({ op: zod.z.literal("settings.list") }).strict(),
72394
72420
  zod.z.object({
72395
72421
  op: zod.z.literal("settings.edit"),
@@ -75480,6 +75506,26 @@ function desktopEndpoint(request) {
75480
75506
  method: "GET"
75481
75507
  };
75482
75508
  }
75509
+ /*
75510
+ * THE LINK-PREVIEW RESOLVE PROXY. A POST because the receipt travels in the
75511
+ * body: core takes `expected_account_id` from the body here and from a HEADER
75512
+ * on the artifact route, and never from a query string, so no intermediary's
75513
+ * log or crash report records whose preview was asked for.
75514
+ *
75515
+ * The receipt is forwarded, never derived: `expected_account_id` is what the
75516
+ * caller says it is, core compares it against the identity the install holds,
75517
+ * and a mismatch is a 409 the renderer draws as "sign in as that account".
75518
+ */
75519
+ case "team_bridge.link_preview.resolve":
75520
+ return {
75521
+ path: "/v1/desktop/team-bridge/link-preview/resolve",
75522
+ method: "POST",
75523
+ body: {
75524
+ url: request.url,
75525
+ index: request.index,
75526
+ expected_account_id: request.expectedAccountId
75527
+ }
75528
+ };
75483
75529
  case "settings.list":
75484
75530
  return { path: "/v1/settings", method: "GET" };
75485
75531
  case "settings.edit":
@@ -76557,6 +76603,7 @@ class AppAttentionService {
76557
76603
  this.account = null;
76558
76604
  this.cursor = void 0;
76559
76605
  this.projection.setBridgeUnread(0, this.projection.currentGeneration);
76606
+ this.ports.principalChanged?.();
76560
76607
  this.invalidate();
76561
76608
  } else if (writes.has(op)) {
76562
76609
  if (op.startsWith("team_bridge.")) this.invalidateBridge();
@@ -76934,7 +76981,7 @@ function toAttachment(payload) {
76934
76981
  stored_path: typeof record.stored_path === "string" ? record.stored_path : null
76935
76982
  };
76936
76983
  }
76937
- function refusalDetail(payload) {
76984
+ function refusalDetail$1(payload) {
76938
76985
  if (payload === null || typeof payload !== "object") return null;
76939
76986
  const detail = payload.detail;
76940
76987
  if (typeof detail === "string" && detail.trim()) return detail;
@@ -77056,7 +77103,7 @@ async function uploadAttachment(input) {
77056
77103
  return {
77057
77104
  success: false,
77058
77105
  code: "refused",
77059
- error: refusalDetail(payload) ?? `The daemon refused the upload (HTTP ${response.status}).`,
77106
+ error: refusalDetail$1(payload) ?? `The daemon refused the upload (HTTP ${response.status}).`,
77060
77107
  sizeBytes: size
77061
77108
  };
77062
77109
  }
@@ -80350,6 +80397,474 @@ class DesktopFeedRelay {
80350
80397
  }
80351
80398
  }
80352
80399
  }
80400
+ const ARTIFACT_TTL_MS = 24 * 60 * 60 * 1e3;
80401
+ const ARTIFACT_MAX_BYTES = 64 * 1024 * 1024;
80402
+ const ARTIFACT_MAX_COUNT = 400;
80403
+ const ARTIFACT_SWEEP_INTERVAL_MS = 5 * 60 * 1e3;
80404
+ const ARTIFACT_MAX_BLOB_BYTES = 4 * 1024 * 1024;
80405
+ const ARTIFACT_ALLOWED_MIMES = /* @__PURE__ */ new Set([
80406
+ "image/png",
80407
+ "image/jpeg",
80408
+ "image/gif",
80409
+ "image/webp",
80410
+ "image/vnd.microsoft.icon"
80411
+ ]);
80412
+ const INDEX_FILE = "index.json";
80413
+ const INDEX_VERSION = 2;
80414
+ const DIRECTORY_MODE = 448;
80415
+ const FILE_MODE = 384;
80416
+ function artifactOwnerFingerprint(accountId) {
80417
+ return node_crypto.createHash("sha256").update(`link-preview-account\0${accountId}`).digest("hex").slice(0, 32);
80418
+ }
80419
+ class LinkPreviewArtifactCache {
80420
+ dir;
80421
+ now;
80422
+ ttlMs;
80423
+ maxBytes;
80424
+ maxArtifacts;
80425
+ sweepIntervalMs;
80426
+ entries = /* @__PURE__ */ new Map();
80427
+ residentBytes = 0;
80428
+ evictions = 0;
80429
+ hits = 0;
80430
+ misses = 0;
80431
+ foreignHits = 0;
80432
+ lastSweep = Number.NEGATIVE_INFINITY;
80433
+ opened = false;
80434
+ /** Serializes every mutating pass, so two concurrent writers cannot interleave
80435
+ * a sweep with a store and leave the index accounting for a file that is gone.
80436
+ * `read` is deliberately NOT queued (it is the hot path); it only mutates
80437
+ * through `forgetEntry`, which is atomic within one synchronous step. */
80438
+ queue = Promise.resolve();
80439
+ constructor(options) {
80440
+ this.dir = options.dir;
80441
+ this.now = options.now ?? (() => Date.now());
80442
+ this.ttlMs = options.ttlMs ?? ARTIFACT_TTL_MS;
80443
+ this.maxBytes = options.maxBytes ?? ARTIFACT_MAX_BYTES;
80444
+ this.maxArtifacts = options.maxArtifacts ?? ARTIFACT_MAX_COUNT;
80445
+ this.sweepIntervalMs = options.sweepIntervalMs ?? ARTIFACT_SWEEP_INTERVAL_MS;
80446
+ }
80447
+ /** The directory this cache owns. Named so a test can assert a file's presence
80448
+ * without re-deriving the path. */
80449
+ get directory() {
80450
+ return this.dir;
80451
+ }
80452
+ /**
80453
+ * Create the directory, load the index, delete files no entry describes, and
80454
+ * apply the bounds once.
80455
+ *
80456
+ * STARTUP IS THE ONE UNCONDITIONAL SWEEP. The interval below bounds how often a
80457
+ * read or write may sweep, which would otherwise let a cold cache keep expired
80458
+ * bytes for five minutes after launch; a process that starts with a full disk
80459
+ * and a stale index should not wait for a card to be drawn before it recovers
80460
+ * the space.
80461
+ */
80462
+ async open() {
80463
+ await promises.mkdir(this.dir, { recursive: true, mode: DIRECTORY_MODE });
80464
+ await promises.chmod(this.dir, DIRECTORY_MODE).catch(() => {
80465
+ });
80466
+ await this.loadIndex();
80467
+ await this.serialize(async () => {
80468
+ await this.removeOrphans();
80469
+ await this.sweepNow();
80470
+ });
80471
+ this.opened = true;
80472
+ this.lastSweep = this.now();
80473
+ }
80474
+ /** Every cached id currently indexed, oldest use first. Diagnostics and tests
80475
+ * only: the bytes are addressed one id at a time. */
80476
+ ids() {
80477
+ return [...this.entries.entries()].sort((a, b) => a[1].lastUsedAt - b[1].lastUsedAt).map(([id2]) => id2);
80478
+ }
80479
+ stats() {
80480
+ return {
80481
+ entries: this.entries.size,
80482
+ residentBytes: this.residentBytes,
80483
+ evictions: this.evictions,
80484
+ hits: this.hits,
80485
+ misses: this.misses,
80486
+ foreignHits: this.foreignHits
80487
+ };
80488
+ }
80489
+ /**
80490
+ * The bytes for one id, for the receipt that asks, or `null`.
80491
+ *
80492
+ * An id that is not in the index is a miss without a filesystem call. An id
80493
+ * whose entry belongs to a DIFFERENT receipt is also a miss — and deliberately
80494
+ * not a deletion: the other account's entry is still the right answer for its
80495
+ * own card, and this request must now go and ask core, which is the authority
80496
+ * on whose scope names what.
80497
+ *
80498
+ * An entry that IS in the index but whose file has gone is a miss too, and the
80499
+ * entry is dropped, so the next lookup does not pay for the same stat. An
80500
+ * expired entry is a miss and is removed at the next sweep, so a read never
80501
+ * depends on when a sweep last ran.
80502
+ */
80503
+ async read(id2, accountFingerprint) {
80504
+ if (!this.opened) return null;
80505
+ const entry = this.entries.get(id2);
80506
+ if (entry === void 0) {
80507
+ this.misses += 1;
80508
+ return null;
80509
+ }
80510
+ if (entry.account !== accountFingerprint) {
80511
+ this.foreignHits += 1;
80512
+ return null;
80513
+ }
80514
+ if (!ARTIFACT_ALLOWED_MIMES.has(entry.mime)) {
80515
+ this.misses += 1;
80516
+ return null;
80517
+ }
80518
+ if (this.now() - entry.storedAt >= this.ttlMs) {
80519
+ this.misses += 1;
80520
+ return null;
80521
+ }
80522
+ let bytes;
80523
+ try {
80524
+ bytes = new Uint8Array(await promises.readFile(path$1.join(this.dir, id2)));
80525
+ } catch {
80526
+ this.forgetEntry(id2);
80527
+ this.misses += 1;
80528
+ return null;
80529
+ }
80530
+ entry.lastUsedAt = this.now();
80531
+ this.hits += 1;
80532
+ void this.maybeSweep();
80533
+ return { mime: entry.mime, bytes };
80534
+ }
80535
+ /**
80536
+ * Keep one blob for one receipt, then re-apply the bounds if they are exceeded.
80537
+ *
80538
+ * A blob over `ARTIFACT_MAX_BLOB_BYTES` is refused before anything is written:
80539
+ * storing it would evict several legitimate artifacts to hold something core
80540
+ * would never have produced. So is a mime outside `ARTIFACT_ALLOWED_MIMES` and
80541
+ * an id that is not one (see the header's note on `image/svg+xml` and on the
80542
+ * file name being a path segment).
80543
+ */
80544
+ async store(id2, mime, bytes, accountFingerprint) {
80545
+ if (!this.opened) return;
80546
+ if (bytes.byteLength === 0 || bytes.byteLength > ARTIFACT_MAX_BLOB_BYTES)
80547
+ return;
80548
+ if (!ARTIFACT_ALLOWED_MIMES.has(mime)) return;
80549
+ if (!LINK_PREVIEW_ARTIFACT_ID.test(id2)) return;
80550
+ await this.serialize(async () => {
80551
+ const path2 = path$1.join(this.dir, id2);
80552
+ const temp = `${path2}.${process.pid}.${node_crypto.randomBytes(6).toString("hex")}.tmp`;
80553
+ try {
80554
+ await promises.writeFile(temp, bytes, { mode: FILE_MODE });
80555
+ await promises.rename(temp, path2);
80556
+ } catch {
80557
+ await promises.rm(temp, { force: true }).catch(() => {
80558
+ });
80559
+ return;
80560
+ }
80561
+ const at = this.now();
80562
+ this.rememberEntry(id2, {
80563
+ mime,
80564
+ size: bytes.byteLength,
80565
+ storedAt: at,
80566
+ // A fresh blob is the newest thing here: its storedAt starts its TTL,
80567
+ // and its lastUsedAt is now, so it is the last thing an LRU pass takes.
80568
+ lastUsedAt: at,
80569
+ account: accountFingerprint
80570
+ });
80571
+ await this.persistIndex();
80572
+ await this.sweepNow();
80573
+ });
80574
+ }
80575
+ /**
80576
+ * Forget specific artifacts — the "disabled"/"absent" rule's only mechanism.
80577
+ *
80578
+ * Called with the ids a preview was holding, so the bytes cannot outlive the
80579
+ * card that asked for them: a cached artifact must not survive
80580
+ * `web_fetch.enabled: false` being turned on-after-off, and a preview that has
80581
+ * since answered `absent` must not keep drawing its old picture.
80582
+ *
80583
+ * Never fails a caller: a blob that cannot be deleted is dropped from the index
80584
+ * anyway, because an unindexed file is unreachable and the next startup's
80585
+ * orphan pass removes it.
80586
+ */
80587
+ async drop(ids) {
80588
+ if (!this.opened || ids.length === 0) return;
80589
+ await this.serialize(async () => {
80590
+ let changed = false;
80591
+ for (const id2 of ids) {
80592
+ if (!this.forgetEntry(id2)) continue;
80593
+ changed = true;
80594
+ try {
80595
+ await promises.rm(path$1.join(this.dir, id2), { force: true });
80596
+ } catch {
80597
+ }
80598
+ }
80599
+ if (changed) await this.persistIndex();
80600
+ });
80601
+ }
80602
+ /**
80603
+ * Drop EVERY cached blob — the principal-transition rule.
80604
+ *
80605
+ * A sign-out or account switch must not leave the previous account's images on
80606
+ * disk for the remainder of their TTL. This is deliberately a full clear rather
80607
+ * than a per-account drop: at the moment the fence fires this process no longer
80608
+ * knows which receipts its entries belonged to, and keeping some of them is
80609
+ * worth less than the guarantee that none of them are the departing account's.
80610
+ */
80611
+ async clear() {
80612
+ if (!this.opened) return;
80613
+ await this.serialize(async () => {
80614
+ const ids = [...this.entries.keys()];
80615
+ for (const id2 of ids) this.forgetEntry(id2);
80616
+ await this.persistIndex();
80617
+ for (const id2 of ids) {
80618
+ try {
80619
+ await promises.rm(path$1.join(this.dir, id2), { force: true });
80620
+ } catch {
80621
+ }
80622
+ }
80623
+ });
80624
+ }
80625
+ /** Apply the bounds now, whatever the interval says. */
80626
+ async sweep() {
80627
+ if (!this.opened) return;
80628
+ await this.serialize(async () => {
80629
+ await this.sweepNow();
80630
+ this.lastSweep = this.now();
80631
+ });
80632
+ }
80633
+ /**
80634
+ * Give up one entry and its bytes from the accounting.
80635
+ *
80636
+ * THE ONLY PLACE `residentBytes` MAY DECREASE, and it decreases exactly when
80637
+ * this call actually removed the entry — `Map.delete` is the witness. The
80638
+ * sibling bug this replaces read an entry, awaited a file read, then subtracted
80639
+ * unconditionally, so two racing misses subtracted one entry twice and the byte
80640
+ * ceiling stopped firing. No `await` may appear between the delete and the
80641
+ * subtract.
80642
+ */
80643
+ forgetEntry(id2) {
80644
+ const entry = this.entries.get(id2);
80645
+ if (entry === void 0) return false;
80646
+ this.entries.delete(id2);
80647
+ this.residentBytes -= entry.size;
80648
+ return true;
80649
+ }
80650
+ /** The only place `residentBytes` may increase, paired with `forgetEntry`. */
80651
+ rememberEntry(id2, entry) {
80652
+ this.forgetEntry(id2);
80653
+ this.entries.set(id2, entry);
80654
+ this.residentBytes += entry.size;
80655
+ }
80656
+ async maybeSweep() {
80657
+ if (this.now() - this.lastSweep < this.sweepIntervalMs) return;
80658
+ this.lastSweep = this.now();
80659
+ await this.serialize(() => this.sweepNow()).catch(() => {
80660
+ });
80661
+ }
80662
+ async sweepNow() {
80663
+ const at = this.now();
80664
+ let changed = false;
80665
+ for (const [id2, entry] of [...this.entries]) {
80666
+ if (at - entry.storedAt < this.ttlMs) continue;
80667
+ if (this.forgetEntry(id2)) {
80668
+ await this.unlink(id2);
80669
+ changed = true;
80670
+ }
80671
+ }
80672
+ while (this.entries.size > this.maxArtifacts || this.residentBytes > this.maxBytes) {
80673
+ const oldest = this.ids()[0];
80674
+ if (oldest === void 0) break;
80675
+ if (!this.forgetEntry(oldest)) break;
80676
+ this.evictions += 1;
80677
+ await this.unlink(oldest);
80678
+ changed = true;
80679
+ }
80680
+ if (changed) await this.persistIndex();
80681
+ }
80682
+ async unlink(id2) {
80683
+ try {
80684
+ await promises.rm(path$1.join(this.dir, id2), { force: true });
80685
+ } catch {
80686
+ }
80687
+ }
80688
+ async loadIndex() {
80689
+ let raw;
80690
+ try {
80691
+ raw = await promises.readFile(path$1.join(this.dir, INDEX_FILE), "utf8");
80692
+ } catch {
80693
+ return;
80694
+ }
80695
+ let document;
80696
+ try {
80697
+ document = JSON.parse(raw);
80698
+ } catch {
80699
+ return;
80700
+ }
80701
+ if (typeof document !== "object" || document === null || document.version !== INDEX_VERSION || typeof document.entries !== "object" || document.entries === null)
80702
+ return;
80703
+ for (const [id2, entry] of Object.entries(
80704
+ document.entries
80705
+ )) {
80706
+ if (!isIndexEntry(entry)) continue;
80707
+ if (!LINK_PREVIEW_ARTIFACT_ID.test(id2)) continue;
80708
+ this.entries.set(id2, { ...entry });
80709
+ this.residentBytes += entry.size;
80710
+ }
80711
+ }
80712
+ /**
80713
+ * Write the index beside the blobs, atomically.
80714
+ *
80715
+ * A failure here is absorbed on purpose. The cost of an unpersisted index is one
80716
+ * cold startup — every file becomes an orphan and is deleted, which loses cached
80717
+ * bytes and nothing else — while throwing would turn "the disk is full" into an
80718
+ * IPC rejection on a card that drew fine a moment ago.
80719
+ */
80720
+ async persistIndex() {
80721
+ const document = {
80722
+ version: INDEX_VERSION,
80723
+ entries: Object.fromEntries(this.entries)
80724
+ };
80725
+ const path2 = path$1.join(this.dir, INDEX_FILE);
80726
+ const temp = `${path2}.${process.pid}.${node_crypto.randomBytes(6).toString("hex")}.tmp`;
80727
+ try {
80728
+ await promises.writeFile(temp, JSON.stringify(document), { mode: FILE_MODE });
80729
+ await promises.rename(temp, path2);
80730
+ } catch {
80731
+ await promises.rm(temp, { force: true }).catch(() => {
80732
+ });
80733
+ }
80734
+ }
80735
+ /** Delete every file this index does not describe, so an interrupted `store`
80736
+ * cannot leak storage past the bounds. `index.json` and in-flight temps are
80737
+ * never touched. */
80738
+ async removeOrphans() {
80739
+ let names;
80740
+ try {
80741
+ names = await promises.readdir(this.dir);
80742
+ } catch {
80743
+ return;
80744
+ }
80745
+ for (const name of names) {
80746
+ if (name === INDEX_FILE) continue;
80747
+ if (this.entries.has(name)) continue;
80748
+ try {
80749
+ await promises.rm(path$1.join(this.dir, name), { recursive: true, force: true });
80750
+ } catch {
80751
+ }
80752
+ }
80753
+ }
80754
+ serialize(work) {
80755
+ const next = this.queue.then(work, work);
80756
+ this.queue = next.catch(() => {
80757
+ });
80758
+ return next;
80759
+ }
80760
+ }
80761
+ function previewKeyFor(accountFingerprint, url) {
80762
+ return node_crypto.createHash("sha256").update(`link-preview\0${accountFingerprint}\0${url}`).digest("hex");
80763
+ }
80764
+ function isIndexEntry(value) {
80765
+ if (typeof value !== "object" || value === null) return false;
80766
+ const entry = value;
80767
+ return typeof entry.mime === "string" && entry.mime.length > 0 && entry.mime.length <= 128 && typeof entry.size === "number" && Number.isInteger(entry.size) && entry.size >= 0 && typeof entry.storedAt === "number" && Number.isFinite(entry.storedAt) && typeof entry.lastUsedAt === "number" && Number.isFinite(entry.lastUsedAt) && typeof entry.account === "string" && entry.account.length === 32;
80768
+ }
80769
+ const DECIMAL_LENGTH$1 = /^\d+$/;
80770
+ const MAX_REFUSAL_BODY_BYTES = 4096;
80771
+ function failure(status2, code) {
80772
+ return {
80773
+ status: status2,
80774
+ kind: "error",
80775
+ detail: "That preview image is not available.",
80776
+ ...code === void 0 ? {} : { refusal: { code } }
80777
+ };
80778
+ }
80779
+ async function refusalCode(response) {
80780
+ if (!response.body) return void 0;
80781
+ let text2;
80782
+ try {
80783
+ const reader = response.body.getReader();
80784
+ const chunks = [];
80785
+ let size = 0;
80786
+ for (; ; ) {
80787
+ const { done, value } = await reader.read();
80788
+ if (done) break;
80789
+ size += value.byteLength;
80790
+ if (size > MAX_REFUSAL_BODY_BYTES) {
80791
+ await reader.cancel().catch(() => {
80792
+ });
80793
+ return void 0;
80794
+ }
80795
+ chunks.push(value);
80796
+ }
80797
+ reader.releaseLock();
80798
+ const data = new Uint8Array(size);
80799
+ let offset = 0;
80800
+ for (const chunk of chunks) {
80801
+ data.set(chunk, offset);
80802
+ offset += chunk.byteLength;
80803
+ }
80804
+ text2 = new TextDecoder().decode(data);
80805
+ } catch {
80806
+ return void 0;
80807
+ }
80808
+ try {
80809
+ const body2 = JSON.parse(text2);
80810
+ const detail = body2?.detail;
80811
+ if (typeof detail !== "object" || detail === null) return void 0;
80812
+ const code = detail.code;
80813
+ return typeof code === "string" && code.length <= 64 ? code : void 0;
80814
+ } catch {
80815
+ return void 0;
80816
+ }
80817
+ }
80818
+ async function readLinkPreviewArtifact(response) {
80819
+ if (response.status !== 200) {
80820
+ const code = response.status === 404 ? await refusalCode(response) : void 0;
80821
+ return failure(response.status, code);
80822
+ }
80823
+ const mime = (response.headers.get("content-type") ?? "").split(";")[0].trim().toLowerCase();
80824
+ if (!ARTIFACT_ALLOWED_MIMES.has(mime)) {
80825
+ await response.body?.cancel().catch(() => {
80826
+ });
80827
+ return failure(422);
80828
+ }
80829
+ const length = response.headers.get("content-length");
80830
+ if (length !== null) {
80831
+ if (!DECIMAL_LENGTH$1.test(length)) return failure(422);
80832
+ if (Number(length) > ARTIFACT_MAX_BLOB_BYTES) {
80833
+ await response.body?.cancel().catch(() => {
80834
+ });
80835
+ return failure(413);
80836
+ }
80837
+ }
80838
+ if (!response.body) return failure(422);
80839
+ const reader = response.body.getReader();
80840
+ const chunks = [];
80841
+ let size = 0;
80842
+ try {
80843
+ for (; ; ) {
80844
+ const { done, value } = await reader.read();
80845
+ if (done) break;
80846
+ size += value.byteLength;
80847
+ if (size > ARTIFACT_MAX_BLOB_BYTES) {
80848
+ await reader.cancel().catch(() => {
80849
+ });
80850
+ return failure(413);
80851
+ }
80852
+ chunks.push(value);
80853
+ }
80854
+ } catch {
80855
+ return failure(503);
80856
+ } finally {
80857
+ reader.releaseLock();
80858
+ }
80859
+ if (size === 0) return failure(422);
80860
+ const data = new Uint8Array(size);
80861
+ let offset = 0;
80862
+ for (const chunk of chunks) {
80863
+ data.set(chunk, offset);
80864
+ offset += chunk.byteLength;
80865
+ }
80866
+ return { status: 200, kind: "bytes", mimeType: mime, data };
80867
+ }
80353
80868
  const IMAGE_CAP = 5 * 1024 * 1024;
80354
80869
  const DECIMAL_LENGTH = /^\d+$/;
80355
80870
  async function readOwnerAuditAttachment(response) {
@@ -80679,6 +81194,25 @@ const mediaRequestSchema = zod.z.discriminatedUnion("op", [
80679
81194
  op: zod.z.literal("notification_sounds.upload"),
80680
81195
  fileName: zod.z.string().min(1).max(255),
80681
81196
  name: zod.z.string().min(1).max(200).optional()
81197
+ }).strict(),
81198
+ /*
81199
+ * ONE CACHED LINK-PREVIEW ARTIFACT, by the id core derived for it.
81200
+ *
81201
+ * THE ID IS SHAPED HERE, not merely passed through: it is a PATH SEGMENT on this
81202
+ * request and a FILE NAME in main's artifact cache, so one check in front of both
81203
+ * is cheaper than a path bug. `[0-9a-f]{32}` mirrors core's own
81204
+ * `ARTIFACT_ID_PATTERN`, which the artifact route and the store both re-check.
81205
+ *
81206
+ * `expectedAccountId` travels as the `X-Link-Preview-Account` HEADER below, never
81207
+ * as a query parameter: this is a GET, and a GET's URL is the one thing every
81208
+ * intermediary writes down. Core answers 404 when the caller's scope does not
81209
+ * name the id - indistinguishable from "gone" by design — and 422 for a
81210
+ * malformed one.
81211
+ */
81212
+ zod.z.object({
81213
+ op: zod.z.literal("team_bridge.link_preview.artifact"),
81214
+ id: zod.z.string().regex(LINK_PREVIEW_ARTIFACT_ID),
81215
+ expectedAccountId: zod.z.string().min(1).max(128)
80682
81216
  }).strict()
80683
81217
  ]);
80684
81218
  function endpoint(request) {
@@ -80813,6 +81347,22 @@ function endpoint(request) {
80813
81347
  path: `/v1/desktop/team-bridge/accounts/${request.accountId}/avatar?${new URLSearchParams({ v: request.hash, size: String(request.size), expected_account_id: request.expectedAccountId })}`,
80814
81348
  method: "GET"
80815
81349
  };
81350
+ /*
81351
+ * One cached link-preview artifact id (core's scope-derived hash).
81352
+ *
81353
+ * The path segment is the id and nothing else: no query string at all, because
81354
+ * the account receipt this route needs travels as the `X-Link-Preview-Account`
81355
+ * HEADER (see the header block in `requestDesktopMediaOutcome`) - a GET's URL is
81356
+ * written down by every intermediary, and an account id does not belong there.
81357
+ * `encodeURIComponent` is belt over the schema's `[0-9a-f]{32}`: the schema is
81358
+ * this client's check, and a hand-built request must not be able to turn an id
81359
+ * into a path fragment either.
81360
+ */
81361
+ case "team_bridge.link_preview.artifact":
81362
+ return {
81363
+ path: `/v1/desktop/team-bridge/link-preview/artifact/${encodeURIComponent(request.id)}`,
81364
+ method: "GET"
81365
+ };
80816
81366
  }
80817
81367
  }
80818
81368
  function scalarParams(params) {
@@ -80875,7 +81425,7 @@ async function requestDesktopMediaOutcome(input, bytes, backendUrl, token) {
80875
81425
  const target2 = endpoint(request);
80876
81426
  let body2;
80877
81427
  let contentType;
80878
- if (request.op === "account.profile" || request.op === "account.avatar.delete" || request.op === "agent.export" || request.op === "agent.avatar" || request.op === "agent.avatar.delete" || request.op === "sessions.attachment" || request.op === "subagents.attachment" || request.op === "sessions.attachment.waveform" || request.op === "sessions.supplementDocument" || request.op === "library.content" || request.op === "library.thumbnail" || request.op === "library.waveform" || request.op === "notification_sounds.audio" || request.op === "team_bridge.attachment" || request.op === "team_bridge.owner_audit.attachment" || request.op === "team_bridge.avatar" || request.op === "team_bridge.endpoint_avatar" || request.op === "team_bridge.notification_avatar") {
81428
+ if (request.op === "account.profile" || request.op === "account.avatar.delete" || request.op === "agent.export" || request.op === "agent.avatar" || request.op === "agent.avatar.delete" || request.op === "sessions.attachment" || request.op === "subagents.attachment" || request.op === "sessions.attachment.waveform" || request.op === "sessions.supplementDocument" || request.op === "library.content" || request.op === "library.thumbnail" || request.op === "library.waveform" || request.op === "notification_sounds.audio" || request.op === "team_bridge.attachment" || request.op === "team_bridge.owner_audit.attachment" || request.op === "team_bridge.avatar" || request.op === "team_bridge.endpoint_avatar" || request.op === "team_bridge.link_preview.artifact" || request.op === "team_bridge.notification_avatar") {
80879
81429
  body2 = void 0;
80880
81430
  } else if (request.op === "team_bridge.attachment.upload" || request.op === "account.avatar.put" || request.op === "agent.avatar.put") {
80881
81431
  if (!bytes || bytes.byteLength === 0) {
@@ -80928,6 +81478,14 @@ async function requestDesktopMediaOutcome(input, bytes, backendUrl, token) {
80928
81478
  // #3363 forwards the name only in file mode; it is display content,
80929
81479
  // never a filesystem path or a declared MIME/safety claim.
80930
81480
  ...request.op === "team_bridge.attachment.upload" && request.mode === "file" && request.fileName ? { "X-Bridge-File-Name": encodeURIComponent(request.fileName) } : {},
81481
+ /*
81482
+ * The artifact route's account RECEIPT, as a header and only as a header
81483
+ * (core's `ACCOUNT_RECEIPT_HEADER`). The preview endpoints take the account
81484
+ * this session claims so core can refuse a mismatch; on this GET there is no
81485
+ * body to carry it and a query string would put it in every log between here
81486
+ * and the daemon, which is precisely what core's route refuses to do.
81487
+ */
81488
+ ...request.op === "team_bridge.link_preview.artifact" ? { "X-Link-Preview-Account": request.expectedAccountId } : {},
80931
81489
  Authorization: `Bearer ${token}`
80932
81490
  },
80933
81491
  body: body2,
@@ -80941,6 +81499,12 @@ async function requestDesktopMediaOutcome(input, bytes, backendUrl, token) {
80941
81499
  });
80942
81500
  answered = true;
80943
81501
  const responseType = response.headers.get("content-type") ?? "";
81502
+ if (request.op === "team_bridge.link_preview.artifact") {
81503
+ return {
81504
+ response: await readLinkPreviewArtifact(response),
81505
+ answered: true
81506
+ };
81507
+ }
80944
81508
  if (request.op === "team_bridge.owner_audit.attachment") {
80945
81509
  return {
80946
81510
  response: await readOwnerAuditAttachment(response),
@@ -81819,6 +82383,48 @@ function withoutAgentShellMarker(env) {
81819
82383
  const launchEnv = {
81820
82384
  ...process.env
81821
82385
  };
82386
+ const ATTACH_BACKEND_URL_VARIABLE = "LOCAL_OPERATOR_UI_ATTACH_BACKEND_URL";
82387
+ const ATTACH_BACKEND_TOKEN_VARIABLE = "LOCAL_OPERATOR_DESKTOP_TOKEN";
82388
+ function resolveBackendAttach(launch, credentials = launch) {
82389
+ const rawUrl = launch[ATTACH_BACKEND_URL_VARIABLE]?.trim();
82390
+ if (!rawUrl) return { kind: "managed" };
82391
+ const token = credentials[ATTACH_BACKEND_TOKEN_VARIABLE]?.trim();
82392
+ if (!token) {
82393
+ return {
82394
+ kind: "incomplete",
82395
+ reason: "token-missing",
82396
+ detail: `${ATTACH_BACKEND_URL_VARIABLE} names a backend to attach to, but ${ATTACH_BACKEND_TOKEN_VARIABLE} is not set, so this app has no credential for it.`
82397
+ };
82398
+ }
82399
+ let parsed;
82400
+ try {
82401
+ parsed = new URL(rawUrl);
82402
+ } catch {
82403
+ return {
82404
+ kind: "incomplete",
82405
+ reason: "url-invalid",
82406
+ detail: `${ATTACH_BACKEND_URL_VARIABLE} is not a URL (${rawUrl}); expected an origin such as http://127.0.0.1:1111.`
82407
+ };
82408
+ }
82409
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
82410
+ return {
82411
+ kind: "incomplete",
82412
+ reason: "url-invalid",
82413
+ detail: `${ATTACH_BACKEND_URL_VARIABLE} must be http or https, not ${parsed.protocol.replace(":", "")}.`
82414
+ };
82415
+ }
82416
+ if (parsed.pathname !== "/" || parsed.search || parsed.hash) {
82417
+ return {
82418
+ kind: "incomplete",
82419
+ reason: "url-invalid",
82420
+ detail: `${ATTACH_BACKEND_URL_VARIABLE} must be an origin with no path or query (${rawUrl}); expected e.g. http://127.0.0.1:1111.`
82421
+ };
82422
+ }
82423
+ return { kind: "attach", baseUrl: parsed.origin };
82424
+ }
82425
+ function resolveBackendAttachForThisProcess() {
82426
+ return resolveBackendAttach(launchEnv, process.env);
82427
+ }
81822
82428
  const LOG_DIR_ENV = "LOCAL_OPERATOR_LOG_DIR";
81823
82429
  function logDirOverride(value) {
81824
82430
  const requested = value?.trim();
@@ -83597,6 +84203,17 @@ function classifyDesktopAnswer(status2) {
83597
84203
  if (status2 === 401 || status2 === 403) return "refused";
83598
84204
  return "unusable";
83599
84205
  }
84206
+ function originPort(origin) {
84207
+ try {
84208
+ const parsed = new URL(origin);
84209
+ if (parsed.port) return Number(parsed.port);
84210
+ if (parsed.protocol === "https:") return 443;
84211
+ if (parsed.protocol === "http:") return 80;
84212
+ return null;
84213
+ } catch {
84214
+ return null;
84215
+ }
84216
+ }
83600
84217
  class BackendServiceManager {
83601
84218
  process = null;
83602
84219
  isRunning = false;
@@ -83683,6 +84300,29 @@ class BackendServiceManager {
83683
84300
  * this field is that this class of failure is not a reason to take the app down.
83684
84301
  */
83685
84302
  spawnRefusals = null;
84303
+ /**
84304
+ * The backend this LAUNCH named, when it named one (`./attach-backend`). Null on
84305
+ * every ordinary launch, and that null is what keeps this class's behaviour
84306
+ * byte-for-byte what it was.
84307
+ *
84308
+ * It is a second fact beside `remoteConfigured` rather than a use of it. The
84309
+ * remote flag answers "was the configured URL deliberately not local", and it
84310
+ * drives prose ("the configured remote server") and the no-spawn branch; an
84311
+ * attach target is typically LOCAL - a daemon a rig or the operator started on
84312
+ * 127.0.0.1 - and calling that remote would be a false sentence in the log, the
84313
+ * banner and the update plan.
84314
+ */
84315
+ attachTarget = null;
84316
+ /**
84317
+ * Why this launch's named backend could not be attached to, in words a person
84318
+ * can act on. Null when it could, or when nothing was named.
84319
+ *
84320
+ * Kept because the caller must NOT fall back to installing a runtime when an
84321
+ * attach fails: `src/main/index.ts` reads this to say what happened, and a
84322
+ * silent "no backend" is the state that would otherwise walk into the
84323
+ * installer. Never holds a token.
84324
+ */
84325
+ attachFailure = null;
83686
84326
  remoteConfigured = false;
83687
84327
  /**
83688
84328
  * The last address this app served on that was NOT the one it is configured for,
@@ -84212,6 +84852,13 @@ class BackendServiceManager {
84212
84852
  );
84213
84853
  }
84214
84854
  this.configuredUrl = this.backendUrl;
84855
+ const attachTarget = options.attach?.kind === "attach" ? options.attach.baseUrl : null;
84856
+ if (attachTarget) {
84857
+ this.attachTarget = attachTarget;
84858
+ this.backendUrl = attachTarget;
84859
+ this.configuredUrl = attachTarget;
84860
+ this.port = originPort(attachTarget) ?? this.port;
84861
+ }
84215
84862
  this.venvPath = managedVenvPath({
84216
84863
  platform: process.platform,
84217
84864
  home: electron.app.getPath("home"),
@@ -84748,7 +85395,7 @@ class BackendServiceManager {
84748
85395
  * forbidden from spawning is still allowed to discover).
84749
85396
  */
84750
85397
  async discoverAndAttach() {
84751
- const adopted = await this.adoptFirstUsableDaemon();
85398
+ const adopted = this.attachTarget ? await this.attachToConfiguredBackend(this.attachTarget) : await this.adoptFirstUsableDaemon();
84752
85399
  if (adopted) this.startHealthCheck();
84753
85400
  return adopted;
84754
85401
  }
@@ -84971,6 +85618,89 @@ class BackendServiceManager {
84971
85618
  return { verdict: "unreachable" };
84972
85619
  }
84973
85620
  }
85621
+ /**
85622
+ * Attach to the backend this LAUNCH named, or say exactly why it cannot.
85623
+ *
85624
+ * WHY THIS IS NOT `adoptFirstUsableDaemon()`. Discovery answers "which daemon on
85625
+ * this machine is mine, and which of these may I drive" by ranking serve
85626
+ * records. A launch that names an address has already answered both questions,
85627
+ * and it has answered them about a daemon that need not have a record at all - a
85628
+ * rig starts `lop serve` with its own config dir - so running discovery would
85629
+ * either find nothing (and invite the installer) or find some OTHER daemon and
85630
+ * quietly become about that one. What is worth keeping from discovery is its
85631
+ * evidence discipline, and that is what this uses: an identity from the process
85632
+ * itself (`probeUnidentified`) and a credential actually accepted
85633
+ * (`probeCandidate`), both against the named address.
85634
+ *
85635
+ * NO FALLBACK BY DESIGN. Every failure returns false with `attachFailure` set;
85636
+ * nothing here spawns, installs, or adopts a neighbour, because a caller that
85637
+ * asked for one specific backend and silently got another is measuring the
85638
+ * wrong thing - and the caller that matters is a QA rig whose evidence would
85639
+ * then be about a daemon it never chose.
85640
+ */
85641
+ async attachToConfiguredBackend(address) {
85642
+ this.attachFailure = null;
85643
+ const token = this.desktopToken;
85644
+ if (!token) {
85645
+ this.attachFailure = `This launch named ${address} as its backend, but this app holds no desktop credential for it (${ATTACH_BACKEND_TOKEN_VARIABLE} is unset), so it cannot authenticate.`;
85646
+ logger.error(this.attachFailure, LogFileType.BACKEND);
85647
+ return false;
85648
+ }
85649
+ const occupant = await probeUnidentified(address);
85650
+ if (!occupant.identity) {
85651
+ this.attachFailure = `${address} was named as this launch's backend, but ${HEALTH_PATH$1} did not identify a Local Operator daemon there (${occupant.detail}).`;
85652
+ logger.error(this.attachFailure, LogFileType.BACKEND);
85653
+ return false;
85654
+ }
85655
+ const identity2 = occupant.identity;
85656
+ const probe = await this.probeCandidate(address, token);
85657
+ if (probe.verdict === "refused") {
85658
+ this.attachFailure = `The Local Operator daemon at ${address} (v${identity2.version || "unknown"}) refused this app's desktop credential (HTTP ${probe.status}). Start it with the same ${ATTACH_BACKEND_TOKEN_VARIABLE} this app holds.`;
85659
+ logger.error(this.attachFailure, LogFileType.BACKEND);
85660
+ return false;
85661
+ }
85662
+ if (probe.verdict !== "accepted") {
85663
+ this.attachFailure = probe.verdict === "unusable" ? `The Local Operator daemon at ${address} answered the desktop request with HTTP ${probe.status}, so it cannot be driven from here.` : `The Local Operator daemon at ${address} identified itself but stopped answering the desktop request.`;
85664
+ logger.error(this.attachFailure, LogFileType.BACKEND);
85665
+ return false;
85666
+ }
85667
+ const previousUrl = this.backendUrl;
85668
+ this.backendUrl = address;
85669
+ this.port = originPort(address) ?? this.port;
85670
+ this.attachedRecord = null;
85671
+ this.isExternalBackend = true;
85672
+ this.startupMode = "EXISTING_SERVER";
85673
+ this.desktopToken = token;
85674
+ this.attachDaemon(
85675
+ {
85676
+ url: address,
85677
+ instanceId: identity2.instanceId,
85678
+ pid: identity2.pid,
85679
+ version: identity2.version,
85680
+ prefix: identity2.prefix,
85681
+ installKind: identity2.installKind
85682
+ },
85683
+ { owned: false }
85684
+ );
85685
+ logger.info(
85686
+ `Attached to the backend this launch named: ${address} (pid ${identity2.pid}, v${identity2.version || "unknown"}, ${identity2.installKind || "kind unknown"})${previousUrl !== address ? ` - backend URL moved from ${previousUrl}` : ""}`,
85687
+ LogFileType.BACKEND
85688
+ );
85689
+ this.notifyStatus();
85690
+ this.notifyBackendReady();
85691
+ return true;
85692
+ }
85693
+ /**
85694
+ * Why this launch's named backend could not be attached to, in words; null when
85695
+ * it was attached or when nothing was named.
85696
+ *
85697
+ * The caller must use this instead of falling through to the installer: a named
85698
+ * backend that cannot be reached is an error to report, never a reason to
85699
+ * download a runtime.
85700
+ */
85701
+ lastAttachFailure() {
85702
+ return this.attachFailure;
85703
+ }
84974
85704
  /**
84975
85705
  * Adopt a validated, usable daemon: rotate onto it and publish the state.
84976
85706
  *
@@ -85211,8 +85941,8 @@ class BackendServiceManager {
85211
85941
  return true;
85212
85942
  }
85213
85943
  if (epoch !== this.startEpoch || this.isAppClosing) return false;
85214
- if (!this.managerMaySpawn || this.remoteConfigured) {
85215
- const noSpawnReason = this.managerMaySpawn ? `the configured target (${this.backendUrl}) is remote` : "VITE_DISABLE_BACKEND_MANAGER=true";
85944
+ if (!this.managerMaySpawn || this.remoteConfigured || this.attachTarget) {
85945
+ const noSpawnReason = this.attachTarget ? `this launch named the backend to attach to (${this.attachTarget})` : this.managerMaySpawn ? `the configured target (${this.backendUrl}) is remote` : "VITE_DISABLE_BACKEND_MANAGER=true";
85216
85946
  logger.info(
85217
85947
  `No daemon discovered, and this app is configured not to spawn one (${noSpawnReason}).`,
85218
85948
  LogFileType.BACKEND
@@ -86004,11 +86734,11 @@ class BackendServiceManager {
86004
86734
  if (!expected) {
86005
86735
  const ok = await this.checkHealth();
86006
86736
  if (ok) return { kind: "identified" };
86007
- const failure = this.lastHealthFailure;
86737
+ const failure2 = this.lastHealthFailure;
86008
86738
  return {
86009
- kind: failure === null || failure === "refused" ? "failed" : "unanswered",
86010
- cause: failure ?? "other",
86011
- detail: failure === null ? `${this.backendUrl}${HEALTH_PATH$1} answered a status this app does not accept` : `No answer from ${this.backendUrl}${HEALTH_PATH$1}`
86739
+ kind: failure2 === null || failure2 === "refused" ? "failed" : "unanswered",
86740
+ cause: failure2 ?? "other",
86741
+ detail: failure2 === null ? `${this.backendUrl}${HEALTH_PATH$1} answered a status this app does not accept` : `No answer from ${this.backendUrl}${HEALTH_PATH$1}`
86012
86742
  };
86013
86743
  }
86014
86744
  const probe = await probeIdentity(this.backendUrl, expected, {
@@ -87589,14 +88319,14 @@ class BackendInstaller {
87589
88319
  if (!this.hasLivePreparationWindow()) return;
87590
88320
  const subject = `${captured}
87591
88321
  ${error instanceof Error ? error.message : String(error ?? "")}`;
87592
- const failure = {
88322
+ const failure2 = {
87593
88323
  phase: this.lastPhase,
87594
88324
  reason: setupFailureCause(subject) ?? installFailureSentence(this.lastPhase),
87595
88325
  detail,
87596
88326
  exitCode
87597
88327
  };
87598
88328
  this.failureOnScreen = true;
87599
- this.sendInstallProgress({ kind: "failed", phase: failure.phase, failure });
88329
+ this.sendInstallProgress({ kind: "failed", phase: failure2.phase, failure: failure2 });
87600
88330
  }
87601
88331
  /**
87602
88332
  * Wait for the window to settle a failure it is showing.
@@ -112850,9 +113580,9 @@ class BrowserHost {
112850
113580
  * something, and presenting one as a failure would make the panel cry wolf on
112851
113581
  * every redirect (see `isReportableLoadFailure`).
112852
113582
  */
112853
- recordLoadFailure(tabId, failure) {
113583
+ recordLoadFailure(tabId, failure2) {
112854
113584
  if (!this.registry.get(tabId)) return;
112855
- this.loadFailures.set(tabId, failure);
113585
+ this.loadFailures.set(tabId, failure2);
112856
113586
  this.onChanged();
112857
113587
  }
112858
113588
  /** The next navigation on this tab is under way, so the last failure is stale. */
@@ -115075,7 +115805,7 @@ class StartupRollback {
115075
115805
  }
115076
115806
  const MAX_START_ATTEMPTS = 3;
115077
115807
  async function startWithRetries(options) {
115078
- let failure = new Error("The browser window closed before startup.");
115808
+ let failure2 = new Error("The browser window closed before startup.");
115079
115809
  for (let attempt = 1; attempt <= MAX_START_ATTEMPTS; attempt += 1) {
115080
115810
  if (options.cancelled()) break;
115081
115811
  options.publish({
@@ -115088,7 +115818,7 @@ async function startWithRetries(options) {
115088
115818
  try {
115089
115819
  return await options.start();
115090
115820
  } catch (error) {
115091
- failure = error;
115821
+ failure2 = error;
115092
115822
  options.log(
115093
115823
  `[browser] startup attempt ${attempt}/${MAX_START_ATTEMPTS} failed: ${String(error)}`
115094
115824
  );
@@ -115104,7 +115834,7 @@ async function startWithRetries(options) {
115104
115834
  // idempotent on re-registration, which is what makes the control safe.
115105
115835
  canRetry: true
115106
115836
  });
115107
- throw failure;
115837
+ throw failure2;
115108
115838
  }
115109
115839
  function numberOrThrow(value, name) {
115110
115840
  if (typeof value !== "number" || !Number.isInteger(value)) {
@@ -119111,7 +119841,7 @@ function isAdmittedSender(event, admitted) {
119111
119841
  (candidate) => candidate.window !== null && !candidate.window.isDestroyed() && event.sender === candidate.window.webContents && event.senderFrame === candidate.window.webContents.mainFrame && trustedDesktopFrame(event.senderFrame.url, candidate.url)
119112
119842
  );
119113
119843
  }
119114
- function registerDesktopIPC(window, expectedUrl, request, streams, media, notifier, noteLeftSession, onKeymapSettingEdited, additionalWindows, supplementMounts2, teamBridgeNotifier, onLanguageSettingEdited, admitDesktopRequest) {
119844
+ function registerDesktopIPC(window, expectedUrl, request, streams, media, notifier, noteLeftSession, onKeymapSettingEdited, additionalWindows, supplementMounts2, teamBridgeNotifier, onLanguageSettingEdited, admitDesktopRequest, linkPreview) {
119115
119845
  const opened = /* @__PURE__ */ new Map();
119116
119846
  function authorize(event) {
119117
119847
  const admitted = [
@@ -119233,6 +119963,16 @@ function registerDesktopIPC(window, expectedUrl, request, streams, media, notifi
119233
119963
  return media(input, payload);
119234
119964
  });
119235
119965
  }
119966
+ if (linkPreview) {
119967
+ electron.ipcMain.handle(LINK_PREVIEW_RESOLVE_CHANNEL, (event, input) => {
119968
+ authorize(event);
119969
+ return linkPreview.resolve(input);
119970
+ });
119971
+ electron.ipcMain.handle(LINK_PREVIEW_ARTIFACT_CHANNEL, (event, input) => {
119972
+ authorize(event);
119973
+ return linkPreview.artifact(input);
119974
+ });
119975
+ }
119236
119976
  electron.ipcMain.handle(
119237
119977
  "desktop-open-authorization",
119238
119978
  async (event, operationId, reopen = false) => {
@@ -120501,6 +121241,233 @@ function isProcessAlive(pid) {
120501
121241
  return error.code !== "ESRCH";
120502
121242
  }
120503
121243
  }
121244
+ const ABSENT_REASONS = /* @__PURE__ */ new Set([
121245
+ "cap",
121246
+ "no-metadata",
121247
+ "local-or-private",
121248
+ "unsupported-scheme",
121249
+ "blocked-host",
121250
+ "content-type",
121251
+ "too-large",
121252
+ "not-html",
121253
+ "disabled"
121254
+ ]);
121255
+ const FORGET_INDEX_LIMIT = 256;
121256
+ class ForgetIndex {
121257
+ ids = /* @__PURE__ */ new Map();
121258
+ record(accountFingerprint, url, artifactIds) {
121259
+ if (artifactIds.length === 0) return;
121260
+ const key = previewKeyFor(accountFingerprint, url);
121261
+ this.ids.delete(key);
121262
+ this.ids.set(key, artifactIds);
121263
+ while (this.ids.size > FORGET_INDEX_LIMIT) {
121264
+ const oldest = this.ids.keys().next();
121265
+ if (oldest.done === true) break;
121266
+ this.ids.delete(oldest.value);
121267
+ }
121268
+ }
121269
+ /** The ids this preview was holding, and forget them: one refusal per preview
121270
+ * needs them once, and a later resolve re-records a fresh answer. */
121271
+ take(accountFingerprint, url) {
121272
+ const key = previewKeyFor(accountFingerprint, url);
121273
+ const held = this.ids.get(key);
121274
+ this.ids.delete(key);
121275
+ return held ?? [];
121276
+ }
121277
+ }
121278
+ function boundedString(value, max) {
121279
+ if (typeof value !== "string") return null;
121280
+ const trimmed = value.trim();
121281
+ if (trimmed.length === 0 || trimmed.length > max) return null;
121282
+ return trimmed;
121283
+ }
121284
+ function isResolveRequest(value) {
121285
+ if (typeof value !== "object" || value === null) return false;
121286
+ const request = value;
121287
+ if (boundedString(request.url, LINK_PREVIEW_MAX_URL_CHARS) === null)
121288
+ return false;
121289
+ if (typeof request.index !== "number" || !Number.isSafeInteger(request.index) || request.index < 0)
121290
+ return false;
121291
+ return boundedString(request.expectedAccountId, LINK_PREVIEW_ACCOUNT_MAX_CHARS) !== null;
121292
+ }
121293
+ function isArtifactRequest(value) {
121294
+ if (typeof value !== "object" || value === null) return false;
121295
+ const request = value;
121296
+ if (typeof request.id !== "string") return false;
121297
+ if (!LINK_PREVIEW_ARTIFACT_ID.test(request.id)) return false;
121298
+ return boundedString(request.expectedAccountId, LINK_PREVIEW_ACCOUNT_MAX_CHARS) !== null;
121299
+ }
121300
+ function optionalText(value) {
121301
+ return typeof value === "string" ? value : null;
121302
+ }
121303
+ function toArtifact(value) {
121304
+ if (typeof value !== "object" || value === null) return null;
121305
+ const artifact = value;
121306
+ if (typeof artifact.id !== "string") return null;
121307
+ if (!LINK_PREVIEW_ARTIFACT_ID.test(artifact.id)) return null;
121308
+ const mime = boundedString(artifact.mime, 128);
121309
+ if (mime === null) return null;
121310
+ return { id: artifact.id, mime };
121311
+ }
121312
+ function toImage(value) {
121313
+ const base = toArtifact(value);
121314
+ if (base === null) return null;
121315
+ const image2 = value;
121316
+ const dimension = (candidate) => typeof candidate === "number" && Number.isInteger(candidate) && candidate > 0 && candidate <= 1e5 ? candidate : null;
121317
+ return {
121318
+ ...base,
121319
+ width: dimension(image2.width),
121320
+ height: dimension(image2.height)
121321
+ };
121322
+ }
121323
+ function toPreview(value) {
121324
+ if (typeof value !== "object" || value === null) return null;
121325
+ const preview = value;
121326
+ const url = boundedString(preview.url, LINK_PREVIEW_MAX_URL_CHARS);
121327
+ if (url === null) return null;
121328
+ const image2 = toImage(preview.image);
121329
+ return {
121330
+ url,
121331
+ // Core omits a field that is absent (`response_model_exclude_none`), so
121332
+ // "not there" and "null" mean the same thing and both become `null` here:
121333
+ // one absence spelling is what the renderer's union declares.
121334
+ title: optionalText(preview.title),
121335
+ description: optionalText(preview.description),
121336
+ siteName: optionalText(preview.siteName),
121337
+ favicon: toArtifact(preview.favicon),
121338
+ image: image2 === null ? null : {
121339
+ id: image2.id,
121340
+ mime: image2.mime,
121341
+ width: image2.width,
121342
+ height: image2.height
121343
+ }
121344
+ };
121345
+ }
121346
+ function absentReason(value) {
121347
+ return typeof value === "string" && ABSENT_REASONS.has(value) ? value : "no-metadata";
121348
+ }
121349
+ function mapResolution(result) {
121350
+ if (typeof result !== "object" || result === null)
121351
+ return { kind: "error", retryable: true };
121352
+ const resolution = result;
121353
+ if (resolution.kind === "ready") {
121354
+ const preview = toPreview(resolution.preview);
121355
+ return preview === null ? { kind: "error", retryable: true } : { kind: "ready", preview };
121356
+ }
121357
+ if (resolution.kind === "absent")
121358
+ return { kind: "absent", reason: absentReason(resolution.reason) };
121359
+ if (resolution.kind === "error")
121360
+ return { kind: "error", retryable: resolution.retryable === true };
121361
+ return { kind: "error", retryable: true };
121362
+ }
121363
+ function retryAfterMs(detail) {
121364
+ if (typeof detail !== "object" || detail === null) return void 0;
121365
+ const seconds = detail.retry_after_seconds;
121366
+ if (typeof seconds !== "number" || !Number.isFinite(seconds))
121367
+ return void 0;
121368
+ if (seconds < 0) return void 0;
121369
+ return Math.min(Math.ceil(seconds * 1e3), 6e4);
121370
+ }
121371
+ function refusalDetail(body2) {
121372
+ if (typeof body2 !== "object" || body2 === null) return void 0;
121373
+ return body2.detail;
121374
+ }
121375
+ function envelopeResult(body2) {
121376
+ if (typeof body2 !== "object" || body2 === null) return void 0;
121377
+ return body2.result;
121378
+ }
121379
+ function artifactRefusalCode(answer) {
121380
+ return answer.kind === "error" ? answer.refusal?.code : void 0;
121381
+ }
121382
+ const RATE_LIMITED = 429;
121383
+ function createLinkPreviewService(options) {
121384
+ const { transport, cache } = options;
121385
+ const forget = new ForgetIndex();
121386
+ async function resolve(input) {
121387
+ if (!isResolveRequest(input))
121388
+ return { kind: "absent", reason: "unsupported-scheme" };
121389
+ const { url, index, expectedAccountId } = input;
121390
+ const accountFingerprint = artifactOwnerFingerprint(expectedAccountId);
121391
+ let answer;
121392
+ try {
121393
+ answer = await transport.request({
121394
+ op: "team_bridge.link_preview.resolve",
121395
+ url,
121396
+ index,
121397
+ expectedAccountId
121398
+ });
121399
+ } catch {
121400
+ return { kind: "error", retryable: true };
121401
+ }
121402
+ if (answer.status === RATE_LIMITED) {
121403
+ const delay2 = retryAfterMs(refusalDetail(answer.body));
121404
+ return {
121405
+ kind: "error",
121406
+ retryable: true,
121407
+ ...delay2 === void 0 ? {} : { retryAfterMs: delay2 }
121408
+ };
121409
+ }
121410
+ if (answer.status !== 200)
121411
+ return {
121412
+ kind: "error",
121413
+ retryable: !(answer.status >= 400 && answer.status < 500)
121414
+ };
121415
+ const mapped = mapResolution(envelopeResult(answer.body));
121416
+ if (mapped.kind === "ready") {
121417
+ const preview = mapped.preview;
121418
+ forget.record(
121419
+ artifactOwnerFingerprint(expectedAccountId),
121420
+ url,
121421
+ [preview.favicon?.id, preview.image?.id].filter(
121422
+ (candidate) => typeof candidate === "string"
121423
+ )
121424
+ );
121425
+ return mapped;
121426
+ }
121427
+ if (mapped.kind === "absent") {
121428
+ const held = forget.take(accountFingerprint, url);
121429
+ if (held.length > 0) await cache?.drop(held);
121430
+ }
121431
+ return mapped;
121432
+ }
121433
+ async function artifact(input) {
121434
+ if (!isArtifactRequest(input))
121435
+ return { kind: "error", code: "invalid-request", status: 400 };
121436
+ const { id: id2, expectedAccountId } = input;
121437
+ const accountFingerprint = artifactOwnerFingerprint(expectedAccountId);
121438
+ const cached2 = await cache?.read(id2, accountFingerprint);
121439
+ if (cached2 !== void 0 && cached2 !== null)
121440
+ return { kind: "bytes", data: cached2.bytes, mimeType: cached2.mime };
121441
+ let answer;
121442
+ try {
121443
+ answer = await transport.media({
121444
+ op: "team_bridge.link_preview.artifact",
121445
+ id: id2,
121446
+ expectedAccountId
121447
+ });
121448
+ } catch {
121449
+ return { kind: "error", code: "io", status: 503 };
121450
+ }
121451
+ if (answer.kind === "bytes") {
121452
+ await cache?.store(id2, answer.mimeType, answer.data, accountFingerprint);
121453
+ return { kind: "bytes", data: answer.data, mimeType: answer.mimeType };
121454
+ }
121455
+ if (answer.status === 404)
121456
+ return {
121457
+ kind: "error",
121458
+ code: artifactRefusalCode(answer) === "artifact_not_found" ? "not-found" : "io",
121459
+ status: answer.status
121460
+ };
121461
+ if (answer.status === 409)
121462
+ return { kind: "error", code: "account-mismatch", status: 409 };
121463
+ if (answer.status === 401 || answer.status === 403)
121464
+ return { kind: "error", code: "unauthorized", status: answer.status };
121465
+ if (answer.status === 422)
121466
+ return { kind: "error", code: "invalid-request", status: 422 };
121467
+ return { kind: "error", code: "io", status: answer.status };
121468
+ }
121469
+ return { resolve, artifact };
121470
+ }
120504
121471
  function deviceLocaleFor(appLike) {
120505
121472
  const read2 = (value) => {
120506
121473
  if (typeof value === "string")
@@ -122948,8 +123915,8 @@ function reportFromPayload(payload) {
122948
123915
  daemons: daemonEntries
122949
123916
  };
122950
123917
  if (typeof raw.ok === "boolean") report.ok = raw.ok;
122951
- const failure = failureFromPayload(raw.failure);
122952
- if (failure) report.failure = failure;
123918
+ const failure2 = failureFromPayload(raw.failure);
123919
+ if (failure2) report.failure = failure2;
122953
123920
  return report;
122954
123921
  }
122955
123922
  function failureFromPayload(value) {
@@ -131606,7 +132573,11 @@ function createWindow(initialSession = null, openCatalogue = false, request = ow
131606
132573
  const userShellPath = createUserShellPath({
131607
132574
  log: (message) => logger.info(message, LogFileType.BACKEND)
131608
132575
  });
131609
- const backendService = new BackendServiceManager({ userShellPath });
132576
+ const backendAttach = resolveBackendAttachForThisProcess();
132577
+ const backendService = new BackendServiceManager({
132578
+ userShellPath,
132579
+ attach: backendAttach
132580
+ });
131610
132581
  const quitState = createQuitState();
131611
132582
  const relaunchPending = createRelaunchPending();
131612
132583
  const backendInstaller = new BackendInstaller({
@@ -131632,6 +132603,10 @@ const reportBackendFailure = (message, fileType) => {
131632
132603
  }
131633
132604
  electron.dialog.showErrorBox("Backend Error", message);
131634
132605
  };
132606
+ const reportAttachFailure = (detail) => {
132607
+ logger.error(`[attach] ${detail}`, LogFileType.BACKEND);
132608
+ console.error(`[attach] ${detail}`);
132609
+ };
131635
132610
  const reportRaise = (line) => {
131636
132611
  logger.info(`[window-raise] ${line}`, LogFileType.BACKEND);
131637
132612
  };
@@ -131977,6 +132952,11 @@ electron.app.whenReady().then(async () => {
131977
132952
  electron.app.exit(0);
131978
132953
  return;
131979
132954
  }
132955
+ if (backendAttach.kind === "incomplete") {
132956
+ reportAttachFailure(backendAttach.detail);
132957
+ electron.app.exit(1);
132958
+ return;
132959
+ }
131980
132960
  if (holdLaunchForLiveInstall({
131981
132961
  log: (message) => logger.info(message, LogFileType.UPDATE_SERVICE)
131982
132962
  })) {
@@ -132114,8 +133094,23 @@ electron.app.whenReady().then(async () => {
132114
133094
  clear: () => {
132115
133095
  publishBadge({ unreadCount: 0, pending: false }, void 0, false);
132116
133096
  nativeBadge.reset();
133097
+ },
133098
+ // Fire-and-forget: the sign-out must not wait on a directory sweep, and a
133099
+ // clear that fails is retried by the next transition's orphan pass. The
133100
+ // cache is constructed just below this statement — see why there, beside
133101
+ // that construction — and this closure only reaches it when a transition
133102
+ // actually fires, which is after this synchronous block has finished.
133103
+ principalChanged: () => {
133104
+ void linkPreviewArtifacts.clear();
132117
133105
  }
132118
133106
  });
133107
+ const linkPreviewArtifacts = new LinkPreviewArtifactCache({
133108
+ // The documented home: <userData>/cache/link-previews, one file per
133109
+ // artifact id with an `index.json` beside them.
133110
+ dir: path$1.join(electron.app.getPath("userData"), "cache", "link-previews")
133111
+ });
133112
+ void linkPreviewArtifacts.open().catch(() => {
133113
+ });
132119
133114
  refreshAppIconBadge = () => {
132120
133115
  if (process.platform === "win32") nativeBadge.invalidateOverlayTarget();
132121
133116
  appAttention.projection.refresh();
@@ -132495,6 +133490,13 @@ electron.app.whenReady().then(async () => {
132495
133490
  },
132496
133491
  (m) => logger.warn(m, LogFileType.BACKEND)
132497
133492
  );
133493
+ const linkPreview = createLinkPreviewService({
133494
+ transport: {
133495
+ request: (input) => sendDesktop(input),
133496
+ media: (input) => backendService.requestDesktopMedia(input, null)
133497
+ },
133498
+ cache: linkPreviewArtifacts
133499
+ });
132498
133500
  registerDesktopIPC(
132499
133501
  () => mainWindow,
132500
133502
  rendererUrl,
@@ -132548,7 +133550,13 @@ electron.app.whenReady().then(async () => {
132548
133550
  () => {
132549
133551
  void mainLocale.refresh();
132550
133552
  },
132551
- (input) => recordingShortcut.admit(input)
133553
+ (input) => recordingShortcut.admit(input),
133554
+ /*
133555
+ * The link-preview proxy, LAST for the reason the signature's own note gives:
133556
+ * every earlier caller passes these positionally. It rides the same sender
133557
+ * gate as every other channel above it.
133558
+ */
133559
+ linkPreview
132552
133560
  );
132553
133561
  const recordingSenders = () => [
132554
133562
  ...mainWindow === null ? [] : [{ window: mainWindow, url: rendererUrl }],
@@ -132624,9 +133632,9 @@ electron.app.whenReady().then(async () => {
132624
133632
  async (_, filePath) => {
132625
133633
  const resolved = resolveUserPath(filePath);
132626
133634
  try {
132627
- const failure = await electron.shell.openPath(resolved);
132628
- if (failure) {
132629
- return { ok: false, resolved, error: failure };
133635
+ const failure2 = await electron.shell.openPath(resolved);
133636
+ if (failure2) {
133637
+ return { ok: false, resolved, error: failure2 };
132630
133638
  }
132631
133639
  return { ok: true, resolved };
132632
133640
  } catch (error) {
@@ -132940,6 +133948,13 @@ electron.app.whenReady().then(async () => {
132940
133948
  });
132941
133949
  const isBackendManagerDisabled = process.env.VITE_DISABLE_BACKEND_MANAGER === "true";
132942
133950
  const hasExternalBackend = await backendService.checkExistingBackend();
133951
+ if (backendAttach.kind === "attach" && !hasExternalBackend) {
133952
+ reportAttachFailure(
133953
+ backendService.lastAttachFailure() ?? `This launch named ${backendAttach.baseUrl} as its backend, but nothing was attached to it.`
133954
+ );
133955
+ electron.app.exit(1);
133956
+ return;
133957
+ }
132943
133958
  if (hasExternalBackend && isBackendManagerDisabled) {
132944
133959
  logger.info(
132945
133960
  "Discovered a daemon; the backend manager is configured not to spawn or kill one.",