@pi-chamber/web 0.3.3 → 0.4.0

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 (121) hide show
  1. package/README.md +1 -0
  2. package/bin/lib/cli-startup.js +1 -0
  3. package/dist/assets/CommitSection-0zl1puqf.js +1 -0
  4. package/dist/assets/DiagramEditor-CFV_TjE2.js +1 -0
  5. package/dist/assets/DiagramView-0I4PZUpw.js +1 -0
  6. package/dist/assets/{DiffView-DGD9DMS7.js → DiffView-BoTz2Zqe.js} +2 -2
  7. package/dist/assets/{FilesView-DB5VI7EN.js → FilesView-CVMNE9Pr.js} +6 -6
  8. package/dist/assets/GitView-DnsbCAWl.js +6 -0
  9. package/dist/assets/JsonTreeView-Cn1Mk0Wf.js +1 -0
  10. package/dist/assets/{MarkdownRendererImpl-V1HMFCjr.js → MarkdownRendererImpl-DJKD8tNq.js} +2 -2
  11. package/dist/assets/PatchDiff-GdGq3IlM.js +1 -0
  12. package/dist/assets/PierreDiffViewer-CdkAUt-S.js +136 -0
  13. package/dist/assets/SessionSwitcherContent-BTzVmIop.js +1 -0
  14. package/dist/assets/SessionSwitcherDropdown-DuPmnk3k.js +2 -0
  15. package/dist/assets/SessionUnreadDot-ogHL0INY.js +1 -0
  16. package/dist/assets/SettingsView-SHhVrRdh.js +4 -0
  17. package/dist/assets/SettingsWindow-D_D1qqLF.js +1 -0
  18. package/dist/assets/{ToolOutputDialog-2zKUdGYL.js → ToolOutputDialog-BHaf293m.js} +6 -6
  19. package/dist/assets/ToolPartDiffPreview-BTMXNcqG.js +8 -0
  20. package/dist/assets/{VirtualizedFileDiff-UMgLcO4Q.js → VirtualizedFileDiff-CRVvv23V.js} +4 -4
  21. package/dist/assets/{SessionSwitcherDropdown-o1RjhCfF.js → WindowsWindowControls-CTtxXnD1.js} +172 -123
  22. package/dist/assets/collapsible-BO4qEdib.js +1 -0
  23. package/dist/assets/computeVirtualFileMetrics-D1I8YrPV.js +3 -0
  24. package/dist/assets/contextFileOpenGuard-w5xG9Qz2.js +1 -0
  25. package/dist/assets/index-3zee2IYy.css +1 -0
  26. package/dist/assets/{index-BAqpUCjs.js → index-CI-cd-mw.js} +6 -6
  27. package/dist/assets/index-DbghctxK.js +1 -0
  28. package/dist/assets/isDiffPlainText-BK9bF1l5.js +1 -0
  29. package/dist/assets/isFilePlainText-Cua0RCRz.js +1 -0
  30. package/dist/assets/main-BNJQ6mSF.js +2 -0
  31. package/dist/assets/{main-CmkRaMOR.js → main-CoA--JT-.js} +6 -6
  32. package/dist/assets/markdownCore-BGlLZrb8.js +3 -0
  33. package/dist/assets/miniChat-DU2jFhXq.js +2 -0
  34. package/dist/assets/mobile-B3lJ_CJR.js +2 -0
  35. package/dist/assets/renderElectronMiniChatApp-BfXYv3zl.js +2 -0
  36. package/dist/assets/renderMobileApp-Cd_F7yMe.js +14 -0
  37. package/dist/assets/{runtimeSurface-CkHYYg0E.js → runtimeSurface-UriLeO95.js} +1 -1
  38. package/dist/assets/{useInlineCommentController-DD31jQNC.js → useInlineCommentController-5XANmO1k.js} +2 -2
  39. package/dist/assets/usePanelSlide-CBZw2Cjo.js +56 -0
  40. package/dist/assets/useSwitcherItems-Cc6Tx-LO.js +1 -0
  41. package/dist/assets/{useWindowTitle-DoHrUC5r.js → useWindowTitle-Bf8ZNN_R.js} +1 -1
  42. package/dist/assets/{vendor-codemirror-language-data-Dp_Z-0GD.js → vendor-codemirror-language-data-DxpwplIe.js} +2 -2
  43. package/dist/assets/{vendor-katex-CHD9BdDO.js → vendor-katex-CNckGUMB.js} +1 -1
  44. package/dist/assets/{vendor-marked-i_gIkIP3.js → vendor-marked-CX41MkDF.js} +1 -1
  45. package/dist/assets/{web-components-Cct1r-wn.js → web-components-g7DKkne_.js} +4 -4
  46. package/dist/index.html +5 -5
  47. package/dist/mini-chat.html +4 -4
  48. package/dist/mobile.html +4 -4
  49. package/dist/sw.js +1 -1
  50. package/package.json +1 -1
  51. package/server/index.js +27 -5
  52. package/server/lib/fs/routes.js +0 -21
  53. package/server/lib/git/DOCUMENTATION.md +13 -3
  54. package/server/lib/git/routes.js +80 -4
  55. package/server/lib/git/routes.test.js +135 -0
  56. package/server/lib/git/service.js +130 -31
  57. package/server/lib/git/service.test.js +146 -0
  58. package/server/lib/pi/routes.js +67 -2
  59. package/server/lib/pi/routes.test.js +43 -3
  60. package/server/lib/pi/session-daemon/DOCUMENTATION.md +4 -4
  61. package/server/lib/pi/session-daemon/message-entry-aliases.js +53 -13
  62. package/server/lib/pi/session-daemon/message-entry-aliases.test.js +110 -0
  63. package/server/lib/pi/session-daemon/session-daemon.js +181 -22
  64. package/server/lib/pi/session-daemon/session-daemon.test.js +123 -3
  65. package/server/lib/pi/session-daemon/session-retry-limits.js +55 -0
  66. package/server/lib/pi/session-daemon/session-retry-limits.test.js +53 -0
  67. package/server/lib/pi/session-daemon/skill-read-classifier.js +39 -0
  68. package/server/lib/pi/session-daemon/skill-read-classifier.test.js +41 -0
  69. package/server/lib/pi/session-daemon/supervisor.js +3 -0
  70. package/server/lib/pi/small-model-generation.js +104 -0
  71. package/server/lib/pi/small-model-generation.test.js +66 -0
  72. package/server/lib/preview/proxy-runtime.js +11 -1
  73. package/server/lib/preview/proxy-runtime.test.js +3 -0
  74. package/server/lib/relay/tunnel-host.js +1 -0
  75. package/server/lib/stt/DOCUMENTATION.md +38 -0
  76. package/server/lib/stt/audio.js +47 -0
  77. package/server/lib/stt/config-store.js +81 -0
  78. package/server/lib/stt/config-store.test.js +36 -0
  79. package/server/lib/stt/local/model-catalog.js +57 -0
  80. package/server/lib/stt/local/model-downloader.js +127 -0
  81. package/server/lib/stt/local/recognizer.js +64 -0
  82. package/server/lib/stt/local/sherpa-loader.js +43 -0
  83. package/server/lib/stt/local/worker-client.js +115 -0
  84. package/server/lib/stt/local/worker-process.js +64 -0
  85. package/server/lib/stt/protocol.js +38 -0
  86. package/server/lib/stt/protocol.test.js +17 -0
  87. package/server/lib/stt/providers/local-worker-provider.js +11 -0
  88. package/server/lib/stt/providers/openai-compatible-provider.js +31 -0
  89. package/server/lib/stt/providers/openai-compatible-provider.test.js +31 -0
  90. package/server/lib/stt/runtime.js +111 -0
  91. package/server/lib/stt/service.js +106 -0
  92. package/server/lib/stt/stream-manager.js +188 -0
  93. package/server/lib/stt/stream-manager.test.js +64 -0
  94. package/server/lib/ui-auth/DOCUMENTATION.md +1 -1
  95. package/server/lib/ui-auth/ui-auth.js +8 -3
  96. package/server/lib/ui-auth/ui-auth.test.js +8 -0
  97. package/server/lib/workspace/host.js +18 -2
  98. package/dist/assets/CommitSection-BAYzLtBf.js +0 -1
  99. package/dist/assets/DiagramEditor-D1yc4joK.js +0 -1
  100. package/dist/assets/DiagramView-CAlJiG11.js +0 -1
  101. package/dist/assets/GitView-CFlPcSn9.js +0 -6
  102. package/dist/assets/JsonTreeView-CoX1ZscV.js +0 -1
  103. package/dist/assets/PatchDiff-D6Gs7K5B.js +0 -1
  104. package/dist/assets/PierreDiffViewer-COYd5Qr-.js +0 -136
  105. package/dist/assets/SettingsView-BYqvfMTS.js +0 -4
  106. package/dist/assets/SettingsWindow-CtNS0tQn.js +0 -1
  107. package/dist/assets/ToolPartDiffPreview-CBFC9min.js +0 -8
  108. package/dist/assets/collapsible-Kx4bmsQM.js +0 -1
  109. package/dist/assets/computeVirtualFileMetrics-DdOCbMyK.js +0 -3
  110. package/dist/assets/contextFileOpenGuard-BRldMp0d.js +0 -1
  111. package/dist/assets/index-CuSNEV7s.js +0 -1
  112. package/dist/assets/index-riABQmQ_.css +0 -1
  113. package/dist/assets/isDiffPlainText-CGIf0q8p.js +0 -1
  114. package/dist/assets/isFilePlainText-D4hgTRxT.js +0 -1
  115. package/dist/assets/main-By_pvk90.js +0 -2
  116. package/dist/assets/markdownCore-CAVCyFnI.js +0 -2
  117. package/dist/assets/miniChat-_XK2gGZE.js +0 -2
  118. package/dist/assets/mobile-B4E4JqAf.js +0 -2
  119. package/dist/assets/renderElectronMiniChatApp-Ca4hZgIz.js +0 -1
  120. package/dist/assets/renderMobileApp-ClA5Cnmw.js +0 -14
  121. package/dist/assets/usePanelSlide-a4c67FIY.js +0 -56
@@ -0,0 +1,53 @@
1
+ import { describe, expect, test } from 'vitest';
2
+ import { join } from 'node:path';
3
+ import { mkdtempSync, writeFileSync, mkdirSync } from 'node:fs';
4
+ import { tmpdir } from 'node:os';
5
+ import {
6
+ PI_FALLBACK_RETRY_LIMIT,
7
+ resolveEffectiveRetryLimitFromDataDir as resolveEffectiveRetryLimit,
8
+ } from './session-retry-limits.js';
9
+
10
+ const makeDataDir = (sidecar) => {
11
+ const dataDir = mkdtempSync(join(tmpdir(), 'pichamber-retry-'));
12
+ if (sidecar !== undefined) {
13
+ mkdirSync(join(dataDir, 'pi'), { recursive: true });
14
+ writeFileSync(join(dataDir, 'pi', 'settings.json'), JSON.stringify(sidecar));
15
+ }
16
+ return dataDir;
17
+ };
18
+
19
+ describe('resolveEffectiveRetryLimit', () => {
20
+ test('explicit payload value wins and is validated', async () => {
21
+ await expect(resolveEffectiveRetryLimit({ payloadRetryLimit: 7, dataDir: makeDataDir({ defaultRetryLimit: 2 }) })).resolves.toBe(7);
22
+ await expect(resolveEffectiveRetryLimit({ payloadRetryLimit: -1, dataDir: undefined })).rejects.toThrow('between 0 and 10');
23
+ await expect(resolveEffectiveRetryLimit({ payloadRetryLimit: 11, dataDir: undefined })).rejects.toThrow('between 0 and 10');
24
+ await expect(resolveEffectiveRetryLimit({ payloadRetryLimit: 2.5, dataDir: undefined })).rejects.toThrow('between 0 and 10');
25
+ });
26
+
27
+ test('sidecar default applies when no explicit value is given', async () => {
28
+ const dataDir = makeDataDir({ version: 1, defaultRetryLimit: 9 });
29
+ await expect(resolveEffectiveRetryLimit({ dataDir })).resolves.toBe(9);
30
+ });
31
+
32
+ test(`no sidecar resolves to undefined so Pi stays authoritative (built-in fallback ${PI_FALLBACK_RETRY_LIMIT})`, async () => {
33
+ // No settings file at all.
34
+ await expect(resolveEffectiveRetryLimit({ dataDir: makeDataDir(undefined) })).resolves.toBeUndefined();
35
+ // File exists but has no retry key.
36
+ await expect(resolveEffectiveRetryLimit({ dataDir: makeDataDir({ version: 1 }) })).resolves.toBeUndefined();
37
+ // null is treated as "no override", matching the store's normalize().
38
+ await expect(resolveEffectiveRetryLimit({ dataDir: makeDataDir({ version: 1, defaultRetryLimit: null }) })).resolves.toBeUndefined();
39
+ });
40
+
41
+ test('a malformed sidecar value fails loudly instead of silently falling back', async () => {
42
+ const badTypes = [3.5, -1, 11, 'five'];
43
+ for (const defaultRetryLimit of badTypes) {
44
+ const dataDir = makeDataDir({ version: 1, defaultRetryLimit });
45
+ await expect(resolveEffectiveRetryLimit({ dataDir })).rejects.toThrow(/retry limit|JSON/i);
46
+ }
47
+ // Malformed JSON surfaces as a syntax error, not a silent undefined.
48
+ const dataDir = mkdtempSync(join(tmpdir(), 'pichamber-retry-'));
49
+ mkdirSync(join(dataDir, 'pi'), { recursive: true });
50
+ writeFileSync(join(dataDir, 'pi', 'settings.json'), '{ not json');
51
+ await expect(resolveEffectiveRetryLimit({ dataDir })).rejects.toThrow();
52
+ });
53
+ });
@@ -0,0 +1,39 @@
1
+ import { posix, win32 } from 'node:path';
2
+
3
+ const pathApiFor = (platform) => platform === 'win32' ? win32 : posix;
4
+
5
+ const pathKey = (filePath, platform = process.platform) => {
6
+ const normalized = pathApiFor(platform).normalize(filePath);
7
+ return platform === 'win32' ? normalized.toLowerCase() : normalized;
8
+ };
9
+
10
+ /**
11
+ * Build the runtime-local lookup used to distinguish Pi skill loads from
12
+ * ordinary read calls. Skill names come from Pi's resource loader rather than
13
+ * from the SKILL.md parent directory because Pi allows those names to differ.
14
+ */
15
+ export function createSkillReadClassifier({ cwd, skills, platform = process.platform }) {
16
+ const skillsByPath = new Map();
17
+ const pathApi = pathApiFor(platform);
18
+ for (const skill of Array.isArray(skills) ? skills : []) {
19
+ if (!skill || typeof skill.name !== 'string' || typeof skill.filePath !== 'string') continue;
20
+ const name = skill.name.trim();
21
+ if (!name || !skill.filePath.trim()) continue;
22
+ const absolutePath = pathApi.isAbsolute(skill.filePath) ? skill.filePath : pathApi.resolve(cwd, skill.filePath);
23
+ skillsByPath.set(pathKey(absolutePath, platform), { name });
24
+ }
25
+
26
+ return (toolName, args) => {
27
+ if (typeof toolName !== 'string' || toolName.toLowerCase() !== 'read' || !args || typeof args !== 'object') {
28
+ return undefined;
29
+ }
30
+ const rawPath = typeof args.path === 'string'
31
+ ? args.path
32
+ : typeof args.file_path === 'string'
33
+ ? args.file_path
34
+ : undefined;
35
+ if (!rawPath?.trim()) return undefined;
36
+ const absolutePath = pathApi.isAbsolute(rawPath) ? rawPath : pathApi.resolve(cwd, rawPath);
37
+ return skillsByPath.get(pathKey(absolutePath, platform));
38
+ };
39
+ }
@@ -0,0 +1,41 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { join } from 'node:path';
3
+
4
+ import { createSkillReadClassifier } from './skill-read-classifier.js';
5
+
6
+ describe('skill read classifier', () => {
7
+ it('matches absolute and cwd-relative reads using Pi skill names', () => {
8
+ const cwd = join('/workspace', 'project');
9
+ const skillPath = join(cwd, '.agents', 'skills', 'directory-name', 'SKILL.md');
10
+ const classify = createSkillReadClassifier({
11
+ cwd,
12
+ skills: [{ name: 'frontmatter-name', filePath: skillPath }],
13
+ platform: 'linux',
14
+ });
15
+
16
+ expect(classify('read', { path: skillPath })).toEqual({ name: 'frontmatter-name' });
17
+ expect(classify('read', { path: join('.agents', 'skills', 'directory-name', 'SKILL.md') })).toEqual({ name: 'frontmatter-name' });
18
+ });
19
+
20
+ it('does not infer skills from filenames or classify other tools', () => {
21
+ const cwd = join('/workspace', 'project');
22
+ const classify = createSkillReadClassifier({
23
+ cwd,
24
+ skills: [{ name: 'known', filePath: join(cwd, '.agents', 'skills', 'known', 'SKILL.md') }],
25
+ platform: 'linux',
26
+ });
27
+
28
+ expect(classify('read', { path: join(cwd, 'notes', 'SKILL.md') })).toBeUndefined();
29
+ expect(classify('write', { path: join(cwd, '.agents', 'skills', 'known', 'SKILL.md') })).toBeUndefined();
30
+ });
31
+
32
+ it('normalizes Windows path casing', () => {
33
+ const classify = createSkillReadClassifier({
34
+ cwd: 'C:\\Workspace',
35
+ skills: [{ name: 'review', filePath: 'C:\\Workspace\\skills\\review\\SKILL.md' }],
36
+ platform: 'win32',
37
+ });
38
+
39
+ expect(classify('READ', { file_path: 'c:\\workspace\\SKILLS\\review\\skill.md' })).toEqual({ name: 'review' });
40
+ });
41
+ });
@@ -26,6 +26,9 @@ const delay = (milliseconds) => new Promise((resolveDelay) => setTimeout(resolve
26
26
 
27
27
  const rejectAfter = (promise, timeoutMs, code) => new Promise((resolvePromise, rejectPromise) => {
28
28
  const timer = setTimeout(() => rejectPromise(new SessionDaemonClientError(code)), timeoutMs);
29
+ // The wrapped request owns its own timeout lifecycle; never hold process
30
+ // shutdown on this outer deadline.
31
+ timer.unref?.();
29
32
  promise.then(
30
33
  (value) => {
31
34
  clearTimeout(timer);
@@ -0,0 +1,104 @@
1
+ import {
2
+ createAgentSessionFromServices,
3
+ createAgentSessionRuntime,
4
+ createAgentSessionServices,
5
+ getAgentDir,
6
+ SessionManager,
7
+ } from '@earendil-works/pi-coding-agent';
8
+
9
+ const DEFAULT_TIMEOUT_MS = 30_000;
10
+
11
+ const resolveAgentDir = () => {
12
+ const configured = typeof process.env.PICHAMBER_PI_AGENT_DIR === 'string'
13
+ ? process.env.PICHAMBER_PI_AGENT_DIR.trim()
14
+ : '';
15
+ return configured || getAgentDir();
16
+ };
17
+
18
+ const readAssistantText = (messages) => {
19
+ const assistant = [...(Array.isArray(messages) ? messages : [])]
20
+ .reverse()
21
+ .find((message) => message?.role === 'assistant');
22
+ if (!assistant) return '';
23
+ if (typeof assistant.content === 'string') return assistant.content.trim();
24
+ if (!Array.isArray(assistant.content)) return '';
25
+ return assistant.content
26
+ .filter((part) => part?.type === 'text' && typeof part.text === 'string')
27
+ .map((part) => part.text)
28
+ .join('')
29
+ .trim();
30
+ };
31
+
32
+ export const createSmallModelGenerator = ({
33
+ agentDir = resolveAgentDir(),
34
+ timeoutMs = DEFAULT_TIMEOUT_MS,
35
+ createServices = createAgentSessionServices,
36
+ createSession = createAgentSessionFromServices,
37
+ createRuntime = createAgentSessionRuntime,
38
+ inMemorySession = (cwd) => SessionManager.inMemory(cwd),
39
+ } = {}) => async ({ directory, prompt, model }) => {
40
+ if (typeof directory !== 'string' || directory.length === 0) throw new Error('Small-model directory is required');
41
+ if (typeof prompt !== 'string' || prompt.trim().length === 0) throw new Error('Small-model prompt is required');
42
+ if (!model || typeof model.providerId !== 'string' || typeof model.modelId !== 'string') {
43
+ const error = new Error('No small model is configured');
44
+ error.code = 'SMALL_MODEL_UNCONFIGURED';
45
+ throw error;
46
+ }
47
+
48
+ const runtimeFactory = async ({ cwd, agentDir: runtimeAgentDir, sessionManager, sessionStartEvent }) => {
49
+ const services = await createServices({
50
+ cwd,
51
+ agentDir: runtimeAgentDir,
52
+ resourceLoaderOptions: { noExtensions: true },
53
+ });
54
+ const selectedModel = services.modelRuntime.getModel(model.providerId, model.modelId);
55
+ if (!selectedModel) {
56
+ const error = new Error('The configured small model is unavailable');
57
+ error.code = 'SMALL_MODEL_UNAVAILABLE';
58
+ throw error;
59
+ }
60
+ return {
61
+ ...(await createSession({
62
+ services,
63
+ sessionManager,
64
+ sessionStartEvent,
65
+ model: selectedModel,
66
+ noTools: 'all',
67
+ })),
68
+ services,
69
+ diagnostics: services.diagnostics,
70
+ };
71
+ };
72
+
73
+ const runtime = await createRuntime(runtimeFactory, {
74
+ cwd: directory,
75
+ agentDir,
76
+ sessionManager: inMemorySession(directory),
77
+ });
78
+
79
+ let timer;
80
+ try {
81
+ await runtime.session.sendUserMessage(prompt.trim(), { expandPromptTemplates: false });
82
+ await Promise.race([
83
+ runtime.session.waitForIdle(),
84
+ new Promise((_, reject) => {
85
+ timer = setTimeout(() => {
86
+ void runtime.session.abort().catch(() => undefined);
87
+ const error = new Error('Small-model generation timed out');
88
+ error.code = 'SMALL_MODEL_TIMEOUT';
89
+ reject(error);
90
+ }, timeoutMs);
91
+ timer.unref?.();
92
+ }),
93
+ ]);
94
+ const text = readAssistantText(runtime.session.messages);
95
+ if (!text) throw new Error('The small model returned an empty response');
96
+ return { text };
97
+ } finally {
98
+ clearTimeout(timer);
99
+ if (runtime.session.isStreaming) await runtime.session.abort().catch(() => undefined);
100
+ await runtime.dispose();
101
+ }
102
+ };
103
+
104
+ export const generateWithSmallModel = createSmallModelGenerator();
@@ -0,0 +1,66 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+
3
+ import { createSmallModelGenerator } from './small-model-generation.js';
4
+
5
+ const createHarness = ({ waitForIdle = async () => undefined, timeoutMs = 100 } = {}) => {
6
+ const abort = vi.fn(async () => undefined);
7
+ const dispose = vi.fn(async () => undefined);
8
+ const session = {
9
+ sendUserMessage: vi.fn(async () => undefined),
10
+ waitForIdle,
11
+ abort,
12
+ isStreaming: false,
13
+ messages: [{ role: 'assistant', content: [{ type: 'text', text: 'fix-auth-timeout' }] }],
14
+ };
15
+ const selectedModel = { provider: 'provider', id: 'small' };
16
+ const createSession = vi.fn(async () => ({ session }));
17
+ const generate = createSmallModelGenerator({
18
+ agentDir: '/agent',
19
+ timeoutMs,
20
+ inMemorySession: () => ({ kind: 'memory' }),
21
+ createServices: async () => ({
22
+ modelRuntime: { getModel: () => selectedModel },
23
+ diagnostics: [],
24
+ }),
25
+ createSession,
26
+ createRuntime: async (factory, options) => ({
27
+ ...(await factory({
28
+ cwd: options.cwd,
29
+ agentDir: options.agentDir,
30
+ sessionManager: options.sessionManager,
31
+ })),
32
+ dispose,
33
+ }),
34
+ });
35
+ return { abort, createSession, dispose, generate, selectedModel, session };
36
+ };
37
+
38
+ describe('small-model generation', () => {
39
+ it('uses an in-memory no-tools session and returns only assistant text', async () => {
40
+ const harness = createHarness();
41
+ await expect(harness.generate({
42
+ directory: '/repo',
43
+ prompt: 'Name this task',
44
+ model: { providerId: 'provider', modelId: 'small' },
45
+ })).resolves.toEqual({ text: 'fix-auth-timeout' });
46
+
47
+ expect(harness.createSession).toHaveBeenCalledWith(expect.objectContaining({
48
+ model: harness.selectedModel,
49
+ noTools: 'all',
50
+ sessionManager: { kind: 'memory' },
51
+ }));
52
+ expect(harness.session.sendUserMessage).toHaveBeenCalledWith('Name this task', { expandPromptTemplates: false });
53
+ expect(harness.dispose).toHaveBeenCalledOnce();
54
+ });
55
+
56
+ it('aborts and disposes a timed-out generation', async () => {
57
+ const harness = createHarness({ waitForIdle: () => new Promise(() => {}), timeoutMs: 5 });
58
+ await expect(harness.generate({
59
+ directory: '/repo',
60
+ prompt: 'Name this task',
61
+ model: { providerId: 'provider', modelId: 'small' },
62
+ })).rejects.toThrow('timed out');
63
+ expect(harness.abort).toHaveBeenCalledOnce();
64
+ expect(harness.dispose).toHaveBeenCalledOnce();
65
+ });
66
+ });
@@ -1190,6 +1190,16 @@ export const createPreviewProxyRuntime = ({
1190
1190
  createProxyMiddleware,
1191
1191
  responseInterceptor,
1192
1192
  }) => {
1193
+ // Preview tokens gate arbitrary loopback proxying, so compare in constant time.
1194
+ // Length mismatch returns false without comparing (timingSafeEqual throws).
1195
+ const tokensMatch = (provided, expected) => {
1196
+ if (typeof provided !== 'string' || provided.length === 0) return false;
1197
+ const a = Buffer.from(provided);
1198
+ const b = Buffer.from(expected);
1199
+ if (a.length !== b.length) return false;
1200
+ return crypto.timingSafeEqual(a, b);
1201
+ };
1202
+
1193
1203
  const targets = new Map();
1194
1204
  let sweepTimer = null;
1195
1205
 
@@ -1247,7 +1257,7 @@ export const createPreviewProxyRuntime = ({
1247
1257
 
1248
1258
  const cookies = parseCookieHeader(req.headers?.cookie);
1249
1259
  const token = parsed.searchParams.get(TOKEN_QUERY_PARAM) || cookies.get(TOKEN_COOKIE_NAME) || '';
1250
- if (!token || token !== entry.token) {
1260
+ if (!token || !tokensMatch(token, entry.token)) {
1251
1261
  return { ok: false, status: 403, code: 'invalid-token', error: 'Preview token missing' };
1252
1262
  }
1253
1263
 
@@ -47,6 +47,9 @@ const createAttachedPreviewRuntime = () => {
47
47
  randomByte += 1;
48
48
  return Buffer.alloc(size, randomByte);
49
49
  },
50
+ timingSafeEqual(a, b) {
51
+ return Buffer.compare(a, b) === 0;
52
+ },
50
53
  },
51
54
  URL,
52
55
  createProxyMiddleware(options) {
@@ -32,6 +32,7 @@ const ALLOWED_WS_PATHS = new Set([
32
32
  '/api/global/event/ws',
33
33
  '/api/event/ws',
34
34
  '/api/terminal/ws',
35
+ '/api/stt/ws',
35
36
  ]);
36
37
 
37
38
  // Hop-by-hop headers stripped from tunneled requests; `host` is set by fetch
@@ -0,0 +1,38 @@
1
+ # Speech-to-text module
2
+
3
+ This module owns final-only composer dictation for web, Electron, hosted mobile, and Capacitor clients. Clients capture mono 16 kHz PCM16 and send binary frames over `/api/stt/ws`. The server buffers bounded segments, commits long recordings at silence or a 90 second hard limit, and returns one combined transcript after `Done`. It never emits incremental transcript text.
4
+
5
+ ## Ownership
6
+
7
+ - `runtime.js` registers the HTTP and WebSocket routes before static fallback routes and shuts sockets, streams, and workers down with the server.
8
+ - `protocol.js` defines the version 1 control messages and binary frame header. A binary frame is a four-byte little-endian sequence followed by PCM16LE bytes.
9
+ - `stream-manager.js` owns ordering, reconnect attachment, five-minute limits, silence detection, segmentation, final ordering, cancellation, and cleanup. A disconnected recording remains for 30 seconds so the client can reconnect. The client also retains the bounded recording and replays from the server's contiguous acknowledgement.
10
+ - `service.js` resolves server-stored provider IDs, model state, downloads, and worker lifecycle.
11
+ - `providers/` adapts one complete committed PCM buffer to either the local worker or an OpenAI-compatible `/v1/audio/transcriptions` endpoint.
12
+ - `local/` owns the pinned model catalog, atomic downloader, native-addon loader, forked worker, bounded two-engine LRU, and one-at-a-time inference queue.
13
+
14
+ ## Routes
15
+
16
+ - `GET /api/stt/status`
17
+ - `PUT /api/stt/config`
18
+ - `POST /api/stt/models/:modelId/download`
19
+ - `DELETE /api/stt/models/:modelId`
20
+ - `WS /api/stt/ws`
21
+
22
+ All routes use the existing `/api` authentication middleware. The WebSocket path is in both the URL-token and private-relay allowlists. Shared UI opens it through `openRuntimeWebSocket` after minting URL auth.
23
+
24
+ Remote URL and API-key values live in `<PiChamber data>/stt/config.json` with owner-only permissions where the platform supports them. Status responses redact API keys. WebSocket start frames carry only a stored provider configuration ID. They never accept a URL or credential.
25
+
26
+ Local models live under `<PiChamber data>/speech-models`. Downloads verify a pinned archive size and SHA-256 checksum, extract into a staging directory, hash required installed files into a manifest, and rename only after verification. Missing, changed-size, or checksum-invalid models are removed before retry. The main server process never imports `sherpa-onnx-node`; only `worker-process.js` does.
27
+
28
+ ## Performance contract
29
+
30
+ - Show recording UI within 100 ms after microphone permission succeeds.
31
+ - Send 250 ms binary chunks, about 32 KB/s.
32
+ - Keep audio bounded to five minutes on client and server.
33
+ - Keep audio level events outside broad React state. The visualizer coalesces them with `requestAnimationFrame` and writes only `transform` and `opacity`.
34
+ - Send one IPC request per committed segment, not one per network chunk.
35
+ - Limit local inference to one operation at a time, cache at most two engines, and stop the worker after five idle minutes.
36
+ - Measure model load separately from warm transcription. Use `bun run benchmark:stt`; see `scripts/stt/DOCUMENTATION.md`.
37
+
38
+ Cancellation, socket failure, runtime switching, empty audio, model errors, and provider errors remove buffered audio and do not mutate the composer draft. Only a successful final transcript reaches the editor.
@@ -0,0 +1,47 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { createReadStream } from 'node:fs';
3
+
4
+ export const PCM_SAMPLE_RATE = 16_000;
5
+ export const PCM_BYTES_PER_SECOND = PCM_SAMPLE_RATE * 2;
6
+
7
+ const asInt16 = (pcm16) => new Int16Array(pcm16.buffer, pcm16.byteOffset, pcm16.byteLength / 2);
8
+
9
+ export function pcm16Peak(pcm16) {
10
+ if (!Buffer.isBuffer(pcm16) || pcm16.byteLength % 2 !== 0) throw new Error('PCM16 audio must contain complete samples');
11
+ let peak = 0;
12
+ for (const sample of asInt16(pcm16)) peak = Math.max(peak, Math.abs(sample));
13
+ return peak;
14
+ }
15
+
16
+ export function pcm16ToFloat32(pcm16, gain = 1) {
17
+ const input = asInt16(pcm16);
18
+ const output = new Float32Array(input.length);
19
+ for (let index = 0; index < input.length; index += 1) {
20
+ output[index] = Math.max(-1, Math.min(1, (input[index] / 32768) * gain));
21
+ }
22
+ return output;
23
+ }
24
+
25
+ export function pcm16ToWav(pcm16, sampleRate = PCM_SAMPLE_RATE) {
26
+ const wav = Buffer.allocUnsafe(44 + pcm16.byteLength);
27
+ wav.write('RIFF', 0);
28
+ wav.writeUInt32LE(36 + pcm16.byteLength, 4);
29
+ wav.write('WAVEfmt ', 8);
30
+ wav.writeUInt32LE(16, 16);
31
+ wav.writeUInt16LE(1, 20);
32
+ wav.writeUInt16LE(1, 22);
33
+ wav.writeUInt32LE(sampleRate, 24);
34
+ wav.writeUInt32LE(sampleRate * 2, 28);
35
+ wav.writeUInt16LE(2, 32);
36
+ wav.writeUInt16LE(16, 34);
37
+ wav.write('data', 36);
38
+ wav.writeUInt32LE(pcm16.byteLength, 40);
39
+ pcm16.copy(wav, 44);
40
+ return wav;
41
+ }
42
+
43
+ export async function sha256File(file) {
44
+ const hash = createHash('sha256');
45
+ for await (const chunk of createReadStream(file)) hash.update(chunk);
46
+ return hash.digest('hex');
47
+ }
@@ -0,0 +1,81 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { chmod, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+
5
+ import { DEFAULT_LOCAL_STT_MODEL, isLocalSttModelId } from './local/model-catalog.js';
6
+
7
+ const DEFAULT_CONFIG = Object.freeze({ enabled: false, providerConfigId: 'local', language: '', localModelId: DEFAULT_LOCAL_STT_MODEL, providers: [] });
8
+ const ID_PATTERN = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/;
9
+
10
+ const cleanString = (value, max = 512) => typeof value === 'string' ? value.trim().slice(0, max) : '';
11
+
12
+ function normalizeProvider(value, previous) {
13
+ const id = cleanString(value?.id, 64);
14
+ if (!ID_PATTERN.test(id) || id === 'local') throw new Error('Invalid STT provider configuration id');
15
+ const baseUrl = cleanString(value?.baseUrl, 2048);
16
+ const parsed = new URL(baseUrl);
17
+ if (!['http:', 'https:'].includes(parsed.protocol)) throw new Error('STT provider URL must use HTTP or HTTPS');
18
+ const model = cleanString(value?.model, 256);
19
+ if (!model) throw new Error('STT provider model is required');
20
+ let apiKey = previous?.apiKey || '';
21
+ if (value?.clearApiKey === true) apiKey = '';
22
+ else if (typeof value?.apiKey === 'string' && value.apiKey.trim()) apiKey = value.apiKey.trim().slice(0, 4096);
23
+ return { id, label: cleanString(value?.label, 100) || id, baseUrl: parsed.toString(), model, apiKey };
24
+ }
25
+
26
+ function normalizeConfig(value) {
27
+ const providers = Array.isArray(value?.providers)
28
+ ? value.providers.slice(0, 8).map((entry) => normalizeProvider(entry))
29
+ : [];
30
+ const providerConfigId = value?.providerConfigId === 'local' || providers.some((provider) => provider.id === value?.providerConfigId)
31
+ ? value.providerConfigId
32
+ : 'local';
33
+ return {
34
+ enabled: value?.enabled === true,
35
+ providerConfigId,
36
+ language: cleanString(value?.language, 35),
37
+ localModelId: isLocalSttModelId(value?.localModelId) ? value.localModelId : DEFAULT_LOCAL_STT_MODEL,
38
+ providers,
39
+ };
40
+ }
41
+
42
+ const publicConfig = (config) => ({
43
+ ...config,
44
+ providers: config.providers.map(({ apiKey, ...provider }) => ({ ...provider, apiKeyConfigured: Boolean(apiKey) })),
45
+ });
46
+
47
+ export function createSttConfigStore({ file, fs = { chmod, mkdir, readFile, rename, rm, writeFile } }) {
48
+ let mutation = Promise.resolve();
49
+ const read = async () => {
50
+ try { return normalizeConfig(JSON.parse(await fs.readFile(file, 'utf8'))); }
51
+ catch (error) { if (error?.code === 'ENOENT') return { ...DEFAULT_CONFIG, providers: [] }; throw new Error('STT configuration is invalid'); }
52
+ };
53
+ const write = async (changes) => {
54
+ const operation = mutation.then(async () => {
55
+ const current = await read();
56
+ let providers = current.providers;
57
+ if (changes?.remoteProvider) {
58
+ const id = cleanString(changes.remoteProvider.id, 64);
59
+ const previous = providers.find((entry) => entry.id === id);
60
+ const updated = normalizeProvider(changes.remoteProvider, previous);
61
+ providers = [...providers.filter((entry) => entry.id !== id), updated].slice(-8);
62
+ }
63
+ if (typeof changes?.deleteProviderId === 'string') providers = providers.filter((entry) => entry.id !== changes.deleteProviderId);
64
+ const next = normalizeConfig({ ...current, ...changes, providers });
65
+ await fs.mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
66
+ const temporary = `${file}.tmp-${process.pid}-${randomUUID()}`;
67
+ try {
68
+ await fs.writeFile(temporary, `${JSON.stringify(next, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 });
69
+ await fs.rename(temporary, file);
70
+ if (process.platform !== 'win32') await fs.chmod(file, 0o600);
71
+ return next;
72
+ } catch (error) {
73
+ await fs.rm(temporary, { force: true }).catch(() => {});
74
+ throw error;
75
+ }
76
+ });
77
+ mutation = operation.catch(() => {});
78
+ return operation;
79
+ };
80
+ return { read, write, readPublic: async () => publicConfig(await read()), publicConfig };
81
+ }
@@ -0,0 +1,36 @@
1
+ import { afterEach, describe, expect, test } from 'bun:test';
2
+ import { mkdtemp, readFile, rm } from 'node:fs/promises';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+
6
+ import { createSttConfigStore } from './config-store.js';
7
+
8
+ const roots = [];
9
+ afterEach(async () => { await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))); });
10
+
11
+ describe('STT config store', () => {
12
+ test('persists provider credentials but redacts them from public configuration', async () => {
13
+ const root = await mkdtemp(path.join(os.tmpdir(), 'pichamber-stt-'));
14
+ roots.push(root);
15
+ const file = path.join(root, 'stt', 'config.json');
16
+ const store = createSttConfigStore({ file });
17
+ await store.write({
18
+ enabled: true,
19
+ remoteProvider: { id: 'remote', baseUrl: 'https://speech.example/v1', model: 'whisper-1', apiKey: 'secret-value' },
20
+ providerConfigId: 'remote',
21
+ });
22
+ const saved = JSON.parse(await readFile(file, 'utf8'));
23
+ expect(saved.providers[0].apiKey).toBe('secret-value');
24
+ expect(await store.readPublic()).toMatchObject({ providers: [{ id: 'remote', apiKeyConfigured: true }] });
25
+ expect(JSON.stringify(await store.readPublic())).not.toContain('secret-value');
26
+ });
27
+
28
+ test('keeps an existing key when an update omits it', async () => {
29
+ const root = await mkdtemp(path.join(os.tmpdir(), 'pichamber-stt-'));
30
+ roots.push(root);
31
+ const store = createSttConfigStore({ file: path.join(root, 'config.json') });
32
+ await store.write({ remoteProvider: { id: 'remote', baseUrl: 'https://speech.example/v1', model: 'one', apiKey: 'kept' } });
33
+ await store.write({ remoteProvider: { id: 'remote', baseUrl: 'https://speech.example/v1', model: 'two' } });
34
+ expect((await store.read()).providers[0]).toMatchObject({ model: 'two', apiKey: 'kept' });
35
+ });
36
+ });
@@ -0,0 +1,57 @@
1
+ import path from 'node:path';
2
+
3
+ export const LOCAL_STT_MODEL_CATALOG = Object.freeze({
4
+ 'parakeet-tdt-0.6b-v2-int8': {
5
+ type: 'nemo_transducer',
6
+ description: 'NVIDIA Parakeet TDT v2, English',
7
+ sizeBytes: 482_468_385,
8
+ sha256: '157c157bc51155e03e37d2466522a3a737dd9c72bb25f36eb18912964161e1ad',
9
+ archiveUrl: 'https://github.com/k2-fsa/sherpa-onnx/releases/download/asr-models/sherpa-onnx-nemo-parakeet-tdt-0.6b-v2-int8.tar.bz2',
10
+ extractedDir: 'sherpa-onnx-nemo-parakeet-tdt-0.6b-v2-int8',
11
+ files: { encoder: 'encoder.int8.onnx', decoder: 'decoder.int8.onnx', joiner: 'joiner.int8.onnx', tokens: 'tokens.txt' },
12
+ },
13
+ 'parakeet-tdt-0.6b-v3-int8': {
14
+ type: 'nemo_transducer',
15
+ description: 'NVIDIA Parakeet TDT v3, multilingual',
16
+ sizeBytes: 487_170_055,
17
+ sha256: '5793d0fd397c5778d2cf2126994d58e9d56b1be7c04d13c7a15bb1b4eafb16bf',
18
+ archiveUrl: 'https://github.com/k2-fsa/sherpa-onnx/releases/download/asr-models/sherpa-onnx-nemo-parakeet-tdt-0.6b-v3-int8.tar.bz2',
19
+ extractedDir: 'sherpa-onnx-nemo-parakeet-tdt-0.6b-v3-int8',
20
+ files: { encoder: 'encoder.int8.onnx', decoder: 'decoder.int8.onnx', joiner: 'joiner.int8.onnx', tokens: 'tokens.txt' },
21
+ },
22
+ 'whisper-base-int8': {
23
+ type: 'whisper',
24
+ description: 'OpenAI Whisper base, multilingual',
25
+ sizeBytes: 207_557_382,
26
+ sha256: '911b2083efd7c0dca2ac3b358b75222660dc09fb716d64fbfc417ba6c99ff3de',
27
+ archiveUrl: 'https://github.com/k2-fsa/sherpa-onnx/releases/download/asr-models/sherpa-onnx-whisper-base.tar.bz2',
28
+ extractedDir: 'sherpa-onnx-whisper-base',
29
+ files: { encoder: 'base-encoder.int8.onnx', decoder: 'base-decoder.int8.onnx', tokens: 'base-tokens.txt' },
30
+ },
31
+ 'whisper-tiny-int8': {
32
+ type: 'whisper',
33
+ description: 'OpenAI Whisper tiny, multilingual',
34
+ sizeBytes: 116_204_861,
35
+ sha256: 'c46116994e539aa165266d96b325252728429c12535eb9d8b6a2b10f129e66b1',
36
+ archiveUrl: 'https://github.com/k2-fsa/sherpa-onnx/releases/download/asr-models/sherpa-onnx-whisper-tiny.tar.bz2',
37
+ extractedDir: 'sherpa-onnx-whisper-tiny',
38
+ files: { encoder: 'tiny-encoder.int8.onnx', decoder: 'tiny-decoder.int8.onnx', tokens: 'tiny-tokens.txt' },
39
+ },
40
+ });
41
+
42
+ export const LOCAL_STT_MODEL_IDS = Object.freeze(Object.keys(LOCAL_STT_MODEL_CATALOG));
43
+ export const DEFAULT_LOCAL_STT_MODEL = 'parakeet-tdt-0.6b-v2-int8';
44
+
45
+ export function isLocalSttModelId(value) {
46
+ return typeof value === 'string' && Object.hasOwn(LOCAL_STT_MODEL_CATALOG, value);
47
+ }
48
+
49
+ export function getLocalSttModelSpec(modelId) {
50
+ if (!isLocalSttModelId(modelId)) throw new Error('Unknown STT model');
51
+ const spec = LOCAL_STT_MODEL_CATALOG[modelId];
52
+ return { id: modelId, ...spec, requiredFiles: Object.values(spec.files) };
53
+ }
54
+
55
+ export function getLocalSttModelDir(modelsDir, modelId) {
56
+ return path.join(modelsDir, getLocalSttModelSpec(modelId).extractedDir);
57
+ }