@openchambery/web 1.19.11 → 1.19.13-beta.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 (123) hide show
  1. package/dist/assets/{AgentAvatar-CX0a1rKE.js → AgentAvatar-CiQIIM0d.js} +1 -1
  2. package/dist/assets/AssistantView-YmeyxehG.js +2 -0
  3. package/dist/assets/{DiagramView-BQO1cBLs.js → DiagramView-BpZb-G9P.js} +1 -1
  4. package/dist/assets/{FadeInOnReveal-CTlNE4Hg.js → FadeInOnReveal-nf6-ZCrs.js} +1 -1
  5. package/dist/assets/{Icon-BYM02QyU.js → Icon-CeKHYyKZ.js} +1 -1
  6. package/dist/assets/MarkdownRenderer-wpeGdciL.js +2 -0
  7. package/dist/assets/{MarkdownRendererImpl--takeMXN.js → MarkdownRendererImpl-Peu0GVSQ.js} +1 -1
  8. package/dist/assets/{MarkstreamRendererImpl-DGSqWcPN.js → MarkstreamRendererImpl-B-odd2Gz.js} +1 -1
  9. package/dist/assets/MobileDetailNavigation-CtYke_1C.js +1 -0
  10. package/dist/assets/{MobileShareBridge-D-BUjACe.js → MobileShareBridge-DIfOl8EZ.js} +3 -3
  11. package/dist/assets/MobileSurface-_KoX75Ff.js +2 -0
  12. package/dist/assets/{MultiRunWindow-BNR9ZWmD.js → MultiRunWindow-BT5Dwgzu.js} +1 -1
  13. package/dist/assets/{OnboardingScreen-DS2nugLX.js → OnboardingScreen-BPusUgFG.js} +1 -1
  14. package/dist/assets/{OverlayScrollbar-KUpvYHdv.js → OverlayScrollbar-DUghqFGg.js} +1 -1
  15. package/dist/assets/{SettingsView-DGerg-C2.js → SettingsView-BwQpbIZl.js} +11 -11
  16. package/dist/assets/{SettingsWindow-CSpd5JbJ.js → SettingsWindow-DfEGfyr8.js} +1 -1
  17. package/dist/assets/{TerminalView-DS-oUxJr.js → TerminalView-8402vpcO.js} +1 -1
  18. package/dist/assets/{ToolOutputDialog-Q1k9-IaY.js → ToolOutputDialog-B5RdkhsG.js} +1 -1
  19. package/dist/assets/{appThemeRegistry-CG7D-3-q.js → appThemeRegistry-CIZ-shMD.js} +1 -1
  20. package/dist/assets/{button-C0cth9tl.js → button-DFPOdZ0g.js} +1 -1
  21. package/dist/assets/{clipboard-DJ4nQEuY.js → clipboard-C05anBwU.js} +1 -1
  22. package/dist/assets/{collapsible-DFT9cE80.js → collapsible-oGbEvbe1.js} +1 -1
  23. package/dist/assets/{context-menu-CAp74NfV.js → context-menu-DGz4_2hs.js} +1 -1
  24. package/dist/assets/{desktopHosts-Dc2PS66M.js → desktopHosts-BVJXQq1S.js} +1 -1
  25. package/dist/assets/{desktopRelayRestore-T9y0orqa.js → desktopRelayRestore-RDfuj1M7.js} +1 -1
  26. package/dist/assets/{diagram-BryzMuta.js → diagram-Csk5GpDC.js} +1 -1
  27. package/dist/assets/{dialog-CgbV5ljg.js → dialog-rrqB-H6q.js} +1 -1
  28. package/dist/assets/{es-BHqnSjoZ.js → es-FE0sJ9EC.js} +1 -1
  29. package/dist/assets/{fileQueries-BY-9OWzp.js → fileQueries-BcdWOPlD.js} +1 -1
  30. package/dist/assets/{fr-BfrlJY9i.js → fr-DNDCSfGt.js} +1 -1
  31. package/dist/assets/{gitApi-Cr-joUEw.js → gitApi-_P0FsoXe.js} +1 -1
  32. package/dist/assets/{input-DFLpqjGR.js → input-BO3r20op.js} +1 -1
  33. package/dist/assets/{insertionBoundaries-X0xbikAA.js → insertionBoundaries-CWoioTdE.js} +1 -1
  34. package/dist/assets/{ja-DP-7qt-x.js → ja-BDwrk0cM.js} +1 -1
  35. package/dist/assets/{ko-E2B5vGQP.js → ko-BeeU2o4I.js} +1 -1
  36. package/dist/assets/{main-D0L7fIg3.js → main-CLj_WS1o.js} +2 -2
  37. package/dist/assets/{main-BI7fNQoi.js → main-CnSZ89pD.js} +4 -4
  38. package/dist/assets/{markdown-worker-CTsrtpPh.js → markdown-worker-CZWE1F1M.js} +1 -1
  39. package/dist/assets/{markdownHeightCache-CYDlisxr.js → markdownHeightCache-Cdd3hkMl.js} +1 -1
  40. package/dist/assets/{markdownTheme-DyJ4Gfcj.js → markdownTheme-DIB8WVmz.js} +1 -1
  41. package/dist/assets/miniChat-B9c3y2pD.js +2 -0
  42. package/dist/assets/{mobile-OcCu_0mG.js → mobile-DvbXUfNS.js} +2 -2
  43. package/dist/assets/{multirun-B0G_BEIN.js → multirun-CxhTsmRq.js} +1 -1
  44. package/dist/assets/{persistence-DdUac14I.js → persistence-CVTWFaqe.js} +2 -2
  45. package/dist/assets/{pl-r8X5gRM5.js → pl-BYuzpcI5.js} +1 -1
  46. package/dist/assets/{platform-B4KKLnZ5.js → platform-BY_Gtsqr.js} +1 -1
  47. package/dist/assets/{projectMeta-BNOzn1QS.js → projectMeta-Dl5iPCB6.js} +1 -1
  48. package/dist/assets/{pt-BR-DcpdXCf5.js → pt-BR-Bn7cwEzv.js} +1 -1
  49. package/dist/assets/{renderElectronMiniChatApp-BREc3uhX.js → renderElectronMiniChatApp-CkJ51qCh.js} +2 -2
  50. package/dist/assets/renderMobileApp-DcjQPhWw.js +28 -0
  51. package/dist/assets/{runtimeConfig-P8nVMYzE.js → runtimeConfig-Bsk2kWsW.js} +1 -1
  52. package/dist/assets/runtimeEndpointReset-BBLFgl85.js +147 -0
  53. package/dist/assets/{sessionChangeSummary-hVby3sJk.js → sessionChangeSummary-DDVT7O5J.js} +1 -1
  54. package/dist/assets/{sessionLookup-C_9-9ggp.js → sessionLookup-C8VZn0gJ.js} +1 -1
  55. package/dist/assets/{sortable-tabs-strip-C8_9kHqu.js → sortable-tabs-strip-s7UUxsa6.js} +1 -1
  56. package/dist/assets/src-BpHDMgud.css +2 -0
  57. package/dist/assets/{store-BDFdnk6l.js → store-n94dSb3M.js} +2 -2
  58. package/dist/assets/{terminalApi-947l7Ra3.js → terminalApi-C54_rKEK.js} +1 -1
  59. package/dist/assets/{textarea-Cgo_nWUU.js → textarea-BjX-KhMN.js} +1 -1
  60. package/dist/assets/{tooltip-BifLJ8o0.js → tooltip-CQGqGAG_.js} +1 -1
  61. package/dist/assets/{uk-Di0vl9V-.js → uk-CwpbHEa3.js} +1 -1
  62. package/dist/assets/{url-Pk6tQ1EZ.js → url-BMjqccCo.js} +1 -1
  63. package/dist/assets/{useAppFontEffects-CEmOsrr6.js → useAppFontEffects-BIFw36SA.js} +5 -5
  64. package/dist/assets/{useAssistantUIStore-me6s63b2.js → useAssistantUIStore-Cg9bsT4b.js} +1 -1
  65. package/dist/assets/{useDesktopWindowControlsLayout-CxaK-zXh.js → useDesktopWindowControlsLayout-DoygEcN4.js} +1 -1
  66. package/dist/assets/{useEffectiveDirectory-BIwv5r5l.js → useEffectiveDirectory-DJSYYkVp.js} +1 -1
  67. package/dist/assets/{useFontPreferences-BCOBlaAd.js → useFontPreferences-B5_apbBC.js} +1 -1
  68. package/dist/assets/{useMobileNavigationStore-DHm5kZPx.js → useMobileNavigationStore-DuTu0Mzh.js} +5 -5
  69. package/dist/assets/{useSessionAutoCleanup-CPLP9KWH.js → useSessionAutoCleanup-C-L9teva.js} +1 -1
  70. package/dist/assets/{useUIStore-CuaA8-Hp.js → useUIStore-DwpQTjLO.js} +1 -1
  71. package/dist/assets/{useWorkerHighlightedLines-CZ4ZTWEH.js → useWorkerHighlightedLines-DxTfgdEi.js} +1 -1
  72. package/dist/assets/{utils-BiK3tBGM.js → utils-81nUI_xp.js} +1 -1
  73. package/dist/assets/{zh-CN-coFCfeQE.js → zh-CN-BpzFZ-LU.js} +1 -1
  74. package/dist/assets/{zh-TW-oDRZ1-yb.js → zh-TW-Bopgc5Eo.js} +1 -1
  75. package/dist/index.html +9 -9
  76. package/dist/mini-chat.html +9 -9
  77. package/dist/mobile.html +9 -9
  78. package/package.json +1 -1
  79. package/server/index.js +19 -0
  80. package/server/lib/assistants/DOCUMENTATION.md +21 -6
  81. package/server/lib/assistants/assign.js +455 -30
  82. package/server/lib/assistants/assign.test.js +351 -0
  83. package/server/lib/assistants/contact-active-turn.http.test.js +134 -0
  84. package/server/lib/assistants/contact-store.js +64 -0
  85. package/server/lib/assistants/contact-store.test.js +12 -0
  86. package/server/lib/assistants/contact-tools.js +216 -25
  87. package/server/lib/assistants/contact-tools.test.js +167 -0
  88. package/server/lib/assistants/contracts.js +2 -2
  89. package/server/lib/assistants/harness.js +20 -3
  90. package/server/lib/assistants/harness.test.js +120 -1
  91. package/server/lib/assistants/pi-tools.js +50 -3
  92. package/server/lib/assistants/pi-tools.test.js +25 -0
  93. package/server/lib/assistants/service.js +320 -27
  94. package/server/lib/assistants/service.test.js +581 -9
  95. package/server/lib/llm/DOCUMENTATION.md +31 -18
  96. package/server/lib/llm/catalog.js +91 -16
  97. package/server/lib/llm/catalog.test.js +152 -11
  98. package/server/lib/llm/generate.js +43 -7
  99. package/server/lib/llm/generate.test.js +98 -1
  100. package/server/lib/llm/temp-directory.js +34 -13
  101. package/server/lib/llm/temp-directory.test.js +57 -0
  102. package/server/lib/notifications/APNS.md +20 -4
  103. package/server/lib/notifications/DOCUMENTATION.md +5 -0
  104. package/server/lib/notifications/apns-runtime.js +136 -18
  105. package/server/lib/notifications/apns-runtime.test.js +128 -0
  106. package/server/lib/notifications/apns-titles.js +21 -1
  107. package/server/lib/notifications/live-activity-refresh-runtime.js +185 -0
  108. package/server/lib/notifications/live-activity-refresh-runtime.test.js +242 -0
  109. package/server/lib/notifications/runtime.js +93 -2
  110. package/server/lib/notifications/runtime.test.js +167 -4
  111. package/server/lib/opencode/settings-helpers.js +12 -0
  112. package/server/lib/opencode/settings-runtime.js +16 -0
  113. package/server/lib/opencode/settings-runtime.test.js +21 -0
  114. package/server/lib/scheduled-tasks/runtime.js +21 -0
  115. package/server/lib/scheduled-tasks/runtime.test.js +24 -0
  116. package/dist/assets/AssistantView-BwrcqJzu.js +0 -2
  117. package/dist/assets/MarkdownRenderer-C49bfcHx.js +0 -2
  118. package/dist/assets/MobileDetailNavigation-LZU2vFAs.js +0 -1
  119. package/dist/assets/MobileSurface-OAJjAQCZ.js +0 -2
  120. package/dist/assets/miniChat-BJ9AclZX.js +0 -2
  121. package/dist/assets/renderMobileApp-C4igZ42L.js +0 -28
  122. package/dist/assets/runtimeEndpointReset-6lVRspis.js +0 -147
  123. package/dist/assets/src-B-P5qIBc.css +0 -2
@@ -0,0 +1,57 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { afterEach, describe, expect, it } from 'vitest';
4
+ import { ensureLlmTempDirectory, stopLlmTempDirectory } from './temp-directory.js';
5
+
6
+ const readAgent = async (root, agentName) =>
7
+ fs.readFile(path.join(root, '.opencode', 'agent', `${agentName}.md`), 'utf8');
8
+
9
+ afterEach(async () => {
10
+ await stopLlmTempDirectory();
11
+ });
12
+
13
+ describe('ensureLlmTempDirectory', () => {
14
+ it('shares one directory across concurrent first ensures and applies each markdown body', async () => {
15
+ const firstBody = '---\nname: a\n---\nFIRST\n';
16
+ const secondBody = '---\nname: a\n---\nSECOND\n';
17
+ const [first, second] = await Promise.all([
18
+ ensureLlmTempDirectory({ agentName: 'openchamber-llm', agentMarkdown: firstBody }),
19
+ ensureLlmTempDirectory({ agentName: 'openchamber-llm', agentMarkdown: secondBody }),
20
+ ]);
21
+ expect(first).toBe(second);
22
+ const written = await readAgent(first, 'openchamber-llm');
23
+ // Last writer wins; both callers must have completed a full write after settle.
24
+ expect(written === firstBody || written === secondBody).toBe(true);
25
+ expect(written).toMatch(/FIRST|SECOND/);
26
+ });
27
+
28
+ it('refreshes markdown on a warm directory under concurrent ensure', async () => {
29
+ const root = await ensureLlmTempDirectory({
30
+ agentName: 'openchamber-llm',
31
+ agentMarkdown: '---\nname: a\n---\nSEED\n',
32
+ });
33
+ const bodies = Array.from({ length: 8 }, (_, index) => `---\nname: a\n---\nREFRESH-${index}\n`);
34
+ const roots = await Promise.all(
35
+ bodies.map((agentMarkdown) => ensureLlmTempDirectory({ agentName: 'openchamber-llm', agentMarkdown })),
36
+ );
37
+ expect(new Set(roots)).toEqual(new Set([root]));
38
+ const written = await readAgent(root, 'openchamber-llm');
39
+ expect(bodies).toContain(written);
40
+ expect(written).toMatch(/REFRESH-\d+/);
41
+ });
42
+
43
+ it('stop clears the singleton so the next ensure creates a fresh directory', async () => {
44
+ const first = await ensureLlmTempDirectory({
45
+ agentName: 'openchamber-llm',
46
+ agentMarkdown: '---\nname: a\n---\nA\n',
47
+ });
48
+ await stopLlmTempDirectory();
49
+ const second = await ensureLlmTempDirectory({
50
+ agentName: 'openchamber-llm',
51
+ agentMarkdown: '---\nname: a\n---\nB\n',
52
+ });
53
+ expect(second).not.toBe(first);
54
+ await expect(fs.access(first)).rejects.toThrow();
55
+ expect(await readAgent(second, 'openchamber-llm')).toContain('B');
56
+ });
57
+ });
@@ -13,10 +13,12 @@ registered them — so a leaked device token alone can't be used to push.
13
13
  `POST /v1/push/register-token`, signed with its auto-generated ECDSA P-256 key
14
14
  (`getOrCreateRelayKeypair`, persisted in settings like the VAPID keys). The relay records
15
15
  `token → serverId` where `serverId = SHA-256(publicKey)`.
16
- 3. On a trigger (ready/error/question/permission/goal_*), the server composes **generic,
17
- content-free** text — a **locale-specific** scenario title (from `apns-titles.js`, keyed off
18
- the locale stored with each device token at `POST /api/push/apns-token`) + the **session name**
19
- as the body, no model/project/message content — plus a **`badge`** count (see below).
16
+ 3. On a trigger (ready/error/question/permission/goal_*), the server composes **generic,
17
+ content-free** text — a **locale-specific** scenario title (from `apns-titles.js`, keyed off
18
+ the locale stored with each device token at `POST /api/push/apns-token`) + the **session name**
19
+ as the body, no model/project/message content — plus a **`badge`** count (see below).
20
+ Scheduled-task runs add `task_complete` / `task_error` scenario titles (task name as the
21
+ body, error text never crosses), gated by their own settings toggle.
20
22
  **Contact turns are the exception:** APNs keeps the assistant nickname as the title and the
21
23
  spoken message as the body (`preserveAlert`), and forwards `assistantID` so a tap opens that
22
24
  conversation. Tokens are grouped by locale (relay signatures cover `title`, so mixed locales
@@ -60,6 +62,20 @@ dismissalDate?, staleDate?, publicKeyJwk, ts, sig }` signed over
60
62
  Direct mode uses HTTP/2 token auth, `apns-topic: ${bundleId}.push-type.liveactivity`,
61
63
  `apns-push-type: liveactivity`, and no alert.
62
64
 
65
+ While sessions are still working, a periodic refresh
66
+ (`live-activity-refresh-runtime.js`, default every 30s,
67
+ `OPENCHAMBER_LIVE_ACTIVITY_REFRESH_INTERVAL_MS`, `0` disables) recomputes each
68
+ persisted Live Activity snapshot from the authoritative server-side session
69
+ states and pushes an **update** only when something changed — a busy→retry
70
+ transition, a newly visible top-level session, a missed idle completion, or a
71
+ stale row recovering to working. Unchanged snapshots never send, because APNs
72
+ budgets Live Activity updates per hour. Update payloads reuse the signed
73
+ live-activity contract above (`staleDate = updatedAt + 20min`, snapshot `items`
74
+ with `sessionID`/`title`/`status` rows — the same shape the foreground app
75
+ writes via ActivityKit); when the recomputed snapshot has no working row left,
76
+ the refresh sends `end` and clears accepted tokens locally. A tick is a no-op
77
+ (one token-store read) when no device registered a Live Activity token.
78
+
63
79
  The APNs / relay payload **must not** carry `sessionId` or user/session content.
64
80
  `contentState` is only `{ status, eventVersion, updatedAt, endedAt }`.
65
81
  `complete` uses a 15-minute dismissal and `error` a 60-minute dismissal (same as
@@ -10,6 +10,7 @@ This module provides notification message preparation utilities for the web serv
10
10
  - `packages/web/server/lib/notifications/apns-runtime.js`: native iOS APNs device-token persistence + delivery, plus a separate Live Activity token store and `end` send path. Two modes: **relay** (default — sign + POST tokens + generic text to the isolated Push Relay in `packages/relay-server/src/push/`, which holds the project APNs key) and **direct** (fallback — sign ES256 JWT with Node crypto + HTTP/2, when `OPENCHAMBER_PUSH_RELAY_DISABLED=true`). Unless `OPENCHAMBER_PUSH_RELAY_URL` is set, the Host maps the effective Relay `wss`/`ws` URL to the same host as `https`/`http` `/v1/push/send`. Before each relay send, the runtime checks an in-memory registration success cache (keyed by current register URL + token + platform) and only POSTs `/v1/push/register-token` for cache misses; only successfully bound tokens are sent. Switching Relay/Push URL clears that cache so persisted tokens re-bind to the new origin on the next send or `reRegisterAllTokens()`. Each server has an auto-generated ECDSA P-256 keypair (`getOrCreateRelayKeypair`, persisted in settings); it binds tokens on the relay (`/v1/push/register-token`) and signs every relay request, so the relay only delivers to tokens bound to that server. APNs is the native app's sole notification channel (no local notifications) and is NOT gated on UI visibility — iOS suppresses the foreground banner instead. Mobile push carries only generic text (scenario title + session name) — see `APNS.md`. Live Activity tokens are persisted beside alert tokens in the same file (`version` 2, `liveActivityTokensBySession`) without mixing the two token types; v1 files remain readable. Live Activity relay bind/send uses `/v1/push/register-live-activity-token`, `/v1/push/unregister-live-activity-token`, and `/v1/push/live-activity`.
11
11
  - `packages/web/server/lib/notifications/emitter-runtime.js`: desktop/stdout + UI SSE notification emission runtime.
12
12
  - `packages/web/server/lib/notifications/runtime.js`: trigger runtime for OpenCode event-driven notification fanout.
13
+ - `packages/web/server/lib/notifications/live-activity-refresh-runtime.js`: periodic Live Activity snapshot refresh (default 30s, `OPENCHAMBER_LIVE_ACTIVITY_REFRESH_INTERVAL_MS` overrides, `0` disables). Each tick snapshots the authoritative session states once, recomputes every persisted Live Activity token's snapshot, and pushes updates only for real changes — busy→retry transitions, newly visible top-level sessions, idle completions the event path missed, and stale-row recovery. Entries whose recomputed snapshot is unchanged never send (APNs budgets Live Activity updates per hour). Rows for sessions without authoritative server state are preserved as-is; server-side-only sub-states (`permission`/`input`/`tool`) keep their last value while the session stays busy. When no row is working anymore the refresh sends `end` and clears accepted tokens.
13
14
  - `packages/web/server/lib/notifications/template-runtime.js`: notification template variables and session text/title enrichment runtime. Zen-model helpers are retained as compatibility stubs only.
14
15
  - `packages/web/server/lib/notifications/message.js`: helper implementation module.
15
16
  - `packages/web/server/lib/notifications/message.test.js`: unit tests for notification message helpers.
@@ -46,8 +47,11 @@ This module provides notification message preparation utilities for the web serv
46
47
  - `createNotificationTriggerRuntime(dependencies)`: creates runtime-owned debounced trigger handling for OpenCode events.
47
48
  - Returned API:
48
49
  - `maybeSendPushForTrigger(payload)`
50
+ - `resolveLiveActivitySessionCandidate(sessionId)` — sidebar candidate for a new Live Activity refresh row: `{ title, visible }` under the same suppression rules as ordinary push. Cache-first across any cached directory, then the directory-less OpenCode session endpoint; a missing meta resolves as not-visible.
51
+ - `sendScheduledTaskRunNotification({ projectID, taskID, taskName, status, sessionId?, reason, errorMessage? })` — scheduled-tasks runtime callback when a scheduled (non-manual) run settles. Gated by `notifyOnScheduledTasks`; manual runs always skip. Desktop/UI SSE carry the task name (plus error text on failure); push follows the generic contract (`task_complete`/`task_error` scenario titles, task name as APNs body, `scheduled-<projectID>-<taskID>` collapse tag).
49
52
  - Owns:
50
53
  - top-level completion/question/permission trigger routing; completion is the sole task-status notification. Ordinary push is limited to sidebar-visible root sessions. Child/subagent sessions, Assistant bindings (`openchamber.assistant.assistantID` unless `assigned.from === 'contact'`), scheduled-task sessions, small-model system sessions (`metadata.openchamber.smallModel.purpose`), LLM gateway throwaway sessions (`metadata.openchamber.llm.purpose`), and `smartfetch-secondary` titles are suppressed. Contact-assigned workers stay visible and still notify.
54
+ - per-event settings gates: `notifyOnCompletion` (ready), `notifyOnQuestion` (question), `notifyOnPermission` (permission — independent of the question toggle), `notifyOnAssistants` (contact turns), `notifyOnGoals` (goal settle push), `notifyOnScheduledTasks` (scheduled task runs); all default to enabled via the settings migration.
51
55
  - contact-turn notifications (`sendContactTurnNotification`) are a separate SMS-style path: title is the assistant nickname, body is the spoken message text, on desktop / UI SSE / web-push / APNs. APNs does **not** rewrite these into the generic "Task completed" scenario title.
52
56
  - top-level completion/error Live Activity `end` (`sendLiveActivityEnd`), independent of ordinary push settings and UI visibility, with the same hidden-session suppression; duplicate terminal events are idempotent at the token store
53
57
  - session meta cache for sidebar-visibility suppression
@@ -77,6 +81,7 @@ This module provides notification message preparation utilities for the web serv
77
81
  - `addOrUpdateLiveActivityToken(uiSessionToken, token, activityId, sessionId)` — idempotent upsert bound to the UI session + OpenCode `sessionId` + ActivityKit `activityId`. Token refresh replaces that activity's previous token. Caps per UI session and lazily expires stale entries. Binds on the relay (`/v1/push/register-live-activity-token`, `kind: "liveactivity"`). Does not log tokens or session ids.
78
82
  - `removeLiveActivityToken(uiSessionToken, token)` — owning UI session only; unregisters from the relay when no local copies remain.
79
83
  - `sendLiveActivityEnd({ sessionId, status, eventVersion?, endedAt? })` — looks up Live Activity tokens for that OpenCode session and sends `event: "end"` with `contentState` `{ status, eventVersion, updatedAt, endedAt }` only. `complete` dismisses after 15 minutes, `error` after 60 minutes (same as native). `staleDate` (`updatedAt + 20min`) is update-only and omitted on end. `eventVersion` is monotonic per session using current milliseconds. Relay body follows the signed live-activity contract; direct mode uses token auth, topic `${bundleId}.push-type.liveactivity`, `apns-push-type: liveactivity`, and no alert. APNs payloads must not carry `sessionId` or user content. Successfully accepted tokens are cleared locally; failures do not drop alert tokens or block ordinary push.
84
+ - `refreshLiveActivityTokens({ computeSnapshot })` — periodic refresh entrypoint for `live-activity-refresh-runtime.js`. The async `computeSnapshot(entry)` returns `{ items }` (unix seconds) when that entry's snapshot changed or `null` to skip; unchanged entries never send. Changed snapshots bump the aggregate `liveActivityEventVersions` entry, persist, and deliver an `update` (with `staleDate`) grouped by identical snapshot — or an `end` plus local token cleanup once no row is working. Delivery shares the same relay/direct path as `sendLiveActivityEnd`.
80
85
  - `sendApnsToAllUiSessions(payload)` — localizes scenario titles per stored token locale (`apns-titles.js`), groups tokens by locale, then signs + sends (no UI-visibility gate; iOS suppresses the foreground banner). Before a relay send, each token is checked against the in-memory registration success cache for the current register URL; cache hits skip `/v1/push/register-token`, misses are registered with bounded concurrency, and only successfully bound tokens are sent. Switching Relay/Push URL clears that cache so the next send re-binds persisted tokens to the new origin. No-ops with a single warning when APNs is unconfigured. Drops tokens on `410` / `BadDeviceToken` / `Unregistered`. Never sends Live Activity tokens.
81
86
  - `reRegisterAllTokens()` — binds every persisted device token to the current Push origin (same success cache and URL-switch invalidation as send).
82
87
  - `resolveApnsConfig()`
@@ -1120,6 +1120,140 @@ export const createApnsRuntime = (deps) => {
1120
1120
  return entries;
1121
1121
  };
1122
1122
 
1123
+ // Shared Live Activity delivery path (relay register-then-send, or direct APNs).
1124
+ // Returns the tokens APNs accepted; callers decide what an accepted `end` means.
1125
+ const deliverLiveActivityPayload = async (tokens, payload) => {
1126
+ const accepted = [];
1127
+ const relay = await resolveRelayConfig();
1128
+ if (relay) {
1129
+ rememberLiveActivityRelayRegisterUrl(relay.liveActivityRegisterUrl);
1130
+ const outcomes = await mapWithBoundedConcurrency(
1131
+ tokens,
1132
+ RELAY_REGISTER_CONCURRENCY,
1133
+ async (token) => {
1134
+ const registered = await registerLiveActivityTokenWithRelay(token, relay);
1135
+ return registered ? token : null;
1136
+ },
1137
+ );
1138
+ const readyTokens = outcomes.filter((token) => typeof token === 'string');
1139
+ if (readyTokens.length > 0) {
1140
+ accepted.push(...await sendLiveActivityViaRelay(readyTokens, payload, relay));
1141
+ }
1142
+ } else {
1143
+ accepted.push(...await sendLiveActivityViaDirectApns(tokens, payload));
1144
+ }
1145
+ return accepted;
1146
+ };
1147
+
1148
+ // Periodic refresh entrypoint (see live-activity-refresh-runtime.js). For every
1149
+ // persisted Live Activity entry the async `computeSnapshot(entry)` returns the
1150
+ // next snapshot items (unix seconds) or null to skip; unchanged snapshots send
1151
+ // nothing. Changed snapshots bump the aggregate event version, persist, and
1152
+ // deliver an `update` — or an `end` (clearing accepted tokens) once no row is
1153
+ // working anymore.
1154
+ const refreshLiveActivityTokens = async ({ computeSnapshot } = {}) => {
1155
+ if (typeof computeSnapshot !== 'function') return;
1156
+ const now = Date.now();
1157
+ const store = await readTokensFromDisk();
1158
+ const pruned = pruneLiveActivityTokensBySession(store.liveActivityTokensBySession, now);
1159
+ const entries = [];
1160
+ const seen = new Set();
1161
+ for (const record of Object.values(pruned)) {
1162
+ for (const entry of record) {
1163
+ if (seen.has(entry.token)) continue;
1164
+ seen.add(entry.token);
1165
+ entries.push(entry);
1166
+ }
1167
+ }
1168
+ if (entries.length === 0) return;
1169
+
1170
+ const nextItemsByToken = new Map();
1171
+ for (const entry of entries) {
1172
+ let next = null;
1173
+ try {
1174
+ next = await computeSnapshot(entry);
1175
+ } catch {
1176
+ next = null;
1177
+ }
1178
+ if (next && Array.isArray(next.items)) nextItemsByToken.set(entry.token, next.items);
1179
+ }
1180
+ if (nextItemsByToken.size === 0) return;
1181
+
1182
+ const planned = [];
1183
+ let nextVersion = 0;
1184
+ await persistTokenUpdate((current) => {
1185
+ const liveActivityTokensBySession = pruneLiveActivityTokensBySession(
1186
+ current.liveActivityTokensBySession,
1187
+ now,
1188
+ );
1189
+ const previous = current.liveActivityEventVersions?.[LIVE_ACTIVITY_AGGREGATE_SESSION_ID];
1190
+ nextVersion = nextLiveActivityEventVersion(now, previous);
1191
+ let plannedInRun = [];
1192
+ for (const [uiSessionToken, record] of Object.entries(liveActivityTokensBySession)) {
1193
+ const nextRecord = record.map((entry) => {
1194
+ const items = nextItemsByToken.get(entry.token);
1195
+ if (!items) return entry;
1196
+ plannedInRun.push({ token: entry.token, items });
1197
+ return { ...entry, snapshot: items };
1198
+ });
1199
+ liveActivityTokensBySession[uiSessionToken] = nextRecord;
1200
+ }
1201
+ planned.push(...plannedInRun);
1202
+ return {
1203
+ ...current,
1204
+ liveActivityTokensBySession,
1205
+ liveActivityEventVersions: {
1206
+ ...(current.liveActivityEventVersions || {}),
1207
+ [LIVE_ACTIVITY_AGGREGATE_SESSION_ID]: nextVersion,
1208
+ },
1209
+ };
1210
+ });
1211
+ if (planned.length === 0) return;
1212
+
1213
+ // Entries with identical snapshots share one APNs payload.
1214
+ const signatureOf = (items) => items
1215
+ .map((item) => `${item.sessionId}\0${item.title}\0${item.status}\0${item.endedAt ?? ''}`)
1216
+ .join('\n');
1217
+ const groups = new Map();
1218
+ for (const plan of planned) {
1219
+ const working = plan.items.filter((item) => liveActivityItemIsWorking(item.status));
1220
+ const key = signatureOf(plan.items);
1221
+ const group = groups.get(key) ?? { items: plan.items, tokens: [] };
1222
+ group.tokens.push(plan.token);
1223
+ groups.set(key, group);
1224
+ }
1225
+
1226
+ const updatedAtSeconds = now / 1000;
1227
+ const tokensToEnd = [];
1228
+ for (const group of groups.values()) {
1229
+ const working = group.items.filter((item) => liveActivityItemIsWorking(item.status));
1230
+ const isEnd = working.length === 0;
1231
+ const status = isEnd
1232
+ ? (group.items.some((item) => item.status === 'error') ? 'error' : 'complete')
1233
+ : (working[0]?.status || 'working');
1234
+ const payload = {
1235
+ event: isEnd ? 'end' : 'update',
1236
+ contentState: contentStateFromSnapshot(
1237
+ group.items,
1238
+ status,
1239
+ nextVersion,
1240
+ updatedAtSeconds,
1241
+ isEnd ? updatedAtSeconds : undefined,
1242
+ ),
1243
+ ...liveActivityPushDates(isEnd ? 'end' : 'update', status, updatedAtSeconds, now),
1244
+ };
1245
+ let accepted = [];
1246
+ try {
1247
+ accepted = await deliverLiveActivityPayload(group.tokens, payload);
1248
+ } catch (error) {
1249
+ console.warn('[Live Activity] refresh failed:', error?.message ?? error);
1250
+ continue;
1251
+ }
1252
+ if (isEnd && accepted.length > 0) tokensToEnd.push(...accepted);
1253
+ }
1254
+ if (tokensToEnd.length > 0) await removeLiveActivityTokens(tokensToEnd);
1255
+ };
1256
+
1123
1257
  const sendLiveActivityEnd = async ({ sessionId, status, eventVersion, endedAt, title } = {}) => {
1124
1258
  const trimmedSessionId = typeof sessionId === 'string' ? sessionId.trim() : '';
1125
1259
  if (!isLimitedId(trimmedSessionId, MAX_LIVE_ACTIVITY_ID_CHARS)) return;
@@ -1217,24 +1351,7 @@ export const createApnsRuntime = (deps) => {
1217
1351
  const tokens = pendingEntries.map((entry) => entry.token);
1218
1352
  let accepted = [];
1219
1353
  try {
1220
- const relay = await resolveRelayConfig();
1221
- if (relay) {
1222
- rememberLiveActivityRelayRegisterUrl(relay.liveActivityRegisterUrl);
1223
- const outcomes = await mapWithBoundedConcurrency(
1224
- tokens,
1225
- RELAY_REGISTER_CONCURRENCY,
1226
- async (token) => {
1227
- const registered = await registerLiveActivityTokenWithRelay(token, relay);
1228
- return registered ? token : null;
1229
- },
1230
- );
1231
- const readyTokens = outcomes.filter((token) => typeof token === 'string');
1232
- if (readyTokens.length > 0) {
1233
- accepted = await sendLiveActivityViaRelay(readyTokens, payload, relay);
1234
- }
1235
- } else {
1236
- accepted = await sendLiveActivityViaDirectApns(tokens, payload);
1237
- }
1354
+ accepted = await deliverLiveActivityPayload(tokens, payload);
1238
1355
  } catch (error) {
1239
1356
  console.warn('[Live Activity] end failed:', error?.message ?? error);
1240
1357
  return;
@@ -1332,6 +1449,7 @@ export const createApnsRuntime = (deps) => {
1332
1449
  addOrUpdateLiveActivityToken,
1333
1450
  removeLiveActivityToken,
1334
1451
  sendLiveActivityEnd,
1452
+ refreshLiveActivityTokens,
1335
1453
  sendApnsToAllUiSessions,
1336
1454
  reRegisterAllTokens,
1337
1455
  resolveApnsConfig,
@@ -1175,3 +1175,131 @@ describe('apns live activity host-relay compatibility', () => {
1175
1175
  expect(apnsCalls).toHaveLength(0);
1176
1176
  });
1177
1177
  });
1178
+
1179
+ describe('apns live activity refresh', () => {
1180
+ it('sends nothing when no snapshot changed', async () => {
1181
+ const fetchMock = vi.fn(async () => jsonResponse({ ok: true, results: [] }));
1182
+ vi.stubGlobal('fetch', fetchMock);
1183
+ process.env.OPENCHAMBER_PUSH_RELAY_URL = 'https://relay.test/v1/push/send';
1184
+ const deps = makeDeps();
1185
+ const runtime = createApnsRuntime(deps);
1186
+ await runtime.addOrUpdateLiveActivityToken('s1', 'la-token', 'act-1', 'live', [
1187
+ { sessionId: 'ses_1', title: 'One', status: 'working', startedAt: 1 },
1188
+ ]);
1189
+
1190
+ fetchMock.mockClear();
1191
+ await runtime.refreshLiveActivityTokens({ computeSnapshot: async () => null });
1192
+ expect(fetchMock.mock.calls.filter(isLiveActivitySend)).toHaveLength(0);
1193
+ const store = JSON.parse(await deps.fsPromises.readFile('/tmp/apns-tokens.json'));
1194
+ expect(store.liveActivityTokensBySession.s1).toHaveLength(1);
1195
+ });
1196
+
1197
+ it('pushes an update with the recomputed snapshot and bumps the event version monotonically', async () => {
1198
+ const fetchMock = vi.fn(async () => jsonResponse({ ok: true, results: [] }));
1199
+ vi.stubGlobal('fetch', fetchMock);
1200
+ process.env.OPENCHAMBER_PUSH_RELAY_URL = 'https://relay.test/v1/push/send';
1201
+ const deps = makeDeps();
1202
+ const runtime = createApnsRuntime(deps);
1203
+ await runtime.addOrUpdateLiveActivityToken('s1', 'la-token', 'act-1', 'live', [
1204
+ { sessionId: 'ses_1', title: 'One', status: 'working', startedAt: 1 },
1205
+ ]);
1206
+
1207
+ fetchMock.mockClear();
1208
+ await runtime.refreshLiveActivityTokens({
1209
+ computeSnapshot: async () => ({
1210
+ items: [{ sessionId: 'ses_1', title: 'One', status: 'retry', startedAt: 1 }],
1211
+ }),
1212
+ });
1213
+ const sent = JSON.parse(fetchMock.mock.calls.find(isLiveActivitySend)[1].body);
1214
+ expect(sent.tokens).toEqual(['la-token']);
1215
+ expect(sent.event).toBe('update');
1216
+ expect(sent.contentState.status).toBe('retry');
1217
+ expect(sent.contentState.workingCount).toBe(1);
1218
+ expect(sent.contentState.items[0]).toMatchObject({ sessionID: 'ses_1', status: 'retry' });
1219
+ expect(sent.staleDate).toBeGreaterThan(0);
1220
+ expect(sent.dismissalDate).toBeUndefined();
1221
+
1222
+ const store = JSON.parse(await deps.fsPromises.readFile('/tmp/apns-tokens.json'));
1223
+ expect(store.liveActivityTokensBySession.s1[0].snapshot[0].status).toBe('retry');
1224
+ const firstVersion = store.liveActivityEventVersions.live;
1225
+
1226
+ fetchMock.mockClear();
1227
+ await runtime.refreshLiveActivityTokens({
1228
+ computeSnapshot: async () => ({
1229
+ items: [{ sessionId: 'ses_1', title: 'One', status: 'working', startedAt: 1 }],
1230
+ }),
1231
+ });
1232
+ const second = JSON.parse(fetchMock.mock.calls.find(isLiveActivitySend)[1].body);
1233
+ expect(second.contentState.eventVersion).toBeGreaterThan(firstVersion);
1234
+ });
1235
+
1236
+ it('ends and clears the token when nothing is working anymore', async () => {
1237
+ const fetchMock = vi.fn(async () => jsonResponse({ ok: true, results: [] }));
1238
+ vi.stubGlobal('fetch', fetchMock);
1239
+ process.env.OPENCHAMBER_PUSH_RELAY_URL = 'https://relay.test/v1/push/send';
1240
+ const deps = makeDeps();
1241
+ const runtime = createApnsRuntime(deps);
1242
+ await runtime.addOrUpdateLiveActivityToken('s1', 'la-token', 'act-1', 'live', [
1243
+ { sessionId: 'ses_1', title: 'One', status: 'working', startedAt: 1 },
1244
+ ]);
1245
+
1246
+ fetchMock.mockClear();
1247
+ await runtime.refreshLiveActivityTokens({
1248
+ computeSnapshot: async () => ({
1249
+ items: [{ sessionId: 'ses_1', title: 'One', status: 'complete', startedAt: 1, endedAt: 5 }],
1250
+ }),
1251
+ });
1252
+ const sent = JSON.parse(fetchMock.mock.calls.find(isLiveActivitySend)[1].body);
1253
+ expect(sent.event).toBe('end');
1254
+ expect(sent.contentState.status).toBe('complete');
1255
+ expect(sent.dismissalDate).toBeGreaterThan(0);
1256
+ expect(sent.staleDate).toBeUndefined();
1257
+
1258
+ const store = JSON.parse(await deps.fsPromises.readFile('/tmp/apns-tokens.json'));
1259
+ expect(store.liveActivityTokensBySession.s1).toBeUndefined();
1260
+ });
1261
+
1262
+ it('groups entries with identical snapshots into one send and keeps distinct snapshots separate', async () => {
1263
+ const fetchMock = vi.fn(async () => jsonResponse({ ok: true, results: [] }));
1264
+ vi.stubGlobal('fetch', fetchMock);
1265
+ process.env.OPENCHAMBER_PUSH_RELAY_URL = 'https://relay.test/v1/push/send';
1266
+ const runtime = createApnsRuntime(makeDeps());
1267
+ await runtime.addOrUpdateLiveActivityToken('s1', 'la-token-a', 'act-1', 'live', [
1268
+ { sessionId: 'ses_1', title: 'One', status: 'working', startedAt: 1 },
1269
+ ]);
1270
+ await runtime.addOrUpdateLiveActivityToken('s2', 'la-token-b', 'act-2', 'live', [
1271
+ { sessionId: 'ses_2', title: 'Two', status: 'working', startedAt: 2 },
1272
+ ]);
1273
+
1274
+ fetchMock.mockClear();
1275
+ await runtime.refreshLiveActivityTokens({
1276
+ computeSnapshot: async (entry) => {
1277
+ if (entry.token === 'la-token-a') {
1278
+ return { items: [{ sessionId: 'ses_1', title: 'One', status: 'retry', startedAt: 1 }] };
1279
+ }
1280
+ return { items: [{ sessionId: 'ses_2', title: 'Two', status: 'retry', startedAt: 2 }] };
1281
+ },
1282
+ });
1283
+ const sends = fetchMock.mock.calls.filter(isLiveActivitySend).map((call) => JSON.parse(call[1].body));
1284
+ expect(sends).toHaveLength(2);
1285
+ });
1286
+
1287
+ it('treats a computeSnapshot rejection as skip, not failure', async () => {
1288
+ const fetchMock = vi.fn(async () => jsonResponse({ ok: true, results: [] }));
1289
+ vi.stubGlobal('fetch', fetchMock);
1290
+ process.env.OPENCHAMBER_PUSH_RELAY_URL = 'https://relay.test/v1/push/send';
1291
+ const deps = makeDeps();
1292
+ const runtime = createApnsRuntime(deps);
1293
+ await runtime.addOrUpdateLiveActivityToken('s1', 'la-token', 'act-1', 'live', [
1294
+ { sessionId: 'ses_1', title: 'One', status: 'working', startedAt: 1 },
1295
+ ]);
1296
+
1297
+ fetchMock.mockClear();
1298
+ await expect(runtime.refreshLiveActivityTokens({
1299
+ computeSnapshot: async () => {
1300
+ throw new Error('boom');
1301
+ },
1302
+ })).resolves.toBeUndefined();
1303
+ expect(fetchMock.mock.calls.filter(isLiveActivitySend)).toHaveLength(0);
1304
+ });
1305
+ });
@@ -16,7 +16,7 @@ export const APNS_LOCALES = Object.freeze([
16
16
  'ja',
17
17
  ]);
18
18
 
19
- /** @typedef {'ready'|'error'|'question'|'permission'|'goal_complete'|'goal_blocked'|'goal_budget'|'update'} ApnsTitleType */
19
+ /** @typedef {'ready'|'error'|'question'|'permission'|'goal_complete'|'goal_blocked'|'goal_budget'|'task_complete'|'task_error'|'update'} ApnsTitleType */
20
20
 
21
21
  const TITLES = Object.freeze({
22
22
  en: Object.freeze({
@@ -27,6 +27,8 @@ const TITLES = Object.freeze({
27
27
  goal_complete: 'Goal completed',
28
28
  goal_blocked: 'Goal blocked',
29
29
  goal_budget: 'Token budget reached',
30
+ task_complete: 'Scheduled task completed',
31
+ task_error: 'Scheduled task failed',
30
32
  update: 'Update',
31
33
  session: 'Session',
32
34
  }),
@@ -38,6 +40,8 @@ const TITLES = Object.freeze({
38
40
  goal_complete: 'Objectif atteint',
39
41
  goal_blocked: 'Objectif bloqué',
40
42
  goal_budget: 'Budget de tokens atteint',
43
+ task_complete: 'Tâche planifiée terminée',
44
+ task_error: 'Échec de la tâche planifiée',
41
45
  update: 'Mise à jour',
42
46
  session: 'Session',
43
47
  }),
@@ -49,6 +53,8 @@ const TITLES = Object.freeze({
49
53
  goal_complete: '目标已完成',
50
54
  goal_blocked: '目标受阻',
51
55
  goal_budget: '已达用量上限',
56
+ task_complete: '定时任务已完成',
57
+ task_error: '定时任务失败',
52
58
  update: '有新进展',
53
59
  session: '会话',
54
60
  }),
@@ -60,6 +66,8 @@ const TITLES = Object.freeze({
60
66
  goal_complete: '目標已完成',
61
67
  goal_blocked: '目標受阻',
62
68
  goal_budget: '已達用量上限',
69
+ task_complete: '排程任務已完成',
70
+ task_error: '排程任務失敗',
63
71
  update: '有新進展',
64
72
  session: '工作階段',
65
73
  }),
@@ -71,6 +79,8 @@ const TITLES = Object.freeze({
71
79
  goal_complete: 'Цілі досягнуто',
72
80
  goal_blocked: 'Цілі заблоковано',
73
81
  goal_budget: 'Досягнуто ліміт токенів',
82
+ task_complete: 'Заплановане завдання виконано',
83
+ task_error: 'Заплановане завдання не вдалося',
74
84
  update: 'Оновлення',
75
85
  session: 'Сесія',
76
86
  }),
@@ -82,6 +92,8 @@ const TITLES = Object.freeze({
82
92
  goal_complete: 'Objetivo completado',
83
93
  goal_blocked: 'Objetivo bloqueado',
84
94
  goal_budget: 'Presupuesto de tokens alcanzado',
95
+ task_complete: 'Tarea programada completada',
96
+ task_error: 'La tarea programada falló',
85
97
  update: 'Actualización',
86
98
  session: 'Sesión',
87
99
  }),
@@ -93,6 +105,8 @@ const TITLES = Object.freeze({
93
105
  goal_complete: 'Objetivo concluído',
94
106
  goal_blocked: 'Objetivo bloqueado',
95
107
  goal_budget: 'Orçamento de tokens atingido',
108
+ task_complete: 'Tarefa agendada concluída',
109
+ task_error: 'A tarefa agendada falhou',
96
110
  update: 'Atualização',
97
111
  session: 'Sessão',
98
112
  }),
@@ -104,6 +118,8 @@ const TITLES = Object.freeze({
104
118
  goal_complete: '목표 완료',
105
119
  goal_blocked: '목표 차단됨',
106
120
  goal_budget: '토큰 한도 도달',
121
+ task_complete: '예약 작업 완료',
122
+ task_error: '예약 작업 실패',
107
123
  update: '업데이트',
108
124
  session: '세션',
109
125
  }),
@@ -115,6 +131,8 @@ const TITLES = Object.freeze({
115
131
  goal_complete: 'Cel ukończony',
116
132
  goal_blocked: 'Cel zablokowany',
117
133
  goal_budget: 'Osiągnięto limit tokenów',
134
+ task_complete: 'Zadanie zaplanowane ukończone',
135
+ task_error: 'Zadanie zaplanowane nie powiodło się',
118
136
  update: 'Aktualizacja',
119
137
  session: 'Sesja',
120
138
  }),
@@ -126,6 +144,8 @@ const TITLES = Object.freeze({
126
144
  goal_complete: '目標完了',
127
145
  goal_blocked: '目標がブロックされました',
128
146
  goal_budget: 'トークン上限に達しました',
147
+ task_complete: 'スケジュールタスクが完了しました',
148
+ task_error: 'スケジュールタスクに失敗しました',
129
149
  update: '更新',
130
150
  session: 'セッション',
131
151
  }),