@kabmo-labs/kabmo 0.53.0 → 0.53.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 (147) hide show
  1. package/dist/client/index.html +1 -1
  2. package/dist/client/index.js +183 -183
  3. package/dist/client/static/js/{Body-sdq2yhmp.js → Body-3v975hq3.js} +3 -3
  4. package/dist/client/static/js/{CsvGrid-afz6vr3m.js → CsvGrid-8xcj58sw.js} +1 -1
  5. package/dist/client/static/js/{DocxView-xwjgt7qq.js → DocxView-fwmfpsg7.js} +1 -1
  6. package/dist/client/static/js/{DrawioView-7m4e8zcm.js → DrawioView-gdtqj2vv.js} +1 -1
  7. package/dist/client/static/js/{HtmlPreview-tad0dezn.js → HtmlPreview-g4bp5mgq.js} +1 -1
  8. package/dist/client/static/js/{ImageView-7bpm4xhb.js → ImageView-5e3vdyc9.js} +1 -1
  9. package/dist/client/static/js/{LayoutWrapper-ehxhj6t3.js → LayoutWrapper-ssxr6q2d.js} +2 -2
  10. package/dist/client/static/js/MergeDiffView-6t5t6exc.js +1 -0
  11. package/dist/client/static/js/{Modal-5qt3v5gn.js → Modal-px8tcv9m.js} +9 -9
  12. package/dist/client/static/js/{PdfView-hbgnnana.js → PdfView-92rx0s88.js} +1 -1
  13. package/dist/client/static/js/{SessionsView-rv9jmr2e.js → SessionsView-s3d9nceb.js} +1 -1
  14. package/dist/client/static/js/{SheetView-55e0a8as.js → SheetView-yeg7gtf9.js} +1 -1
  15. package/dist/client/static/js/{SvgPreview-10fa6mj1.js → SvgPreview-6evr72fg.js} +1 -1
  16. package/dist/client/static/js/{abnfDiagram-O67JEVCF-9w4p3dhe.js → abnfDiagram-O67JEVCF-a6n0cab2.js} +1 -1
  17. package/dist/client/static/js/{architectureDiagram-NJMV4G6O-5x6sb253.js → architectureDiagram-NJMV4G6O-z9k17qfg.js} +2 -2
  18. package/dist/client/static/js/{astro-m3fcq2sa.js → astro-asmathwv.js} +1 -1
  19. package/dist/client/static/js/{blockDiagram-BEXU5L5S-2c6y4pkn.js → blockDiagram-BEXU5L5S-63d683v3.js} +2 -2
  20. package/dist/client/static/js/c-20y64hcp.js +1 -0
  21. package/dist/client/static/js/{c4Diagram-YGBWAQC7-45rtm401.js → c4Diagram-YGBWAQC7-5bk6kv13.js} +2 -2
  22. package/dist/client/static/js/{classDiagram-v2-NBCMYWYE-rksw3aw9.js → classDiagram-v2-NBCMYWYE-s6rmr6vt.js} +2 -2
  23. package/dist/client/static/js/{cose-bilkent-JH36ORCC-4hxtttt5.js → cose-bilkent-JH36ORCC-wd5v7q2m.js} +1 -1
  24. package/dist/client/static/js/cpp-ty6n0dg9.js +1 -0
  25. package/dist/client/static/js/css-ncvxaxt0.js +1 -0
  26. package/dist/client/static/js/{cynefinDiagram-VND7K2PF-5dhexpf2.js → cynefinDiagram-VND7K2PF-j71tvbhy.js} +1 -1
  27. package/dist/client/static/js/{dagre-6A5THRUB-1k3w4qm9.js → dagre-6A5THRUB-q6x3d9xb.js} +2 -2
  28. package/dist/client/static/js/{diagram-22UHCM2B-fw76k272.js → diagram-22UHCM2B-g6e427jm.js} +2 -2
  29. package/dist/client/static/js/{diagram-3UASUU5V-qnb2gn31.js → diagram-3UASUU5V-rg3nty46.js} +1 -1
  30. package/dist/client/static/js/{diagram-ATOU4E4O-cavnxzpf.js → diagram-ATOU4E4O-m82xv6ka.js} +2 -2
  31. package/dist/client/static/js/{diagram-CDSNMT55-6dxaj054.js → diagram-CDSNMT55-q3aa8sv0.js} +2 -2
  32. package/dist/client/static/js/{diagram-MLGK6HIB-f16fv9ay.js → diagram-MLGK6HIB-nkyd150x.js} +1 -1
  33. package/dist/client/static/js/{diagram-MPIPVDR6-zsryj72g.js → diagram-MPIPVDR6-1gchkss2.js} +1 -1
  34. package/dist/client/static/js/{dockerfile-frznktsa.js → dockerfile-f51g7549.js} +1 -1
  35. package/dist/client/static/js/{ebnfDiagram-ZINNZB2B-1zz5h7sw.js → ebnfDiagram-ZINNZB2B-4dsm3p06.js} +1 -1
  36. package/dist/client/static/js/{elk-276RUBZZ-25pehy1p.js → elk-276RUBZZ-d8wtwxae.js} +1 -1
  37. package/dist/client/static/js/{erDiagram-OPXOYQCR-ezpjhgzw.js → erDiagram-OPXOYQCR-bq865cmc.js} +2 -2
  38. package/dist/client/static/js/flowDiagram-KWPJA3E3-z01c78q6.js +1 -0
  39. package/dist/client/static/js/{ganttDiagram-FUAMR5RP-n11hq4ag.js → ganttDiagram-FUAMR5RP-ndnqbbzn.js} +1 -1
  40. package/dist/client/static/js/{gitGraphDiagram-X574FWY7-3znkxh7y.js → gitGraphDiagram-X574FWY7-d9y6fnz0.js} +1 -1
  41. package/dist/client/static/js/{index-acpn178r.js → index-046kc8ft.js} +1 -1
  42. package/dist/client/static/js/{index-s78f7j47.js → index-049xtm14.js} +1 -1
  43. package/dist/client/static/js/{index-y79ebmam.js → index-0ccj7j87.js} +1 -1
  44. package/dist/client/static/js/{index-vjmy9r20.js → index-0fpc1h6v.js} +1 -1
  45. package/dist/client/static/js/{index-j97qmbbv.js → index-25g1ydkd.js} +1 -1
  46. package/dist/client/static/js/{index-4nvcwtvr.js → index-25zpywv7.js} +1 -1
  47. package/dist/client/static/js/{index-1qjxg7mh.js → index-2jtkrmry.js} +1 -1
  48. package/dist/client/static/js/{index-scmtzcv1.js → index-396g4zz4.js} +2 -2
  49. package/dist/client/static/js/{index-qrpx4sk1.js → index-3x88t8g9.js} +2 -2
  50. package/dist/client/static/js/{index-7ag37ghj.js → index-4kchzh9y.js} +8 -8
  51. package/dist/client/static/js/{index-5z7f6bq4.js → index-4pwk5cjy.js} +1 -1
  52. package/dist/client/static/js/{index-ht164kw9.js → index-53hrj27y.js} +1 -1
  53. package/dist/client/static/js/{index-2k6wyyds.js → index-5g21qv2b.js} +4 -4
  54. package/dist/client/static/js/{index-wvw70pgd.js → index-668fc1df.js} +2 -2
  55. package/dist/client/static/js/{index-gmea6fjd.js → index-6775m1pa.js} +5 -5
  56. package/dist/client/static/js/{index-5j0wejvq.js → index-6pxh5p8g.js} +2 -2
  57. package/dist/client/static/js/{index-4faphth3.js → index-79qddnbx.js} +1 -1
  58. package/dist/client/static/js/{index-tnhnysj1.js → index-7fkdwm69.js} +1 -1
  59. package/dist/client/static/js/index-7jr49rd4.js +2 -0
  60. package/dist/client/static/js/{index-ey0ckd66.js → index-8k568z0z.js} +2 -2
  61. package/dist/client/static/js/{index-dzp9rwy0.js → index-8w69r0c4.js} +161 -161
  62. package/dist/client/static/js/{index-m1hd7ska.js → index-9eddntv4.js} +25 -25
  63. package/dist/client/static/js/{index-zkkttvtx.js → index-bcns8arc.js} +2 -2
  64. package/dist/client/static/js/{index-8972fxm9.js → index-f7sssx5h.js} +1 -1
  65. package/dist/client/static/js/{index-1w92sjkm.js → index-g46qcgp8.js} +2 -2
  66. package/dist/client/static/js/{index-hqc2cazc.js → index-gm9cqsqg.js} +4 -4
  67. package/dist/client/static/js/{index-02skcm4d.js → index-gr5wd7hv.js} +1 -1
  68. package/dist/client/static/js/{index-5pbf6dcz.js → index-h9p3748x.js} +3 -3
  69. package/dist/client/static/js/{index-me7ag6sy.js → index-hav1hhbr.js} +1 -1
  70. package/dist/client/static/js/{index-58kgkwxt.js → index-hn0brpdf.js} +4 -4
  71. package/dist/client/static/js/{index-qj6b15r4.js → index-k8ks184k.js} +2 -2
  72. package/dist/client/static/js/{index-er7pj5k6.js → index-m6eh5g1q.js} +1 -1
  73. package/dist/client/static/js/{index-kyarw08m.js → index-mnadx740.js} +2 -2
  74. package/dist/client/static/js/{index-5hqjscys.js → index-mttf7ej7.js} +2 -2
  75. package/dist/client/static/js/{index-10cxm9ty.js → index-pd4s49n5.js} +2 -2
  76. package/dist/client/static/js/{index-32gh2645.js → index-pnjnvdvb.js} +1 -1
  77. package/dist/client/static/js/index-rc8f8gjk.js +1 -0
  78. package/dist/client/static/js/{index-ej1va073.js → index-rsyqf691.js} +2 -2
  79. package/dist/client/static/js/{index-e0h6xkpv.js → index-stfccv2r.js} +1 -1
  80. package/dist/client/static/js/{index-1e7fek0v.js → index-v8fztm3w.js} +1 -1
  81. package/dist/client/static/js/{index-z9msykm1.js → index-vjk01ja9.js} +1 -1
  82. package/dist/client/static/js/{index-b039ef9w.js → index-w39c85k3.js} +2 -2
  83. package/dist/client/static/js/{index-899yw6fh.js → index-x3g8fwkc.js} +2 -2
  84. package/dist/client/static/js/{index-dkz8d77n.js → index-xakrt0sx.js} +1 -1
  85. package/dist/client/static/js/{index-dzsjyzht.js → index-xf662xsf.js} +2 -2
  86. package/dist/client/static/js/{index-9n1cg95f.js → index-z0vvdpkv.js} +1 -1
  87. package/dist/client/static/js/{infoDiagram-VRGFBTTK-kmv3jtrd.js → infoDiagram-VRGFBTTK-t52bsrem.js} +1 -1
  88. package/dist/client/static/js/{ishikawaDiagram-OU5B5YK6-5kp6geeh.js → ishikawaDiagram-OU5B5YK6-vysv38pr.js} +1 -1
  89. package/dist/client/static/js/{journeyDiagram-ZHPQQLJL-6w5f1ddc.js → journeyDiagram-ZHPQQLJL-7222yn0y.js} +2 -2
  90. package/dist/client/static/js/json-xha2drny.js +1 -0
  91. package/dist/client/static/js/{julia-nwh5w343.js → julia-d18zhpyp.js} +1 -1
  92. package/dist/client/static/js/{kanban-definition-PNTS6WVX-6esn6xqn.js → kanban-definition-PNTS6WVX-9cg88rcn.js} +2 -2
  93. package/dist/client/static/js/lua-njwwdj4s.js +1 -0
  94. package/dist/client/static/js/{mermaid.core-z83pf8ch.js → mermaid.core-3qc3zvgb.js} +7 -7
  95. package/dist/client/static/js/{mindmap-definition-NLK3R4M7-0h1nhw66.js → mindmap-definition-NLK3R4M7-hdbsk349.js} +1 -1
  96. package/dist/client/static/js/one-dark-pro-3570ra7e.js +1 -0
  97. package/dist/client/static/js/one-light-3v5yk200.js +1 -0
  98. package/dist/client/static/js/{pegDiagram-GJSIUBJH-xdcpr8my.js → pegDiagram-GJSIUBJH-jtqqcrhq.js} +1 -1
  99. package/dist/client/static/js/{perl-wb4wtc9x.js → perl-sns2qvmf.js} +1 -1
  100. package/dist/client/static/js/{php-9g594k9f.js → php-3q6v9eey.js} +1 -1
  101. package/dist/client/static/js/{pieDiagram-5QR66LMP-0210zd5b.js → pieDiagram-5QR66LMP-2c82jghr.js} +1 -1
  102. package/dist/client/static/js/{quadrantDiagram-O4NWA36T-j0rtvvcm.js → quadrantDiagram-O4NWA36T-vp2hw2a8.js} +1 -1
  103. package/dist/client/static/js/{railroadDiagram-XR7U4H2S-mzxat5g5.js → railroadDiagram-XR7U4H2S-4168nq4f.js} +1 -1
  104. package/dist/client/static/js/{requirementDiagram-PLB6GJNP-zq5b9ts2.js → requirementDiagram-PLB6GJNP-gwqcyxag.js} +2 -2
  105. package/dist/client/static/js/{ruby-c4hxsegh.js → ruby-f9k99tfq.js} +1 -1
  106. package/dist/client/static/js/{rust-vmn352hx.js → rust-6m8myprw.js} +1 -1
  107. package/dist/client/static/js/{sankeyDiagram-IPEJSGJF-06s3r7bv.js → sankeyDiagram-IPEJSGJF-y5fakn56.js} +2 -2
  108. package/dist/client/static/js/{sass-6yxywx7t.js → sass-2syegq28.js} +1 -1
  109. package/dist/client/static/js/{sequenceDiagram-PO4LG4MO-7s4gz4t5.js → sequenceDiagram-PO4LG4MO-z140kern.js} +3 -3
  110. package/dist/client/static/js/{sizeCapture-INFHLROL-yensh9k2.js → sizeCapture-INFHLROL-gfez373x.js} +1 -1
  111. package/dist/client/static/js/{stateDiagram-v2-GCMORJYK-1q8p06fk.js → stateDiagram-v2-GCMORJYK-1d6h03nr.js} +1 -1
  112. package/dist/client/static/js/{swimlanes-2SLR337P-2mfxddzf.js → swimlanes-2SLR337P-75wg3n6d.js} +1 -1
  113. package/dist/client/static/js/{swimlanesDiagram-TC7HE7FX-k2xf0gby.js → swimlanesDiagram-TC7HE7FX-18fj17m7.js} +1 -1
  114. package/dist/client/static/js/{timeline-definition-EJHVYXUP-xrk07evk.js → timeline-definition-EJHVYXUP-q750z70f.js} +2 -2
  115. package/dist/client/static/js/{usecaseDiagram-POWQR4AR-ca9h5skn.js → usecaseDiagram-POWQR4AR-9q7tg456.js} +1 -1
  116. package/dist/client/static/js/{vennDiagram-UO4OBE2U-c0y47znt.js → vennDiagram-UO4OBE2U-010nw1kd.js} +1 -1
  117. package/dist/client/static/js/{vue-rcdqpz7q.js → vue-e8e3q3hj.js} +1 -1
  118. package/dist/client/static/js/{wardleyDiagram-VNRHLVJA-mfk1ck3n.js → wardleyDiagram-VNRHLVJA-7n33n10f.js} +1 -1
  119. package/dist/client/static/js/xml-8516fzfp.js +1 -0
  120. package/dist/client/static/js/{xychartDiagram-PMCCYNJV-6f8xt89k.js → xychartDiagram-PMCCYNJV-7q0n5vvd.js} +2 -2
  121. package/package.json +1 -1
  122. package/src/client/hooks/chat/timeline/new-chat-open.ts +5 -3
  123. package/src/client/hooks/chat/timeline/new-chat.test.ts +18 -2
  124. package/src/client/hooks/chat/timeline/new-chat.ts +13 -12
  125. package/src/client/hooks/chat/timeline/scope.test.ts +100 -0
  126. package/src/client/hooks/chat/timeline/scope.ts +9 -9
  127. package/src/client/lib/tts/gapless.ts +205 -0
  128. package/src/client/lib/tts/player.test.ts +83 -64
  129. package/src/client/lib/tts/player.ts +48 -98
  130. package/src/server/lib/fs/fs-write-git.test.ts +2 -51
  131. package/src/server/lib/fs/git-ignore.test.ts +101 -0
  132. package/src/server/lib/fs/git-ignore.ts +38 -1
  133. package/src/server/lib/fs/listing.test.ts +19 -0
  134. package/src/shared/lib/workspace/active-project.test.ts +45 -0
  135. package/src/shared/lib/workspace/active-project.ts +21 -0
  136. package/dist/client/static/js/MergeDiffView-28xkyts9.js +0 -1
  137. package/dist/client/static/js/c-ypdp030b.js +0 -1
  138. package/dist/client/static/js/cpp-cxwev3gs.js +0 -1
  139. package/dist/client/static/js/css-6mxcqf8c.js +0 -1
  140. package/dist/client/static/js/flowDiagram-KWPJA3E3-zh6hmn6g.js +0 -1
  141. package/dist/client/static/js/index-qva2vqbh.js +0 -2
  142. package/dist/client/static/js/index-xvh25zer.js +0 -1
  143. package/dist/client/static/js/json-mb8k0b1n.js +0 -1
  144. package/dist/client/static/js/lua-nxnqww9z.js +0 -1
  145. package/dist/client/static/js/one-dark-pro-wsgaqq27.js +0 -1
  146. package/dist/client/static/js/one-light-w8zdrvyc.js +0 -1
  147. package/dist/client/static/js/xml-vtrdnrn6.js +0 -1
@@ -26,7 +26,7 @@ import type { Dispatch, SetStateAction } from 'preact/compat';
26
26
  import type { Attachment, ChatMessageData, PromptDispatchResult, WorkspaceFolderData } from '@/shared/types';
27
27
  import type { SetSearchParams } from '@/client/lib/router/search-params';
28
28
  import { clearBranchParams } from '@/client/lib/router/branch-params';
29
- import { activeProjectForSession } from '@/shared/lib/workspace/active-project';
29
+ import { newChatFolderId } from '@/shared/lib/workspace/active-project';
30
30
  import { startPendingSession, patchPendingEntry } from '@/client/hooks/chat/omp/pending-sessions';
31
31
  import { setHarnessPick } from '@/client/hooks/chat/timeline/session-harness';
32
32
 
@@ -69,10 +69,14 @@ export function useNewChatSubmit(
69
69
  }, [sessionId, executeSend]);
70
70
 
71
71
  return useCallback((text, attachments, harness) => {
72
+ // The workspace this chat will RUN in: the folder owning the chat the card
73
+ // was opened from, else the composer's pick. Resolved ONCE here — the
74
+ // pending row, the prewarm (`useNewChatOpen`) and the spawn all read it.
75
+ const folderId = newChatFolderId(folders, sessionId, selectedFolderId);
72
76
  // The store mints the pending id and owns the row it stands for: the
73
77
  // sidebar/navbar show a default title immediately, and the row survives the
74
78
  // `new-…` → omp-UUID switch when the first send spawns.
75
- const pendingId = startPendingSession(activeProjectForSession(folders, sessionId).folder?.id ?? selectedFolderId);
79
+ const pendingId = startPendingSession(folderId);
76
80
  // The card's agent becomes the PENDING chat's agent now, not at the send:
77
81
  // the composer's mode surface and the prewarm both read the pick, and a
78
82
  // harness that only appears when the prompt lands showed omp's toggles over
@@ -87,16 +91,13 @@ export function useNewChatSubmit(
87
91
  // `forkFrom`/`forkAt` in the URL, and this chat would be drawn as it.
88
92
  const next = clearBranchParams(prev);
89
93
  next.set('sessionId', pendingId);
90
- // Carry the workspace the chat was started from: the first send SPAWNS a
91
- // real omp session in that folder's cwd, and a dialog opened from a
92
- // session picked in the sidebar has no `folderId` in the URL (the
93
- // sidebar's own New Session copies it from the current session, which is
94
- // exactly this). Without one the spawn has no cwd and the send falls back
95
- // to the simulated stream.
96
- if (!next.get('folderId')) {
97
- const folderId = activeProjectForSession(folders, sessionId).folder?.id ?? selectedFolderId;
98
- if (folderId !== null && folderId !== undefined) next.set('folderId', String(folderId));
99
- }
94
+ // The chat runs in `folderId` — that is where the prewarm fired and where
95
+ // the first send spawns. A `folderId` the URL already carried is the
96
+ // right panel's scope, not this chat's target, and it must not veto the
97
+ // workspace the chat was started from: keeping it spawned the prompt in
98
+ // the previous workspace while the warm child sat in this one.
99
+ if (folderId !== null && folderId !== undefined) next.set('folderId', String(folderId));
100
+ else next.delete('folderId');
100
101
  return next;
101
102
  }, { replace: true });
102
103
  setLocalMessages([]);
@@ -0,0 +1,100 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The chat's folder scope IS the URL's `folderId` — read, never mirrored.
8
+ *
9
+ * The New Chat dialog's first send is dispatched in the SAME commit that writes
10
+ * `?folderId=` for the pending chat (`useNewChatSubmit` → the parked send). A
11
+ * copy kept in `useState` and synced by an effect is one render behind there,
12
+ * so the spawn read the PREVIOUS folder and the prompt landed in another
13
+ * workspace than the prewarmed one. These cases pin the value's freshness, not
14
+ * the mirror's mechanism.
15
+ */
16
+
17
+ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
18
+ import { Window } from 'happy-dom';
19
+ import { h, render } from 'preact';
20
+ import { act } from 'preact/test-utils';
21
+
22
+ import { useTimelineScope, type TimelineScope } from '@/client/hooks/chat/timeline/scope';
23
+ import { installDomGlobals, restoreDomGlobals } from '@/test-support/pristine-globals';
24
+
25
+ const BASE = 'http://localhost/?sessionId=omp-a&folderId=9';
26
+
27
+ let container: HTMLElement | undefined;
28
+ let scope: TimelineScope | null = null;
29
+ /** `selectedFolderId` of every render, in order. */
30
+ const renders: Array<number | null> = [];
31
+
32
+ function Probe() {
33
+ const current = useTimelineScope();
34
+ scope = current;
35
+ renders.push(current.selectedFolderId);
36
+ return null;
37
+ }
38
+
39
+ async function mount() {
40
+ container = document.body.appendChild(document.createElement('div'));
41
+ await act(async () => { render(h(Probe, {}), container as HTMLElement); });
42
+ await act(async () => {});
43
+ }
44
+
45
+ beforeAll(() => {
46
+ installDomGlobals(new Window({ url: BASE }));
47
+ });
48
+
49
+ afterAll(() => {
50
+ restoreDomGlobals();
51
+ });
52
+
53
+ beforeEach(() => {
54
+ window.history.replaceState(null, '', BASE);
55
+ renders.length = 0;
56
+ scope = null;
57
+ });
58
+
59
+ afterEach(() => {
60
+ if (container) render(null, container);
61
+ container?.remove();
62
+ container = undefined;
63
+ });
64
+
65
+ describe('useTimelineScope', () => {
66
+ test('the URL folder is on the FIRST render a URL write produces', async () => {
67
+ await mount();
68
+ expect(renders).toEqual([9]);
69
+
70
+ const before = renders.length;
71
+ await act(async () => {
72
+ // Exactly what the New Chat dialog does: the pending chat's id and the
73
+ // workspace it was started from, in one write.
74
+ scope?.setSearchParams((prev) => {
75
+ prev.set('sessionId', 'new-1');
76
+ prev.set('folderId', '7');
77
+ return prev;
78
+ }, { replace: true });
79
+ });
80
+
81
+ // A mirrored copy answered `9` here and only caught up on the next render —
82
+ // which is the commit the parked send already used.
83
+ expect(renders[before]).toBe(7);
84
+ expect(scope?.sessionId).toBe('new-1');
85
+ });
86
+
87
+ test('the picker writes the param and reads back the number', async () => {
88
+ await mount();
89
+
90
+ await act(async () => { scope?.selectContextFolder(11); });
91
+
92
+ expect(window.location.search).toContain('folderId=11');
93
+ expect(scope?.selectedFolderId).toBe(11);
94
+
95
+ await act(async () => { scope?.selectContextFolder(null); });
96
+
97
+ expect(window.location.search).not.toContain('folderId');
98
+ expect(scope?.selectedFolderId).toBeNull();
99
+ });
100
+ });
@@ -13,8 +13,8 @@
13
13
  * so both readers move together.
14
14
  */
15
15
 
16
- import { useCallback, useEffect, useState } from 'preact/hooks';
17
- import { useSearchParams } from '@/client/lib/router/search-params';
16
+ import { useCallback } from 'preact/hooks';
17
+ import { useSearchParams, type SetSearchParams } from '@/client/lib/router/search-params';
18
18
 
19
19
  export interface TimelineScope {
20
20
  sessionId: string | null;
@@ -23,22 +23,22 @@ export interface TimelineScope {
23
23
  selectContextFolder: (id: number | null) => void;
24
24
  /** The raw URL setter, for the send path: adopting a freshly spawned session
25
25
  * rewrites `sessionId` in place, and the layout reads the same params. */
26
- setSearchParams: ReturnType<typeof useSearchParams>[1];
26
+ setSearchParams: SetSearchParams;
27
27
  }
28
28
 
29
29
  export function useTimelineScope(): TimelineScope {
30
30
  const [searchParams, setSearchParams] = useSearchParams();
31
31
  const sessionId = searchParams.get('sessionId');
32
32
  const folderId = searchParams.get('folderId');
33
- const [selectedFolderId, setSelectedFolderId] = useState<number | null>(null);
34
-
35
- useEffect(() => {
36
- setSelectedFolderId(folderId ? parseInt(folderId, 10) : null);
37
- }, [folderId]);
33
+ // DERIVED, never mirrored into state. The URL is the one value the picker,
34
+ // the prewarm and the send all read; a copy in `useState` synced by an effect
35
+ // lagged it by one render — and the New Chat dialog's first send is
36
+ // dispatched in the very commit that writes `?folderId=`, so it read the
37
+ // PREVIOUS folder and spawned the prompt in another workspace.
38
+ const selectedFolderId = folderId ? parseInt(folderId, 10) : null;
38
39
 
39
40
  const selectContextFolder = useCallback(
40
41
  (id: number | null) => {
41
- setSelectedFolderId(id);
42
42
  setSearchParams(
43
43
  (prev) => {
44
44
  if (id) prev.set('folderId', String(id));
@@ -0,0 +1,205 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * Gapless synthesis playback.
8
+ *
9
+ * The player used to start one `<audio>` element per chunk. Even when the next
10
+ * blob was already in memory, swapping `src` tore down the decoder and called
11
+ * `play()` again, so every paragraph boundary carried an audible pause. This
12
+ * module decodes each chunk to an `AudioBuffer` and starts it at the previous
13
+ * buffer's exact end, on the browser's own continuous timeline.
14
+ *
15
+ * Pause suspends the context instead of the element: `currentTime` freezes,
16
+ * the scheduled sources keep their sample offsets, and resume continues from
17
+ * the same sample. Stop closes the context; the next read opens a fresh one.
18
+ *
19
+ * The context is created on the first scheduled read, so the module can be
20
+ * imported where no `AudioContext` exists (the server bundle, tests) and the
21
+ * refusal arrives on the click that needs it.
22
+ */
23
+
24
+ const START_LEAD_SECONDS = 0.05;
25
+ /**
26
+ * Decoded audio kept ahead of the playhead. Three chunks is enough for the
27
+ * next request to land while two are still queued, without holding a
28
+ * ten-minute answer in memory.
29
+ */
30
+ const MAX_SCHEDULED_CHUNKS = 3;
31
+ const RESUME_TIMEOUT_MS = 750;
32
+ const BLOCKED_MESSAGE = 'The browser blocked autoplay. Press the speaker button to hear this answer.';
33
+
34
+ interface AudioGlobals {
35
+ AudioContext?: typeof AudioContext;
36
+ webkitAudioContext?: typeof AudioContext;
37
+ }
38
+
39
+ export class GaplessAudio {
40
+ private context: AudioContext | null = null;
41
+ private nextStart = 0;
42
+ private readonly active = new Set<AudioBufferSourceNode>();
43
+ private readonly roomWaiters = new Set<() => void>();
44
+ private readonly idleWaiters = new Set<() => void>();
45
+ private paused = false;
46
+ private generation = 0;
47
+
48
+ constructor(private readonly createContext: () => AudioContext) {}
49
+
50
+ static create(): GaplessAudio | null {
51
+ const scope = globalThis as unknown as AudioGlobals;
52
+ const Ctor = scope.AudioContext ?? scope.webkitAudioContext;
53
+ return Ctor ? new GaplessAudio(() => new Ctor()) : null;
54
+ }
55
+
56
+ get hasAudio(): boolean {
57
+ return this.active.size > 0;
58
+ }
59
+
60
+ /** Open the context and make sure the browser will let it start. */
61
+ async ensure(): Promise<void> {
62
+ const existing = this.context?.state === 'closed' ? null : this.context;
63
+ const context = existing ?? this.open();
64
+ this.context = context;
65
+ if (this.paused) {
66
+ if (context.state === 'running') await context.suspend().catch(() => undefined);
67
+ return;
68
+ }
69
+ await this.resumeContext(context);
70
+ if (this.paused && context.state === 'running') await context.suspend().catch(() => undefined);
71
+ }
72
+
73
+ /** Decode one chunk and put it on the queue; resolves once it is scheduled. */
74
+ async schedule(blob: Blob): Promise<void> {
75
+ const generation = this.generation;
76
+ const context = this.context;
77
+ if (!context) throw new Error('Speech playback has not started.');
78
+
79
+ const bytes = await blob.arrayBuffer();
80
+ if (generation !== this.generation) return;
81
+
82
+ let buffer: AudioBuffer;
83
+ try {
84
+ buffer = await context.decodeAudioData(bytes);
85
+ } catch {
86
+ throw new Error('The audio could not be decoded.');
87
+ }
88
+ if (generation !== this.generation) return;
89
+
90
+ while (this.active.size >= MAX_SCHEDULED_CHUNKS && generation === this.generation) {
91
+ const room = Promise.withResolvers<void>();
92
+ this.roomWaiters.add(room.resolve);
93
+ await room.promise;
94
+ }
95
+ if (generation !== this.generation) return;
96
+ this.startBuffer(context, buffer);
97
+ }
98
+
99
+ /** Resolve when every scheduled buffer has finished playing. */
100
+ finish(): Promise<void> {
101
+ if (this.active.size === 0) return Promise.resolve();
102
+ const idle = Promise.withResolvers<void>();
103
+ this.idleWaiters.add(idle.resolve);
104
+ return idle.promise;
105
+ }
106
+
107
+ pause(): void {
108
+ this.paused = true;
109
+ const context = this.context;
110
+ if (context && context.state === 'running') void context.suspend().catch(() => undefined);
111
+ }
112
+
113
+ /** Continue a paused read at the sample where the context froze. */
114
+ async resume(): Promise<void> {
115
+ this.paused = false;
116
+ const context = this.context;
117
+ if (!context) return;
118
+ await this.resumeContext(context);
119
+ }
120
+
121
+ /** Silence the context after a natural end without closing it. */
122
+ idle(): void {
123
+ const context = this.context;
124
+ if (context && context.state === 'running') void context.suspend().catch(() => undefined);
125
+ }
126
+
127
+ stop(): void {
128
+ this.generation += 1;
129
+ for (const source of this.active) {
130
+ source.onended = null;
131
+ try {
132
+ source.stop();
133
+ } catch {
134
+ // The source already ended; there is nothing left to stop.
135
+ }
136
+ try {
137
+ source.disconnect();
138
+ } catch {
139
+ // The node was never connected, or was already disconnected.
140
+ }
141
+ }
142
+ this.active.clear();
143
+ this.nextStart = 0;
144
+ this.paused = false;
145
+ this.notifyRoom();
146
+ this.notifyIdle();
147
+ const context = this.context;
148
+ this.context = null;
149
+ if (context) void context.close().catch(() => undefined);
150
+ }
151
+
152
+ private open(): AudioContext {
153
+ try {
154
+ return this.createContext();
155
+ } catch (error) {
156
+ throw new Error(
157
+ error instanceof Error && error.name === 'NotAllowedError'
158
+ ? BLOCKED_MESSAGE
159
+ : 'This browser cannot play synthesized speech.',
160
+ );
161
+ }
162
+ }
163
+
164
+ private async resumeContext(context: AudioContext): Promise<void> {
165
+ if (context.state === 'closed') throw new Error('Speech playback was closed.');
166
+ if (context.state === 'suspended') {
167
+ const timeout = Promise.withResolvers<void>();
168
+ const timer = setTimeout(() => timeout.resolve(), RESUME_TIMEOUT_MS);
169
+ const resume = context.resume().catch(() => undefined);
170
+ try {
171
+ await Promise.race([resume, timeout.promise]);
172
+ } finally {
173
+ clearTimeout(timer);
174
+ }
175
+ }
176
+ if (context.state !== 'running' && !this.paused) throw new Error(BLOCKED_MESSAGE);
177
+ }
178
+
179
+ private startBuffer(context: AudioContext, buffer: AudioBuffer): void {
180
+ const source = context.createBufferSource();
181
+ source.buffer = buffer;
182
+ source.connect(context.destination);
183
+ source.onended = () => {
184
+ this.active.delete(source);
185
+ this.notifyRoom();
186
+ this.notifyIdle();
187
+ };
188
+ this.active.add(source);
189
+
190
+ const startAt = Math.max(context.currentTime + START_LEAD_SECONDS, this.nextStart);
191
+ this.nextStart = startAt + buffer.duration;
192
+ source.start(startAt);
193
+ }
194
+
195
+ private notifyRoom(): void {
196
+ for (const resolve of this.roomWaiters) resolve();
197
+ this.roomWaiters.clear();
198
+ }
199
+
200
+ private notifyIdle(): void {
201
+ if (this.active.size > 0) return;
202
+ for (const resolve of this.idleWaiters) resolve();
203
+ this.idleWaiters.clear();
204
+ }
205
+ }
@@ -5,67 +5,82 @@
5
5
 
6
6
  /**
7
7
  * The player's own contract: an answer is split at the engine's budget, each
8
- * chunk is fetched once, playback runs in order, and the snapshot returns to
9
- * idle at the end.
8
+ * chunk is fetched once, chunk audio is scheduled back-to-back, and the
9
+ * snapshot returns to idle at the end.
10
10
  *
11
- * Audio and fetch are fakes. What is pinned is the sequence Kabmo controls —
12
- * chunk boundaries, the `/api/tts/speak` body, and the cache — not the browser's
13
- * decoder.
11
+ * Audio is a fake AudioContext. What is pinned is the sequence Kabmo controls —
12
+ * chunk boundaries, the `/api/tts/speak` body, the cache, and the contiguous
13
+ * start times that remove the gap between chunks — not the browser's decoder.
14
14
  */
15
15
 
16
16
  import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
17
+ import { GaplessAudio } from '@/client/lib/tts/gapless';
17
18
  import { ttsPlayer, type TtsSnapshot } from '@/client/lib/tts/player';
18
19
  import { DEFAULT_TTS_CONFIG } from '@/shared/lib/tts/settings';
19
20
 
20
21
  const originalFetch = globalThis.fetch;
21
- const originalAudio = globalThis.Audio;
22
- const originalCreate = URL.createObjectURL;
23
- const originalRevoke = URL.revokeObjectURL;
22
+ const originalAudioContext = globalThis.AudioContext;
24
23
 
25
24
  let requests: Array<{ text: string; config: Record<string, unknown> }> = [];
26
25
 
27
- class FakeAudio {
26
+ class FakeSource {
28
27
  onended: (() => void) | null = null;
29
- onerror: (() => void) | null = null;
30
- src = '';
31
- play(): Promise<void> {
32
- queueMicrotask(() => this.onended?.());
33
- return Promise.resolve();
28
+ buffer: AudioBuffer | null = null;
29
+ startedAt: number | null = null;
30
+ stopped = false;
31
+
32
+ connect(): void {}
33
+ disconnect(): void {}
34
+
35
+ start(when: number): void {
36
+ this.startedAt = when;
37
+ }
38
+
39
+ stop(): void {
40
+ this.stopped = true;
34
41
  }
35
- pause(): void {}
36
- removeAttribute(name: string): void {
37
- if (name === 'src') this.src = '';
42
+
43
+ end(): void {
44
+ if (this.stopped) return;
45
+ this.stopped = true;
46
+ this.onended?.();
38
47
  }
39
- load(): void {}
40
48
  }
41
49
 
42
- /** An element whose playback only ends when the test says so. */
43
- class ManualAudio {
44
- static instances: ManualAudio[] = [];
45
- /** Fires for each element the player creates, so a test can await the next chunk. */
46
- static created: ((audio: ManualAudio) => void) | null = null;
47
- onended: (() => void) | null = null;
48
- onerror: (() => void) | null = null;
49
- src = '';
50
- playCalls = 0;
51
- pauseCalls = 0;
50
+ class FakeAudioContext {
51
+ static instances: FakeAudioContext[] = [];
52
+ static autoEnd = true;
53
+
54
+ state: AudioContextState = 'running';
55
+ currentTime = 0;
56
+ destination = {} as AudioDestinationNode;
57
+ sources: FakeSource[] = [];
58
+
52
59
  constructor() {
53
- ManualAudio.instances.push(this);
54
- ManualAudio.created?.(this);
60
+ FakeAudioContext.instances.push(this);
61
+ }
62
+
63
+ createBufferSource(): AudioBufferSourceNode {
64
+ const source = new FakeSource();
65
+ this.sources.push(source);
66
+ if (FakeAudioContext.autoEnd) queueMicrotask(() => source.end());
67
+ return source as unknown as AudioBufferSourceNode;
55
68
  }
56
- play(): Promise<void> {
57
- this.playCalls += 1;
58
- return Promise.resolve();
69
+
70
+ async decodeAudioData(_bytes: ArrayBuffer): Promise<AudioBuffer> {
71
+ return { duration: 1 } as AudioBuffer;
59
72
  }
60
- pause(): void {
61
- this.pauseCalls += 1;
73
+
74
+ async suspend(): Promise<void> {
75
+ this.state = 'suspended';
62
76
  }
63
- removeAttribute(name: string): void {
64
- if (name === 'src') this.src = '';
77
+
78
+ async resume(): Promise<void> {
79
+ this.state = 'running';
65
80
  }
66
- load(): void {}
67
- end(): void {
68
- this.onended?.();
81
+
82
+ async close(): Promise<void> {
83
+ this.state = 'closed';
69
84
  }
70
85
  }
71
86
 
@@ -82,25 +97,21 @@ function waitFor(predicate: (snapshot: TtsSnapshot) => boolean): Promise<TtsSnap
82
97
 
83
98
  beforeEach(() => {
84
99
  requests = [];
85
- ManualAudio.instances = [];
86
- ManualAudio.created = null;
100
+ FakeAudioContext.instances = [];
101
+ FakeAudioContext.autoEnd = true;
87
102
  ttsPlayer.stop();
88
103
  globalThis.fetch = (async (_input: RequestInfo | URL, init?: RequestInit) => {
89
104
  const body = JSON.parse(String(init?.body)) as { text: string; config: Record<string, unknown> };
90
105
  requests.push(body);
91
106
  return new Response(new Blob([new Uint8Array([1])]), { headers: { 'content-type': 'audio/mpeg' } });
92
107
  }) as unknown as typeof fetch;
93
- globalThis.Audio = FakeAudio as unknown as typeof Audio;
94
- URL.createObjectURL = () => 'blob:test';
95
- URL.revokeObjectURL = () => {};
108
+ globalThis.AudioContext = FakeAudioContext as unknown as typeof AudioContext;
96
109
  });
97
110
 
98
111
  afterEach(() => {
99
112
  ttsPlayer.stop();
100
113
  globalThis.fetch = originalFetch;
101
- globalThis.Audio = originalAudio;
102
- URL.createObjectURL = originalCreate;
103
- URL.revokeObjectURL = originalRevoke;
114
+ globalThis.AudioContext = originalAudioContext;
104
115
  });
105
116
 
106
117
  describe('ttsPlayer', () => {
@@ -112,6 +123,7 @@ describe('ttsPlayer', () => {
112
123
  const snapshot = await settled;
113
124
 
114
125
  expect(snapshot).toEqual({ status: 'idle', activeKey: null, error: null });
126
+ expect(FakeAudioContext.instances).toHaveLength(1);
115
127
  expect(requests.length).toBeGreaterThan(1);
116
128
  for (const request of requests) {
117
129
  expect(request.text.length).toBeLessThanOrEqual(4096);
@@ -133,32 +145,39 @@ describe('ttsPlayer', () => {
133
145
  expect(requests).toHaveLength(1);
134
146
  });
135
147
 
136
- test('pause holds the read and never starts the next chunk', async () => {
137
- globalThis.Audio = ManualAudio as unknown as typeof Audio;
138
- const nextChunk = Promise.withResolvers<ManualAudio>();
139
- ManualAudio.created = () => {
140
- if (ManualAudio.instances.length === 2) nextChunk.resolve(ManualAudio.instances[1]!);
141
- };
148
+ test('pause suspends the audio context and resume continues it', async () => {
149
+ FakeAudioContext.autoEnd = false;
142
150
  const text = Array.from({ length: 30 }, (_, index) => `Sentence number ${index + 1} is here.`).join(' ');
143
151
 
144
152
  ttsPlayer.speak(text, 'run-1', { ...DEFAULT_TTS_CONFIG, engine: 'openai' });
145
153
  await waitFor((snapshot) => snapshot.status === 'playing');
146
- const first = ManualAudio.instances[0];
147
- expect(first).toBeDefined();
154
+ const context = FakeAudioContext.instances.at(-1);
155
+ expect(context).toBeDefined();
156
+ expect(context!.sources.length).toBeGreaterThan(0);
148
157
 
149
158
  ttsPlayer.pause();
150
159
  expect(ttsPlayer.getSnapshot()).toEqual({ status: 'paused', activeKey: 'run-1', error: null });
151
- expect(first!.pauseCalls).toBe(1);
152
-
153
- // The chunk ends while paused: the next one must be loaded but silent.
154
- first!.end();
155
- const second = await nextChunk.promise;
156
- expect(ttsPlayer.getSnapshot().status).toBe('paused');
157
- expect(second.playCalls).toBe(0);
160
+ expect(context!.state).toBe('suspended');
158
161
 
159
162
  ttsPlayer.resume();
160
163
  expect(ttsPlayer.getSnapshot().status).toBe('playing');
161
- expect(second.playCalls).toBe(1);
164
+ expect(context!.state).toBe('running');
162
165
  ttsPlayer.stop();
163
166
  });
167
+
168
+ test('starts each chunk at the previous chunk end', async () => {
169
+ FakeAudioContext.autoEnd = false;
170
+ const context = new FakeAudioContext();
171
+ const audio = new GaplessAudio(() => context as unknown as AudioContext);
172
+
173
+ await audio.ensure();
174
+ await audio.schedule(new Blob([new Uint8Array([1])]));
175
+ await audio.schedule(new Blob([new Uint8Array([2])]));
176
+
177
+ expect(context.sources).toHaveLength(2);
178
+ expect(context.sources[0]!.startedAt).toBeCloseTo(0.05, 5);
179
+ expect(context.sources[1]!.startedAt).toBeCloseTo(1.05, 5);
180
+
181
+ audio.stop();
182
+ });
164
183
  });