@pi-chamber/web 0.3.3 → 0.5.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.
- package/README.md +1 -0
- package/bin/lib/cli-startup.js +1 -0
- package/dist/assets/CommitSection-Cz-ACBaD.js +1 -0
- package/dist/assets/DiagramEditor-BNUOrd9m.js +1 -0
- package/dist/assets/DiagramView-D4YR9YRt.js +1 -0
- package/dist/assets/{DiffView-DGD9DMS7.js → DiffView-DPW8dcg_.js} +3 -3
- package/dist/assets/FilesView-BFGIdY6b.js +14 -0
- package/dist/assets/GitView-CKtiKOfJ.js +6 -0
- package/dist/assets/JsonTreeView-c-UJUw3D.js +1 -0
- package/dist/assets/{MarkdownRendererImpl-V1HMFCjr.js → MarkdownRendererImpl-CvC9eXoa.js} +2 -2
- package/dist/assets/PatchDiff-YGHsZUIR.js +1 -0
- package/dist/assets/PierreDiffViewer-CoXa-JJK.js +136 -0
- package/dist/assets/SessionSwitcherContent-B7eep3dO.js +1 -0
- package/dist/assets/SessionSwitcherDropdown-CZOFeJHH.js +2 -0
- package/dist/assets/SessionUnreadDot-ClpeYFPz.js +1 -0
- package/dist/assets/SettingsView-CPmHHDbQ.js +4 -0
- package/dist/assets/SettingsWindow-2CBpoJ8H.js +1 -0
- package/dist/assets/{ToolOutputDialog-2zKUdGYL.js → ToolOutputDialog-HMW-Kh19.js} +6 -6
- package/dist/assets/ToolPartDiffPreview-C3nbNbxk.js +8 -0
- package/dist/assets/{VirtualizedFileDiff-UMgLcO4Q.js → VirtualizedFileDiff-DEX83nQ0.js} +3 -3
- package/dist/assets/{SessionSwitcherDropdown-o1RjhCfF.js → WindowsWindowControls-PPk5H89-.js} +172 -118
- package/dist/assets/collapsible-Dux-9hAC.js +1 -0
- package/dist/assets/computeVirtualFileMetrics-Cy0nxMJB.js +3 -0
- package/dist/assets/contextFileOpenGuard-Dn_38hd9.js +1 -0
- package/dist/assets/index--zDkVFU6.css +1 -0
- package/dist/assets/index-DU2OBBy5.js +8 -0
- package/dist/assets/index-EN7MioVf.js +1 -0
- package/dist/assets/isDiffPlainText-DSWRVq-W.js +1 -0
- package/dist/assets/isFilePlainText-7RAjjrQ5.js +1 -0
- package/dist/assets/{main-CmkRaMOR.js → main-BGKjg-qW.js} +8 -8
- package/dist/assets/main-DGHrBx_u.js +2 -0
- package/dist/assets/markdownCore-BYPqQtbE.js +3 -0
- package/dist/assets/miniChat-DW2PVX49.js +2 -0
- package/dist/assets/mobile-0Gxc02iO.js +2 -0
- package/dist/assets/renderElectronMiniChatApp-C-qpqp1i.js +2 -0
- package/dist/assets/renderMobileApp-UB9bhC1x.js +14 -0
- package/dist/assets/{runtimeSurface-CkHYYg0E.js → runtimeSurface-DefD-2Iv.js} +1 -1
- package/dist/assets/{useInlineCommentController-DD31jQNC.js → useInlineCommentController-B8p2XwXA.js} +2 -2
- package/dist/assets/usePanelSlide-CbqVf-y8.js +56 -0
- package/dist/assets/usePushVisibilityBeacon-CvjN-47R.js +10 -0
- package/dist/assets/useSwitcherItems-B6_F-J-z.js +1 -0
- package/dist/assets/{vendor-codemirror-language-data-Dp_Z-0GD.js → vendor-codemirror-language-data-BhBdEPsJ.js} +2 -2
- package/dist/assets/{vendor-katex-CHD9BdDO.js → vendor-katex-CNckGUMB.js} +1 -1
- package/dist/assets/{vendor-marked-i_gIkIP3.js → vendor-marked-CX41MkDF.js} +1 -1
- package/dist/assets/{web-components-Cct1r-wn.js → web-components-C9yVPsWN.js} +2 -2
- package/dist/index.html +8 -5
- package/dist/mini-chat.html +7 -4
- package/dist/mobile.html +7 -4
- package/dist/sw.js +1 -1
- package/package.json +1 -1
- package/server/index.js +27 -5
- package/server/lib/fs/routes.js +0 -21
- package/server/lib/git/DOCUMENTATION.md +15 -5
- package/server/lib/git/issue-2746-longpaths.test.js +11 -11
- package/server/lib/git/routes.js +80 -4
- package/server/lib/git/routes.test.js +135 -0
- package/server/lib/git/service.js +144 -82
- package/server/lib/git/service.test.js +182 -36
- package/server/lib/pi/extension-protocol.js +62 -0
- package/server/lib/pi/extension-protocol.test.js +34 -0
- package/server/lib/pi/fixtures/pichamber-gui-demo.ts +251 -0
- package/server/lib/pi/routes-extension-events.test.js +152 -0
- package/server/lib/pi/routes.js +345 -7
- package/server/lib/pi/routes.test.js +43 -28
- package/server/lib/pi/session-daemon/DOCUMENTATION.md +8 -5
- package/server/lib/pi/session-daemon/extension-bridge.js +488 -0
- package/server/lib/pi/session-daemon/message-entry-aliases.js +53 -13
- package/server/lib/pi/session-daemon/message-entry-aliases.test.js +110 -0
- package/server/lib/pi/session-daemon/session-daemon-extensions.e2e.test.js +215 -0
- package/server/lib/pi/session-daemon/session-daemon-extensions.test.js +559 -0
- package/server/lib/pi/session-daemon/session-daemon.js +483 -54
- package/server/lib/pi/session-daemon/session-daemon.test.js +212 -4
- package/server/lib/pi/session-daemon/session-retry-limits.js +55 -0
- package/server/lib/pi/session-daemon/session-retry-limits.test.js +53 -0
- package/server/lib/pi/session-daemon/skill-read-classifier.js +39 -0
- package/server/lib/pi/session-daemon/skill-read-classifier.test.js +41 -0
- package/server/lib/pi/session-daemon/supervisor.js +3 -0
- package/server/lib/pi/small-model-generation.js +104 -0
- package/server/lib/pi/small-model-generation.test.js +66 -0
- package/server/lib/preview/proxy-runtime.js +11 -1
- package/server/lib/preview/proxy-runtime.test.js +3 -0
- package/server/lib/relay/tunnel-host.js +1 -0
- package/server/lib/server/cors.js +0 -2
- package/server/lib/server/cors.test.js +4 -4
- package/server/lib/stt/DOCUMENTATION.md +38 -0
- package/server/lib/stt/audio.js +47 -0
- package/server/lib/stt/config-store.js +81 -0
- package/server/lib/stt/config-store.test.js +36 -0
- package/server/lib/stt/local/model-catalog.js +57 -0
- package/server/lib/stt/local/model-downloader.js +127 -0
- package/server/lib/stt/local/recognizer.js +64 -0
- package/server/lib/stt/local/sherpa-loader.js +43 -0
- package/server/lib/stt/local/worker-client.js +115 -0
- package/server/lib/stt/local/worker-process.js +64 -0
- package/server/lib/stt/protocol.js +38 -0
- package/server/lib/stt/protocol.test.js +17 -0
- package/server/lib/stt/providers/local-worker-provider.js +11 -0
- package/server/lib/stt/providers/openai-compatible-provider.js +31 -0
- package/server/lib/stt/providers/openai-compatible-provider.test.js +31 -0
- package/server/lib/stt/runtime.js +111 -0
- package/server/lib/stt/service.js +106 -0
- package/server/lib/stt/stream-manager.js +188 -0
- package/server/lib/stt/stream-manager.test.js +64 -0
- package/server/lib/ui-auth/DOCUMENTATION.md +1 -1
- package/server/lib/ui-auth/ui-auth.js +8 -3
- package/server/lib/ui-auth/ui-auth.test.js +8 -0
- package/server/lib/workspace/host.js +19 -3
- package/dist/assets/CommitSection-BAYzLtBf.js +0 -1
- package/dist/assets/DiagramEditor-D1yc4joK.js +0 -1
- package/dist/assets/DiagramView-CAlJiG11.js +0 -1
- package/dist/assets/FilesView-DB5VI7EN.js +0 -14
- package/dist/assets/GitView-CFlPcSn9.js +0 -6
- package/dist/assets/JsonTreeView-CoX1ZscV.js +0 -1
- package/dist/assets/PatchDiff-D6Gs7K5B.js +0 -1
- package/dist/assets/PierreDiffViewer-COYd5Qr-.js +0 -136
- package/dist/assets/SettingsView-BYqvfMTS.js +0 -4
- package/dist/assets/SettingsWindow-CtNS0tQn.js +0 -1
- package/dist/assets/ToolPartDiffPreview-CBFC9min.js +0 -8
- package/dist/assets/collapsible-Kx4bmsQM.js +0 -1
- package/dist/assets/computeVirtualFileMetrics-DdOCbMyK.js +0 -3
- package/dist/assets/contextFileOpenGuard-BRldMp0d.js +0 -1
- package/dist/assets/index-BAqpUCjs.js +0 -8
- package/dist/assets/index-CuSNEV7s.js +0 -1
- package/dist/assets/index-riABQmQ_.css +0 -1
- package/dist/assets/isDiffPlainText-CGIf0q8p.js +0 -1
- package/dist/assets/isFilePlainText-D4hgTRxT.js +0 -1
- package/dist/assets/main-By_pvk90.js +0 -2
- package/dist/assets/markdownCore-CAVCyFnI.js +0 -2
- package/dist/assets/miniChat-_XK2gGZE.js +0 -2
- package/dist/assets/mobile-B4E4JqAf.js +0 -2
- package/dist/assets/renderElectronMiniChatApp-Ca4hZgIz.js +0 -1
- package/dist/assets/renderMobileApp-ClA5Cnmw.js +0 -14
- package/dist/assets/usePanelSlide-a4c67FIY.js +0 -56
- package/dist/assets/useWindowTitle-DoHrUC5r.js +0 -10
- package/server/lib/pi/legacy-ui-model-defaults.js +0 -57
- package/server/lib/pi/legacy-ui-model-defaults.test.js +0 -65
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
import { PCM_BYTES_PER_SECOND, PCM_SAMPLE_RATE, pcm16Peak } from './audio.js';
|
|
2
|
+
|
|
3
|
+
const MAX_RECORDING_BYTES = 5 * 60 * PCM_BYTES_PER_SECOND;
|
|
4
|
+
const SEGMENT_MIN_BYTES = 60 * PCM_BYTES_PER_SECOND;
|
|
5
|
+
const SEGMENT_MAX_BYTES = 90 * PCM_BYTES_PER_SECOND;
|
|
6
|
+
const SILENCE_PEAK = 300;
|
|
7
|
+
const RECONNECT_GRACE_MS = 30_000;
|
|
8
|
+
const FINAL_TIMEOUT_MS = 5 * 60 * 1000;
|
|
9
|
+
const MAX_STREAMS = 8;
|
|
10
|
+
const MAX_REORDERED_CHUNKS = 64;
|
|
11
|
+
|
|
12
|
+
const send = (state, message) => {
|
|
13
|
+
try { state.emit?.({ version: 1, recordingId: state.id, ...message }); } catch {}
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
export class SttStreamManager {
|
|
17
|
+
constructor({ createTranscriber }) {
|
|
18
|
+
this.createTranscriber = createTranscriber;
|
|
19
|
+
this.streams = new Map();
|
|
20
|
+
this.pendingStarts = new Map();
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
async start({ recordingId, providerConfigId, emit }) {
|
|
24
|
+
if (typeof recordingId !== 'string' || !/^[a-zA-Z0-9-]{16,128}$/.test(recordingId)) throw new Error('Invalid recording id');
|
|
25
|
+
const existing = this.streams.get(recordingId);
|
|
26
|
+
if (existing) {
|
|
27
|
+
clearTimeout(existing.detachTimer);
|
|
28
|
+
existing.detachTimer = null;
|
|
29
|
+
existing.emit = emit;
|
|
30
|
+
send(existing, existing.completed
|
|
31
|
+
? { type: 'final', text: existing.finalText }
|
|
32
|
+
: { type: 'started', ackSequence: existing.nextSequence - 1, maxDurationSeconds: 300 });
|
|
33
|
+
return existing;
|
|
34
|
+
}
|
|
35
|
+
const pendingStart = this.pendingStarts.get(recordingId);
|
|
36
|
+
if (pendingStart) {
|
|
37
|
+
await pendingStart;
|
|
38
|
+
return this.start({ recordingId, providerConfigId, emit });
|
|
39
|
+
}
|
|
40
|
+
if (this.streams.size + this.pendingStarts.size >= MAX_STREAMS) throw Object.assign(new Error('The STT server is busy'), { code: 'STT_BUSY' });
|
|
41
|
+
const creating = this.createTranscriber(providerConfigId);
|
|
42
|
+
this.pendingStarts.set(recordingId, creating);
|
|
43
|
+
let transcriber;
|
|
44
|
+
try { transcriber = await creating; }
|
|
45
|
+
finally { this.pendingStarts.delete(recordingId); }
|
|
46
|
+
const state = {
|
|
47
|
+
id: recordingId,
|
|
48
|
+
providerConfigId: providerConfigId || null,
|
|
49
|
+
transcriber,
|
|
50
|
+
emit,
|
|
51
|
+
received: new Map(),
|
|
52
|
+
nextSequence: 0,
|
|
53
|
+
audioBytes: 0,
|
|
54
|
+
segmentChunks: [],
|
|
55
|
+
segmentBytes: 0,
|
|
56
|
+
segmentPeak: 0,
|
|
57
|
+
jobs: [],
|
|
58
|
+
finishing: false,
|
|
59
|
+
finalSequence: null,
|
|
60
|
+
completed: false,
|
|
61
|
+
finalText: '',
|
|
62
|
+
detachTimer: null,
|
|
63
|
+
finalTimer: null,
|
|
64
|
+
};
|
|
65
|
+
this.streams.set(recordingId, state);
|
|
66
|
+
send(state, { type: 'started', ackSequence: -1, maxDurationSeconds: 300 });
|
|
67
|
+
return state;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
append(recordingId, sequence, pcm16) {
|
|
71
|
+
const state = this.streams.get(recordingId);
|
|
72
|
+
if (!state || state.completed) throw new Error('STT recording was not started');
|
|
73
|
+
if (state.finishing) throw new Error('STT recording is already finishing');
|
|
74
|
+
if (!Number.isInteger(sequence) || sequence < 0) throw new Error('Invalid STT audio sequence');
|
|
75
|
+
if (sequence < state.nextSequence) {
|
|
76
|
+
send(state, { type: 'ack', ackSequence: state.nextSequence - 1 });
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
if (state.received.has(sequence)) return;
|
|
80
|
+
if (state.received.size >= MAX_REORDERED_CHUNKS) throw new Error('Too many out-of-order STT chunks');
|
|
81
|
+
if (state.audioBytes + pcm16.byteLength > MAX_RECORDING_BYTES) {
|
|
82
|
+
throw Object.assign(new Error('Recording reached the five minute limit'), { code: 'RECORDING_LIMIT' });
|
|
83
|
+
}
|
|
84
|
+
state.audioBytes += pcm16.byteLength;
|
|
85
|
+
state.received.set(sequence, Buffer.from(pcm16));
|
|
86
|
+
while (state.received.has(state.nextSequence)) {
|
|
87
|
+
const chunk = state.received.get(state.nextSequence);
|
|
88
|
+
state.received.delete(state.nextSequence);
|
|
89
|
+
state.nextSequence += 1;
|
|
90
|
+
state.segmentChunks.push(chunk);
|
|
91
|
+
state.segmentBytes += chunk.byteLength;
|
|
92
|
+
const peak = pcm16Peak(chunk);
|
|
93
|
+
state.segmentPeak = Math.max(state.segmentPeak, peak);
|
|
94
|
+
if (state.segmentBytes >= SEGMENT_MAX_BYTES || (state.segmentBytes >= SEGMENT_MIN_BYTES && peak < SILENCE_PEAK)) {
|
|
95
|
+
this.commitSegment(state);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
send(state, { type: 'ack', ackSequence: state.nextSequence - 1 });
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
commitSegment(state) {
|
|
102
|
+
const chunks = state.segmentChunks;
|
|
103
|
+
const bytes = state.segmentBytes;
|
|
104
|
+
const peak = state.segmentPeak;
|
|
105
|
+
state.segmentChunks = [];
|
|
106
|
+
state.segmentBytes = 0;
|
|
107
|
+
state.segmentPeak = 0;
|
|
108
|
+
if (!bytes || peak < SILENCE_PEAK) return;
|
|
109
|
+
const pcm16 = chunks.length === 1 ? chunks[0] : Buffer.concat(chunks, bytes);
|
|
110
|
+
const previous = state.jobs.at(-1)?.promise ?? Promise.resolve();
|
|
111
|
+
const job = { promise: null };
|
|
112
|
+
job.promise = previous.then(() => {
|
|
113
|
+
if (!this.streams.has(state.id)) return { text: '' };
|
|
114
|
+
return state.transcriber.transcribe(pcm16, PCM_SAMPLE_RATE);
|
|
115
|
+
});
|
|
116
|
+
state.jobs.push(job);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
finish(recordingId, finalSequence) {
|
|
120
|
+
const state = this.streams.get(recordingId);
|
|
121
|
+
if (!state || state.completed) throw new Error('STT recording was not started');
|
|
122
|
+
if (!Number.isInteger(finalSequence) || finalSequence < -1) throw new Error('Invalid final STT sequence');
|
|
123
|
+
if (state.nextSequence - 1 < finalSequence) {
|
|
124
|
+
send(state, { type: 'ack', ackSequence: state.nextSequence - 1 });
|
|
125
|
+
return false;
|
|
126
|
+
}
|
|
127
|
+
if (state.finishing) return true;
|
|
128
|
+
state.finishing = true;
|
|
129
|
+
state.finalSequence = finalSequence;
|
|
130
|
+
this.commitSegment(state);
|
|
131
|
+
send(state, { type: 'transcribing' });
|
|
132
|
+
state.finalTimer = setTimeout(() => this.fail(state, new Error('Transcription timed out'), 'TRANSCRIPTION_TIMEOUT'), FINAL_TIMEOUT_MS);
|
|
133
|
+
state.finalTimer.unref?.();
|
|
134
|
+
void Promise.all(state.jobs.map((job) => job.promise)).then((results) => {
|
|
135
|
+
if (!this.streams.has(state.id)) return;
|
|
136
|
+
const text = results.map((result) => String(result?.text ?? '').trim()).filter(Boolean).join(' ').trim();
|
|
137
|
+
if (!text) {
|
|
138
|
+
this.fail(state, new Error('No speech was detected'), 'EMPTY_AUDIO');
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
clearTimeout(state.finalTimer);
|
|
142
|
+
state.completed = true;
|
|
143
|
+
state.finalText = text;
|
|
144
|
+
state.transcriber.close?.();
|
|
145
|
+
send(state, { type: 'final', text });
|
|
146
|
+
this.scheduleRemoval(state);
|
|
147
|
+
}).catch((error) => this.fail(state, error, error?.code || 'TRANSCRIPTION_FAILED'));
|
|
148
|
+
return true;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
cancel(recordingId) {
|
|
152
|
+
const state = this.streams.get(recordingId);
|
|
153
|
+
if (state) this.remove(state);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
detach(recordingId, emit) {
|
|
157
|
+
const state = this.streams.get(recordingId);
|
|
158
|
+
if (!state || state.emit !== emit) return;
|
|
159
|
+
state.emit = null;
|
|
160
|
+
this.scheduleRemoval(state);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
scheduleRemoval(state) {
|
|
164
|
+
clearTimeout(state.detachTimer);
|
|
165
|
+
state.detachTimer = setTimeout(() => this.remove(state), RECONNECT_GRACE_MS);
|
|
166
|
+
state.detachTimer.unref?.();
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
fail(state, error, code) {
|
|
170
|
+
if (!this.streams.has(state.id)) return;
|
|
171
|
+
send(state, { type: 'error', code, message: error?.message || 'Transcription failed' });
|
|
172
|
+
this.remove(state);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
remove(state) {
|
|
176
|
+
if (this.streams.get(state.id) !== state) return;
|
|
177
|
+
this.streams.delete(state.id);
|
|
178
|
+
clearTimeout(state.detachTimer);
|
|
179
|
+
clearTimeout(state.finalTimer);
|
|
180
|
+
state.received.clear();
|
|
181
|
+
state.segmentChunks.length = 0;
|
|
182
|
+
try { state.transcriber.close?.(); } catch {}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
shutdown() {
|
|
186
|
+
for (const state of this.streams.values()) this.remove(state);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test';
|
|
2
|
+
|
|
3
|
+
import { SttStreamManager } from './stream-manager.js';
|
|
4
|
+
|
|
5
|
+
const speech = (samples = 4000) => {
|
|
6
|
+
const pcm = Buffer.alloc(samples * 2);
|
|
7
|
+
for (let index = 0; index < samples; index += 1) pcm.writeInt16LE(index % 2 ? 5000 : -5000, index * 2);
|
|
8
|
+
return pcm;
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
|
|
12
|
+
|
|
13
|
+
describe('SttStreamManager', () => {
|
|
14
|
+
test('emits one final transcript after finish and never emits partial text', async () => {
|
|
15
|
+
const messages = [];
|
|
16
|
+
const calls = [];
|
|
17
|
+
const manager = new SttStreamManager({
|
|
18
|
+
createTranscriber: async () => ({
|
|
19
|
+
transcribe: async (pcm16, sampleRate) => { calls.push({ pcm16, sampleRate }); return { text: 'hello world' }; },
|
|
20
|
+
close() {},
|
|
21
|
+
}),
|
|
22
|
+
});
|
|
23
|
+
await manager.start({ recordingId: 'recording-123456789', providerConfigId: 'local', emit: (message) => messages.push(message) });
|
|
24
|
+
manager.append('recording-123456789', 0, speech());
|
|
25
|
+
manager.finish('recording-123456789', 0);
|
|
26
|
+
await settle();
|
|
27
|
+
expect(calls).toHaveLength(1);
|
|
28
|
+
expect(messages.some((message) => message.type === 'partial')).toBe(false);
|
|
29
|
+
expect(messages.at(-1)).toMatchObject({ type: 'final', text: 'hello world' });
|
|
30
|
+
manager.shutdown();
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
test('reattaches to a retained recording and acks replayed chunks without decoding twice', async () => {
|
|
34
|
+
const first = [];
|
|
35
|
+
const second = [];
|
|
36
|
+
let calls = 0;
|
|
37
|
+
const manager = new SttStreamManager({
|
|
38
|
+
createTranscriber: async () => ({ transcribe: async () => { calls += 1; return { text: 'retained' }; }, close() {} }),
|
|
39
|
+
});
|
|
40
|
+
const emitFirst = (message) => first.push(message);
|
|
41
|
+
await manager.start({ recordingId: 'recording-abcdefgh', emit: emitFirst });
|
|
42
|
+
manager.append('recording-abcdefgh', 0, speech());
|
|
43
|
+
manager.detach('recording-abcdefgh', emitFirst);
|
|
44
|
+
await manager.start({ recordingId: 'recording-abcdefgh', emit: (message) => second.push(message) });
|
|
45
|
+
manager.append('recording-abcdefgh', 0, speech());
|
|
46
|
+
manager.finish('recording-abcdefgh', 0);
|
|
47
|
+
await settle();
|
|
48
|
+
expect(second[0]).toMatchObject({ type: 'started', ackSequence: 0 });
|
|
49
|
+
expect(calls).toBe(1);
|
|
50
|
+
manager.shutdown();
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
test('rejects silent recordings without calling a provider', async () => {
|
|
54
|
+
const messages = [];
|
|
55
|
+
let calls = 0;
|
|
56
|
+
const manager = new SttStreamManager({ createTranscriber: async () => ({ transcribe: async () => { calls += 1; return { text: '' }; }, close() {} }) });
|
|
57
|
+
await manager.start({ recordingId: 'recording-silence12', emit: (message) => messages.push(message) });
|
|
58
|
+
manager.append('recording-silence12', 0, Buffer.alloc(8000));
|
|
59
|
+
manager.finish('recording-silence12', 0);
|
|
60
|
+
await settle();
|
|
61
|
+
expect(calls).toBe(0);
|
|
62
|
+
expect(messages.at(-1)).toMatchObject({ type: 'error', code: 'EMPTY_AUDIO' });
|
|
63
|
+
});
|
|
64
|
+
});
|
|
@@ -7,7 +7,7 @@ Trusted-device access has one durable credential model: a remote client bearer t
|
|
|
7
7
|
|
|
8
8
|
Pairing v2 is implemented by `packages/web/server/lib/client-auth/pairing.js`. It stores short-lived one-time pairing sessions with hashed secrets, exposes create/cancel/redeem routes under `/api/client-auth/pairing/*`, and redeems a valid pairing secret into the same remote client token used by password/passkey trusted-device flows.
|
|
9
9
|
|
|
10
|
-
Browser WebSocket clients mint a 60-second `oc_url_token` through the authenticated `/auth/url-token` route because the WebSocket constructor cannot attach an Authorization header. The token is accepted only for the explicit WebSocket allowlist, currently `/api/terminal/ws`; ordinary API routes and unknown upgrade paths reject it. The token resolves to the UI session or remote-client identity that minted it.
|
|
10
|
+
Browser WebSocket clients mint a 60-second `oc_url_token` through the authenticated `/auth/url-token` route because the WebSocket constructor cannot attach an Authorization header. The token is accepted only for the explicit WebSocket allowlist, currently `/api/terminal/ws` and `/api/stt/ws`; ordinary API routes and unknown upgrade paths reject it. The token resolves to the UI session or remote-client identity that minted it.
|
|
11
11
|
|
|
12
12
|
## Entrypoints and structure
|
|
13
13
|
- `packages/web/server/lib/ui-auth/ui-auth.js`: UI auth controller runtime, cookie/session issuance, rate limiting, and auth route handlers.
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import crypto from 'crypto';
|
|
2
|
+
import { promisify } from 'util';
|
|
2
3
|
import { SignJWT, jwtVerify } from 'jose';
|
|
3
4
|
import fs from 'fs';
|
|
4
5
|
import path from 'path';
|
|
@@ -295,6 +296,7 @@ const isUrlAuthReadableHttpPath = (pathname) => pathname === '/api/pi/events';
|
|
|
295
296
|
|
|
296
297
|
const URL_AUTH_WEBSOCKET_PATHS = new Set([
|
|
297
298
|
'/api/terminal/ws',
|
|
299
|
+
'/api/stt/ws',
|
|
298
300
|
]);
|
|
299
301
|
|
|
300
302
|
const isUrlAuthWebSocketPath = (pathname) => URL_AUTH_WEBSOCKET_PATHS.has(pathname);
|
|
@@ -653,7 +655,10 @@ export const createUiAuth = ({
|
|
|
653
655
|
res.setHeader('Set-Cookie', header);
|
|
654
656
|
};
|
|
655
657
|
|
|
656
|
-
|
|
658
|
+
// Async scrypt keeps the N=16384 key derivation off the event loop; a login
|
|
659
|
+
// attempt must not stall SSE frames and API traffic for its full duration.
|
|
660
|
+
const scryptAsync = promisify(crypto.scrypt);
|
|
661
|
+
const verifyPassword = async (candidate) => {
|
|
657
662
|
if (!candidate) {
|
|
658
663
|
return false;
|
|
659
664
|
}
|
|
@@ -662,7 +667,7 @@ export const createUiAuth = ({
|
|
|
662
667
|
return false;
|
|
663
668
|
}
|
|
664
669
|
try {
|
|
665
|
-
const candidateHash =
|
|
670
|
+
const candidateHash = await scryptAsync(normalizedCandidate, salt, 64);
|
|
666
671
|
return crypto.timingSafeEqual(candidateHash, expectedHash);
|
|
667
672
|
} catch {
|
|
668
673
|
return false;
|
|
@@ -808,7 +813,7 @@ export const createUiAuth = ({
|
|
|
808
813
|
}
|
|
809
814
|
|
|
810
815
|
const candidate = typeof req.body?.password === 'string' ? req.body.password : '';
|
|
811
|
-
if (!verifyPassword(candidate)) {
|
|
816
|
+
if (!(await verifyPassword(candidate))) {
|
|
812
817
|
await recordFailedAttempt(req);
|
|
813
818
|
clearSessionCookie(req, res);
|
|
814
819
|
res.status(401).json({ error: 'Invalid credentials' });
|
|
@@ -191,6 +191,14 @@ describe('ui auth client credential seam', () => {
|
|
|
191
191
|
const terminalWsRes = createResponse();
|
|
192
192
|
expect(await auth.ensureSessionToken(terminalWsReq, terminalWsRes)).toBe('client:device-1');
|
|
193
193
|
|
|
194
|
+
const sttWsReq = {
|
|
195
|
+
method: 'GET',
|
|
196
|
+
path: '/api/stt/ws',
|
|
197
|
+
url: `/api/stt/ws?oc_url_token=${encodeURIComponent(urlToken)}`,
|
|
198
|
+
headers: { connection: 'Upgrade', upgrade: 'websocket' },
|
|
199
|
+
};
|
|
200
|
+
expect(await auth.ensureSessionToken(sttWsReq, createResponse())).toBe('client:device-1');
|
|
201
|
+
|
|
194
202
|
const arbitraryWsReq = {
|
|
195
203
|
method: 'GET',
|
|
196
204
|
path: '/api/not-allowed/ws',
|
|
@@ -10,6 +10,7 @@ import { createPreviewProxyRuntime } from '../preview/proxy-runtime.js';
|
|
|
10
10
|
import { createRequestSecurityRuntime } from '../security/request-security.js';
|
|
11
11
|
import { mergePathValues } from '../server/path-utils.js';
|
|
12
12
|
import { createTerminalRuntime } from '../terminal/runtime.js';
|
|
13
|
+
import { createSttRuntime } from '../stt/runtime.js';
|
|
13
14
|
import { getExecutableSearchDirectories } from '../tunnels/executable-search.js';
|
|
14
15
|
|
|
15
16
|
const normalizeDirectoryPath = (value) => (typeof value === 'string' ? path.resolve(value.trim()) : '');
|
|
@@ -34,7 +35,7 @@ const isExecutable = (filePath) => {
|
|
|
34
35
|
};
|
|
35
36
|
|
|
36
37
|
const resolveProjectDirectory = async (req) => {
|
|
37
|
-
const header = typeof req.get === 'function' ? req.get('x-
|
|
38
|
+
const header = typeof req.get === 'function' ? req.get('x-pichamber-directory') : null;
|
|
38
39
|
const query = Array.isArray(req.query?.directory) ? req.query.directory[0] : req.query?.directory;
|
|
39
40
|
const requested = typeof query === 'string' && query.trim() ? query.trim() : (typeof header === 'string' ? header.trim() : '');
|
|
40
41
|
if (!requested) return { directory: process.cwd(), error: null };
|
|
@@ -48,7 +49,7 @@ const resolveProjectDirectory = async (req) => {
|
|
|
48
49
|
}
|
|
49
50
|
};
|
|
50
51
|
|
|
51
|
-
export const registerWorkspaceIntegrations = ({ app, server, express, uiAuthController }) => {
|
|
52
|
+
export const registerWorkspaceIntegrations = ({ app, server, express, uiAuthController, dataDir }) => {
|
|
52
53
|
const security = createRequestSecurityRuntime({ readSettingsFromDiskMigrated: async () => ({}) });
|
|
53
54
|
registerGitRoutes(app);
|
|
54
55
|
registerFsRoutes(app, {
|
|
@@ -63,7 +64,7 @@ export const registerWorkspaceIntegrations = ({ app, server, express, uiAuthCont
|
|
|
63
64
|
resolveGitBinaryForSpawn: () => searchPathFor(process.platform === 'win32' ? 'git.exe' : 'git'),
|
|
64
65
|
pichamberUserConfigRoot: path.join(os.homedir(), '.config'),
|
|
65
66
|
});
|
|
66
|
-
createTerminalRuntime({
|
|
67
|
+
const terminalRuntime = createTerminalRuntime({
|
|
67
68
|
app,
|
|
68
69
|
server,
|
|
69
70
|
express,
|
|
@@ -76,6 +77,16 @@ export const registerWorkspaceIntegrations = ({ app, server, express, uiAuthCont
|
|
|
76
77
|
isRequestOriginAllowed: security.isRequestOriginAllowed,
|
|
77
78
|
rejectWebSocketUpgrade: security.rejectWebSocketUpgrade,
|
|
78
79
|
});
|
|
80
|
+
const sttRuntime = createSttRuntime({
|
|
81
|
+
app,
|
|
82
|
+
server,
|
|
83
|
+
express,
|
|
84
|
+
uiAuthController,
|
|
85
|
+
isRequestOriginAllowed: security.isRequestOriginAllowed,
|
|
86
|
+
rejectWebSocketUpgrade: security.rejectWebSocketUpgrade,
|
|
87
|
+
modelsDir: path.join(dataDir, 'speech-models'),
|
|
88
|
+
configFile: path.join(dataDir, 'stt', 'config.json'),
|
|
89
|
+
});
|
|
79
90
|
createPreviewProxyRuntime({
|
|
80
91
|
crypto,
|
|
81
92
|
URL,
|
|
@@ -88,4 +99,9 @@ export const registerWorkspaceIntegrations = ({ app, server, express, uiAuthCont
|
|
|
88
99
|
isRequestOriginAllowed: security.isRequestOriginAllowed,
|
|
89
100
|
rejectWebSocketUpgrade: security.rejectWebSocketUpgrade,
|
|
90
101
|
});
|
|
102
|
+
return {
|
|
103
|
+
shutdown: async () => {
|
|
104
|
+
await Promise.allSettled([terminalRuntime.shutdown(), sttRuntime.shutdown()]);
|
|
105
|
+
},
|
|
106
|
+
};
|
|
91
107
|
};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{R as C,j as e}from"./vendor-react-DYyjh7Q0.js";import{f as z,T as y,q as _,B as c,I as a,s as v,aQ as I}from"./SessionSwitcherDropdown-o1RjhCfF.js";import{u as H}from"./index-BAqpUCjs.js";const N=38,h=200,k=({value:t,onChange:o,placeholder:m,disabled:i=!1,hasTouchInput:r=!1,isMobile:u=!1})=>{const n=C.useRef(null),j=H(s=>s.inputSpellcheckEnabled);return C.useLayoutEffect(()=>{const s=n.current;if(!s)return;const l=document.activeElement===s,d=()=>{s.style.height=`${N}px`;const p=s.scrollHeight,x=Math.min(Math.max(p,N),h);s.style.height=`${x}px`,s.style.overflowY=p>h?"auto":"hidden",p>h&&!l&&(s.scrollTop=s.scrollHeight)};d();const f=window.requestAnimationFrame(d);return()=>{window.cancelAnimationFrame(f)}},[t]),e.jsx("textarea",{ref:n,value:t,onChange:s=>o(s.target.value),placeholder:m??"Commit message",rows:1,disabled:i,autoCorrect:r?"on":"off",autoCapitalize:r?"sentences":"off",spellCheck:u||j,className:z("w-full rounded-lg border border-border/60 bg-surface-elevated px-3 py-2 typography-ui-label text-foreground placeholder:text-muted-foreground","resize-none outline-none transition-[border-color,box-shadow] duration-150","focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)]",i&&"opacity-50"),style:{minHeight:N,maxHeight:h}})},F=({highlights:t,onInsert:o})=>{if(t.length===0)return null;const m=()=>{o(t)};return e.jsxs("div",{className:"space-y-2 rounded-xl border border-border/60 bg-transparent px-3 py-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Highlights"}),e.jsxs(y,{children:[e.jsx(_,{asChild:!0,children:e.jsx(c,{variant:"ghost",size:"icon",className:"size-6",onClick:m,"aria-label":"Insert aria label",children:e.jsx(a,{name:"arrow-down",className:"size-4"})})}),e.jsx(v,{sideOffset:8,children:"Insert tooltip"})]})]}),e.jsx("ul",{className:"space-y-1",children:t.map((i,r)=>e.jsx("li",{className:"typography-meta text-foreground",children:i},`${i}-${r}`))})]})},q=({stagedCount:t,commitMessage:o,onCommitMessageChange:m,generatedHighlights:i,onInsertHighlights:r,onGenerateMessage:u,isGeneratingMessage:n,onCommit:j,onCommitAndPush:s,commitAction:l,hasPendingIndexMutation:d=!1,gitmojiEnabled:f,onOpenGitmojiPicker:p})=>{const x=t>0,b=o.trim()&&x&&l===null&&!d,{isMobile:g,hasTouchInput:w}=I();return e.jsxs("section",{className:"border-0 bg-transparent rounded-none",children:[e.jsxs("div",{className:"flex w-full items-baseline gap-2 px-0 pt-2 pb-1",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Commit"}),x?null:e.jsx("span",{className:"min-w-0 truncate typography-meta text-muted-foreground",children:"Stage files to enable commit."})]}),e.jsxs("div",{className:"flex flex-col gap-3 px-0 pt-1 pb-3",children:[e.jsx(F,{highlights:i,onInsert:r}),e.jsx(k,{value:o,onChange:m,placeholder:"Commit message",disabled:l!==null,hasTouchInput:w,isMobile:g}),f&&e.jsxs(c,{variant:"outline",size:"sm",onClick:p,className:"w-fit",type:"button",children:[e.jsx(a,{name:"emotion-happy",className:"size-4"}),"Add gitmoji"]}),e.jsxs("div",{className:"@container/commit-actions flex items-center gap-2 min-w-0",children:[e.jsxs(c,{variant:"outline",size:"sm",onClick:u,disabled:n||l!==null||d||t===0,type:"button","aria-label":"Generate commit message",className:"commit-actions__btn",children:[n?e.jsx(a,{name:"loader-4",className:"size-4 animate-spin"}):e.jsx(a,{name:"ai-generate-2",className:"size-4 text-primary"}),e.jsx("span",{className:"commit-actions__label",children:"Generate"})]}),e.jsx("div",{className:"flex-1"}),e.jsx(c,{size:"sm",variant:"outline",onClick:j,disabled:!b||n,className:"commit-actions__btn whitespace-nowrap","aria-label":"Commit aria label",children:l==="commit"?e.jsxs(e.Fragment,{children:[e.jsx(a,{name:"loader-4",className:"size-4 animate-spin"}),e.jsx("span",{className:"commit-actions__label",children:"Committing..."})]}):e.jsxs(e.Fragment,{children:[e.jsx(a,{name:"git-commit",className:"size-4"}),e.jsx("span",{className:"commit-actions__label",children:"Commit"})]})}),g?e.jsxs(y,{children:[e.jsx(_,{asChild:!0,children:e.jsx(c,{variant:"default",size:"sm",onClick:()=>s(),disabled:!b||n,className:"h-7 w-7 p-0","aria-label":"Commit and sync",children:l==="commitAndPush"?e.jsx(a,{name:"loader-4",className:"size-4 animate-spin"}):e.jsx(a,{name:"arrow-up",className:"size-3.5"})})}),e.jsx(v,{side:"top",children:e.jsx("p",{children:"Commit & sync"})})]}):e.jsx(c,{size:"sm",variant:"default",onClick:()=>s(),disabled:!b||n,className:"commit-actions__btn","aria-label":"Commit and sync",children:l==="commitAndPush"?e.jsxs(e.Fragment,{children:[e.jsx(a,{name:"loader-4",className:"size-4 animate-spin"}),e.jsx("span",{className:"commit-actions__label commit-actions__label--push",children:"Syncing..."})]}):e.jsxs(e.Fragment,{children:[e.jsx(a,{name:"arrow-up",className:"size-3.5"}),e.jsx("span",{className:"commit-actions__label commit-actions__label--push",children:"Commit & sync"})]})})]})]})]})};export{q as C};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{R as e,j as h}from"./vendor-react-DYyjh7Q0.js";import{D as E}from"./vendor-react-drawio-Boqanm0j.js";import{f as x}from"./SessionSwitcherDropdown-o1RjhCfF.js";const D='<mxfile><diagram id="new" name="Page-1"><mxGraphModel dx="0" dy="0" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="827" pageHeight="1169" math="0" shadow="0"><root><mxCell id="0"/><mxCell id="1" parent="0"/></root></mxGraphModel></diagram></mxfile>';function g(){if(typeof document>"u")return!1;const o=document.documentElement.getAttribute("data-theme");return o==="dark"||!o&&window.matchMedia("(prefers-color-scheme: dark)").matches}const X=e.forwardRef(function({xml:t,readOnly:a,className:R,onChange:c},v){const s=e.useRef(t),i=e.useRef(null),m=e.useRef(!1),[n,k]=e.useState(g),u=e.useRef(t),d=e.useRef(t);d.current!==t&&(d.current=t,u.current=t,s.current=t);const f=e.useRef(n);f.current!==n&&(f.current=n,u.current=s.current);const l=e.useRef(null);e.useEffect(()=>{const r=()=>k(g());r();const p=new MutationObserver(r);return p.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]}),()=>p.disconnect()},[]),e.useEffect(()=>{const r=setTimeout(()=>{l.current?.querySelector(".diagrams-iframe")?.focus()},600);return()=>clearTimeout(r)},[]),e.useImperativeHandle(v,()=>({getXml:()=>s.current}));const b=e.useCallback(()=>{!t&&!m.current&&(m.current=!0,setTimeout(()=>{i.current?.template({})},500))},[t]),w=e.useCallback(r=>{s.current=r.xml,c?.(r.xml)},[c]);return h.jsx("div",{ref:l,className:x("h-full w-full",R),children:h.jsx(E,{ref:i,xml:u.current||D,autosave:!0,urlParameters:{ui:a?"simple":n?"dark":"kennedy",spin:!0,libraries:!a,chrome:a,nav:a,layers:a,noSaveBtn:!0,noExitBtn:!0,saveAndExit:!1},onLoad:b,onAutoSave:w},n?"dark":"light")})});export{X as D};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{R as r,j as t}from"./vendor-react-DYyjh7Q0.js";import{u as a}from"./index-BAqpUCjs.js";import{C as v,I as m}from"./SessionSwitcherDropdown-o1RjhCfF.js";import{D as j}from"./DiagramEditor-D1yc4joK.js";import"./vendor-scheduler-7OC5HNn7.js";import"./vendor-zustand-CnsBKjP5.js";import"./vendor-simplewebauthn-browser-VDA66rT_.js";import"./vendor-vite-runtime-DD1OZmLC.js";import"./vendor-base-ui-DL8r2fgQ.js";import"./vendor-floating-ui-utils-BzXdqYpP.js";import"./vendor-floating-ui-react-dom-sVFnuruh.js";import"./vendor-floating-ui-dom-Bkw82kL9.js";import"./vendor-floating-ui-core-CXmKXOXc.js";import"./vendor-use-sync-external-store-B7OScDIw.js";import"./runtimeSurface-CkHYYg0E.js";import"./vendor-dnd-kit-core-GipZW2tY.js";import"./vendor-dnd-kit-utilities-CrOcp0Bp.js";import"./vendor-dnd-kit-accessibility-Cv52zwWT.js";import"./vendor-dnd-kit-sortable-Ct2QxIHb.js";import"./vendor-cmdk-BCEUzcHE.js";import"./vendor-radix-ui-react-dialog-jX3Dld8c.js";import"./vendor-radix-ui-primitive-Dc_FVRD7.js";import"./vendor-radix-ui-react-compose-refs-D1GnwnP9.js";import"./vendor-radix-ui-react-context-CM4yFQ2I.js";import"./vendor-radix-ui-react-id-BcxRjnbX.js";import"./vendor-radix-ui-react-use-layout-effect-0fyGwS2_.js";import"./vendor-radix-ui-react-use-controllable-state-C_ecoh35.js";import"./vendor-radix-ui-react-dismissable-layer-M7LsH3yL.js";import"./vendor-radix-ui-react-primitive-CfpW6_IT.js";import"./vendor-radix-ui-react-slot-BxUc3Pvz.js";import"./vendor-radix-ui-react-use-callback-ref-UKEWHtoP.js";import"./vendor-radix-ui-react-use-escape-keydown-Co13lHGj.js";import"./vendor-radix-ui-react-focus-scope-C2K7lNPv.js";import"./vendor-radix-ui-react-portal-xlJWBfDg.js";import"./vendor-radix-ui-react-presence-Btn-Dp7L.js";import"./vendor-radix-ui-react-focus-guards-D5MZ0nQs.js";import"./vendor-react-remove-scroll-CfeMe0DL.js";import"./vendor-tslib-De9GV7Vy.js";import"./vendor-react-remove-scroll-bar-C9YRs2nU.js";import"./vendor-react-style-singleton-B1H4bWSG.js";import"./vendor-get-nonce-C-Z93AgS.js";import"./vendor-use-sidecar-C-AuTczP.js";import"./vendor-use-callback-ref-CJB0R85I.js";import"./vendor-aria-hidden-DvXkyWUv.js";import"./vendor-codemirror-language-E2vgV9K3.js";import"./vendor-lezer-common-B3-cUCR_.js";import"./vendor-codemirror-state-CNWM3Q8V.js";import"./vendor-marijn-find-cluster-break-DXwl3gUT.js";import"./vendor-codemirror-view-DSzLbZiS.js";import"./vendor-style-mod-NZ5MEPvj.js";import"./vendor-w3c-keyname-Vcq4gwWv.js";import"./vendor-crelt-C8TCjufn.js";import"./vendor-lezer-highlight-CDMHUZ74.js";import"./vendor-codemirror-lang-javascript-BUlYhQ3o.js";import"./vendor-lezer-javascript-D7Tj24ot.js";import"./vendor-lezer-lr-bhwg1HMg.js";import"./vendor-codemirror-autocomplete-BS2SpSAZ.js";import"./vendor-codemirror-lang-json-CqayksDf.js";import"./vendor-lezer-json-Iaex0UN-.js";import"./vendor-codemirror-lang-css-Ba8JZ6fp.js";import"./vendor-lezer-css-C5xB6jxd.js";import"./vendor-codemirror-lang-html-DK27qQri.js";import"./vendor-lezer-html-C0I1p52t.js";import"./vendor-codemirror-lang-markdown-CvO36Y1p.js";import"./vendor-lezer-markdown-C6g-d6P3.js";import"./vendor-codemirror-language-data-Dp_Z-0GD.js";import"./vendor-codemirror-lang-python-_2bIYTiJ.js";import"./vendor-lezer-python-CvuFxeZl.js";import"./vendor-codemirror-commands-RrgJ8H_6.js";import"./vendor-class-variance-authority-5VPnzWs2.js";import"./vendor-clsx-B-dksMZM.js";import"./vendor-tanstack-react-virtual-IrbCBGJ4.js";import"./vendor-tanstack-virtual-core-Dubg10g5.js";import"./vendor-framer-motion-DJASDzNt.js";import"./vendor-motion-dom-DJLgZh4Q.js";import"./vendor-motion-utils-BGh8QBgx.js";import"./vendor-sonner-CW8w438f.js";import"./vendor-tailwind-merge-CPcsbTWB.js";import"./vendor-fuse.js-Dw8P0qyA.js";import"./vendor-react-drawio-Boqanm0j.js";function Kt(){const{files:o}=v(),[e,d]=r.useState(null),[s,p]=r.useState(""),[x,n]=r.useState(!0),l=r.useRef(null),c=a(i=>i.pendingDiagramFile),u=r.useCallback(async i=>{n(!0),d(i);try{const f=await o?.readFile?.(i);f&&p(f.content)}catch{p("")}finally{n(!1)}},[o]);r.useEffect(()=>{if(!c)return;const i=a.getState().consumePendingDiagramFile();i&&u(i)},[u,c]);const g=r.useCallback(async()=>{const i=l.current?.getXml();e&&o?.writeFile&&i&&i!==s&&(await o.writeFile(e,i),p(i))},[e,o,s]),h=e?e.split("/").pop()||e:"";return e?x?t.jsx("div",{className:"flex h-full items-center justify-center p-3",children:t.jsx(m,{name:"loader-4",className:"size-4 animate-spin"})}):t.jsxs("div",{className:"flex h-full flex-col",children:[t.jsxs("div",{className:"flex items-center gap-2 border-b border-border/30 px-3 py-1.5",children:[t.jsx(m,{name:"file",className:"size-4 shrink-0 text-muted-foreground"}),t.jsx("span",{className:"typography-ui text-muted-foreground truncate flex-1",children:h}),t.jsx("button",{type:"button",onClick:()=>{g()},className:"size-6 flex items-center justify-center rounded-md text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",title:"Save diagram",children:t.jsx(m,{name:"save-3",className:"size-4"})}),t.jsx("button",{type:"button",onClick:()=>a.getState().setActiveMainTab("chat"),className:"size-6 flex items-center justify-center rounded-md text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",title:"Close diagram view",children:t.jsx(m,{name:"close",className:"size-4"})})]}),t.jsx("div",{className:"flex-1 min-h-0",children:t.jsx(j,{ref:l,xml:s,className:"h-full"})})]}):t.jsx("div",{className:"flex h-full items-center justify-center p-3",children:t.jsx("div",{className:"typography-ui text-muted-foreground",children:"Pick a file from the tree."})})}export{Kt as DiagramView};
|