@steerable/steer 0.0.0-stage → 0.3.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +35 -2
  3. package/bin/steer.js +2 -0
  4. package/dist/packages/doc-preview/src/assemble.js +183 -0
  5. package/dist/packages/doc-preview/src/edit-failure.js +116 -0
  6. package/dist/packages/doc-preview/src/edit-service.js +879 -0
  7. package/dist/packages/doc-preview/src/edit.js +437 -0
  8. package/dist/packages/doc-preview/src/export.js +540 -0
  9. package/dist/packages/doc-preview/src/index.js +5 -0
  10. package/dist/packages/doc-preview/src/migrations.js +77 -0
  11. package/dist/packages/doc-preview/src/office-converter.js +186 -0
  12. package/dist/packages/doc-preview/src/office-file-preview.js +457 -0
  13. package/dist/packages/doc-preview/src/office-media.js +80 -0
  14. package/dist/packages/doc-preview/src/office-raster.js +146 -0
  15. package/dist/packages/doc-preview/src/office-routes.js +191 -0
  16. package/dist/packages/doc-preview/src/office-runtime.js +251 -0
  17. package/dist/packages/doc-preview/src/preview.js +296 -0
  18. package/dist/packages/doc-preview/src/render.js +351 -0
  19. package/dist/packages/doc-preview/src/routes.js +376 -0
  20. package/dist/packages/doc-preview/src/settings.js +58 -0
  21. package/dist/packages/doc-preview/src/store.js +134 -0
  22. package/dist/packages/doc-preview/src/tasks.js +16 -0
  23. package/dist/packages/doc-preview/src/word-font.js +232 -0
  24. package/dist/packages/doc-preview/src/word-preview.js +292 -0
  25. package/dist/packages/doc-preview/src/word-render.js +283 -0
  26. package/dist/packages/doc-preview/src/word-routes.js +203 -0
  27. package/dist/packages/doc-preview/src/workspace.js +100 -0
  28. package/dist/products/bundled-python.js +110 -0
  29. package/dist/products/load-locale.js +38 -0
  30. package/dist/products/manifest.json +13 -0
  31. package/dist/products/node-gate.js +131 -0
  32. package/dist/products/steer/active.js +93 -0
  33. package/dist/products/steer/browser-detect.js +230 -0
  34. package/dist/products/steer/browser-protocol.js +2 -0
  35. package/dist/products/steer/browser-session.js +811 -0
  36. package/dist/products/steer/browser.js +521 -0
  37. package/dist/products/steer/cli-main.js +13 -0
  38. package/dist/products/steer/cli.js +8 -0
  39. package/dist/products/steer/computer-macos.js +126 -0
  40. package/dist/products/steer/computer-session.js +118 -0
  41. package/dist/products/steer/computer.js +186 -0
  42. package/dist/products/steer/file-preview.js +392 -0
  43. package/dist/products/steer/locales/shell.zh.json +1120 -0
  44. package/dist/products/steer/locales/zh.json +95 -0
  45. package/dist/products/steer/markdown-preview.js +139 -0
  46. package/dist/products/steer/migrate-legacy-data.js +238 -0
  47. package/dist/products/steer/permissions.js +174 -0
  48. package/dist/products/steer/product.json +85 -0
  49. package/dist/products/steer/server.js +8 -0
  50. package/dist/products/steer/skill-read.js +105 -0
  51. package/dist/products/steer/turn-changes.js +187 -0
  52. package/package.json +38 -4
@@ -0,0 +1,376 @@
1
+ /**
2
+ * etown 包的 local-backend 路由(1.2 从 router.ts 提取)。
3
+ *
4
+ * 两批前缀:
5
+ * - `/api/v2/ppt-preview/*`:设计稿预览 / 资源上传 / 单页修改队列 / 历史
6
+ * 回滚 / 导出;
7
+ * - `/api/v2/local-settings/ppt-edit`:单页修改并发上限的设置读写。
8
+ *
9
+ * 路由处理器只编排包内模块与注入的服务句柄;宿主经
10
+ * `local-backend/pack-backend-routes.ts` 注册表在自带路由之后匹配。
11
+ */
12
+ import { getSidecarSupervisor } from '@steerable/agent-shell/llm/index';
13
+ import { backupPptSlide, buildPptSlideEditInstruction, filterValidPptResources, listPptSlideHistory, restorePptSlideHistory, savePptResources, } from './edit.js';
14
+ import { generatePptExport } from './export.js';
15
+ import { invalidatePptPreviewsCache, listPptPreviews, listPptResources, readPptSvg, } from './preview.js';
16
+ import { resolvePptEditConcurrency } from './settings.js';
17
+ function asRecord(body) {
18
+ if (!body || typeof body !== 'object')
19
+ return {};
20
+ return body;
21
+ }
22
+ /** `/api/v2/ppt-preview/*` 一批。 */
23
+ export function createEtownPreviewRoutes(ctx) {
24
+ const { pptEditService } = ctx;
25
+ return [
26
+ {
27
+ method: 'GET',
28
+ path: '/api/v2/ppt-preview',
29
+ handler: async ({ query }) => {
30
+ const chatId = query.get('chatId') ?? '';
31
+ const previews = await listPptPreviews(chatId);
32
+ return { status: 200, data: { previews } };
33
+ },
34
+ },
35
+ {
36
+ method: 'GET',
37
+ path: '/api/v2/ppt-preview/svg',
38
+ handler: async ({ query }) => {
39
+ const chatId = query.get('chatId') ?? '';
40
+ const project = query.get('project') ?? '';
41
+ const slide = query.get('slide') ?? '';
42
+ const svg = await readPptSvg(chatId, project, slide);
43
+ if (svg === null) {
44
+ return { status: 404, data: { detail: 'svg not found' } };
45
+ }
46
+ return { status: 200, data: { svg } };
47
+ },
48
+ },
49
+ // ─── PPT 单页修改:上传图片/数据资源 ─────────────────────────────────
50
+ {
51
+ method: 'POST',
52
+ path: '/api/v2/ppt-preview/upload',
53
+ handler: async ({ body }) => {
54
+ const payload = asRecord(body);
55
+ const chatId = String(payload.chatId ?? '');
56
+ const projectId = String(payload.projectId ?? '');
57
+ const rawFiles = Array.isArray(payload.files) ? payload.files : [];
58
+ const files = rawFiles
59
+ .filter((f) => f &&
60
+ typeof f === 'object' &&
61
+ (typeof f.path === 'string' ||
62
+ typeof f.data === 'string'))
63
+ .map((f) => {
64
+ const item = f;
65
+ return {
66
+ name: typeof item.name === 'string' ? item.name : undefined,
67
+ path: typeof item.path === 'string' ? item.path : undefined,
68
+ data: typeof item.data === 'string' ? item.data : undefined,
69
+ kind: item.kind,
70
+ };
71
+ });
72
+ if (!chatId || !projectId || files.length === 0) {
73
+ return { status: 400, data: { detail: 'chatId / projectId / files are required' } };
74
+ }
75
+ try {
76
+ const result = await savePptResources(chatId, projectId, files);
77
+ return { status: 200, data: result };
78
+ }
79
+ catch (err) {
80
+ return {
81
+ status: 500,
82
+ data: { detail: err instanceof Error ? err.message : String(err) },
83
+ };
84
+ }
85
+ },
86
+ },
87
+ // ─── PPT 单页修改:列出已上传资源 ───────────────────────────────────
88
+ {
89
+ method: 'GET',
90
+ path: '/api/v2/ppt-preview/resources',
91
+ handler: async ({ query }) => {
92
+ const chatId = query.get('chatId') ?? '';
93
+ const project = query.get('project') ?? '';
94
+ const resources = await listPptResources(chatId, project);
95
+ return { status: 200, data: { resources } };
96
+ },
97
+ },
98
+ // ─── PPT 单页修改:入队(不再 steer 主对话回合)──────────────────────
99
+ //
100
+ // 历史坑:这里原先在会话有活跃回合时 `steerChat()` 注入正在跑的回合,而
101
+ // sidecar 的 steer 是把消息追加进**同一个 transcript**的下一个 round——
102
+ // 模型正在改第 3 页,突然看到「目标页 07_xxx.svg」就转向第 7 页,第 3 页
103
+ // 的修改被顶掉(用户看到的是"后提交的任务把前一个撤销了")。
104
+ //
105
+ // 现在每次修改进 `PptEditService` 队列,跑在**独立流**上:不占用父会话
106
+ // 那唯一的回合写者,队列串行(并发可配),同页互斥。sidecar 不可用时
107
+ // 才退回老的 fallback(把指令交回前端经主聊天发送),保留逃生通道。
108
+ {
109
+ method: 'POST',
110
+ path: '/api/v2/ppt-preview/edit',
111
+ handler: async ({ body }) => {
112
+ const payload = asRecord(body);
113
+ const chatId = String(payload.chatId ?? '');
114
+ const projectId = String(payload.projectId ?? '');
115
+ const slideName = String(payload.slideName ?? '');
116
+ const instruction = String(payload.instruction ?? '').trim();
117
+ if (!instruction) {
118
+ return { status: 400, data: { detail: 'instruction is required' } };
119
+ }
120
+ if (instruction.length > 4000) {
121
+ return { status: 400, data: { detail: 'instruction too long (max 4000 chars)' } };
122
+ }
123
+ // 项目和页必须真实存在。
124
+ const previews = await listPptPreviews(chatId, { force: true });
125
+ const project = previews.find((p) => p.projectId === projectId);
126
+ if (!project || !project.slides.some((s) => s.name === slideName)) {
127
+ return { status: 404, data: { detail: 'slide not found' } };
128
+ }
129
+ // 只把仍落在项目内且存在的资源写进指令。
130
+ const resources = await filterValidPptResources(chatId, projectId, payload.resources);
131
+ const chartType = payload.chartType === 'bar' || payload.chartType === 'line' || payload.chartType === 'pie'
132
+ ? payload.chartType
133
+ : 'auto';
134
+ if (pptEditService && getSidecarSupervisor()) {
135
+ const edit = pptEditService.enqueue({
136
+ chatId,
137
+ projectId,
138
+ projectPath: project.projectPath,
139
+ slideName,
140
+ instruction,
141
+ resources,
142
+ chartType,
143
+ });
144
+ return {
145
+ status: 200,
146
+ data: {
147
+ accepted: true,
148
+ mode: 'queued',
149
+ editId: edit.id,
150
+ status: edit.status,
151
+ position: edit.position,
152
+ },
153
+ };
154
+ }
155
+ // sidecar 未运行 / 队列服务未注入:退回主聊天发送路径。
156
+ const fullInstruction = buildPptSlideEditInstruction({
157
+ projectPath: project.projectPath,
158
+ slideName,
159
+ instruction,
160
+ resources,
161
+ chartType,
162
+ });
163
+ // 修改前先备份当前页,便于一键回滚。
164
+ const backup = await backupPptSlide(chatId, projectId, slideName);
165
+ const images = resources
166
+ .filter((r) => r.kind === 'image')
167
+ .map((r) => ({ path: r.path, name: r.name }));
168
+ return {
169
+ status: 200,
170
+ data: {
171
+ accepted: false,
172
+ mode: 'fallback',
173
+ instruction: fullInstruction,
174
+ images,
175
+ backup: backup?.name ?? null,
176
+ },
177
+ };
178
+ },
179
+ },
180
+ // ─── PPT 单页修改:队列快照 ─────────────────────────────────────────
181
+ {
182
+ method: 'GET',
183
+ path: '/api/v2/ppt-preview/edits',
184
+ handler: async ({ query }) => {
185
+ if (!pptEditService) {
186
+ return { status: 503, data: { detail: 'ppt edit service unavailable' } };
187
+ }
188
+ const chatId = query.get('chatId') ?? '';
189
+ const project = query.get('project') ?? '';
190
+ if (!chatId)
191
+ return { status: 400, data: { detail: 'chatId is required' } };
192
+ return {
193
+ status: 200,
194
+ data: {
195
+ edits: pptEditService.list(chatId, project || undefined),
196
+ concurrency: pptEditService.concurrency,
197
+ },
198
+ };
199
+ },
200
+ },
201
+ // ─── PPT 单页修改:取消单条(排队中出队 / 运行中停流)────────────────
202
+ {
203
+ method: 'POST',
204
+ path: '/api/v2/ppt-preview/edits/:id/cancel',
205
+ handler: async ({ params, body }) => {
206
+ if (!pptEditService) {
207
+ return { status: 503, data: { detail: 'ppt edit service unavailable' } };
208
+ }
209
+ const payload = asRecord(body);
210
+ const chatId = String(payload.chatId ?? '');
211
+ if (!chatId)
212
+ return { status: 400, data: { detail: 'chatId is required' } };
213
+ const result = pptEditService.cancel(chatId, params.id);
214
+ if (!result.ok) {
215
+ return { status: 409, data: { detail: result.error ?? 'cancel failed' } };
216
+ }
217
+ return { status: 200, data: { success: true } };
218
+ },
219
+ },
220
+ // ─── PPT 单页修改:重试一条失败 / 已取消的修改 ────────────────────────
221
+ // 服务层克隆成一条新任务(原始那条连错误现场一起留着);这里负责重新
222
+ // 校验目标页还在——项目被删/换页之后重试应该明确报错,而不是排一条必然
223
+ // 失败的队。
224
+ {
225
+ method: 'POST',
226
+ path: '/api/v2/ppt-preview/edits/:id/retry',
227
+ handler: async ({ params, body }) => {
228
+ if (!pptEditService) {
229
+ return { status: 503, data: { detail: 'ppt edit service unavailable' } };
230
+ }
231
+ const payload = asRecord(body);
232
+ const chatId = String(payload.chatId ?? '');
233
+ if (!chatId)
234
+ return { status: 400, data: { detail: 'chatId is required' } };
235
+ const source = pptEditService.get(chatId, params.id);
236
+ if (!source)
237
+ return { status: 404, data: { detail: 'edit not found' } };
238
+ const previews = await listPptPreviews(chatId, { force: true });
239
+ const project = previews.find((p) => p.projectId === source.projectId);
240
+ if (!project || !project.slides.some((s) => s.name === source.slideName)) {
241
+ return {
242
+ status: 404,
243
+ data: { detail: `目标页已不存在(${source.slideName}),无法重试` },
244
+ };
245
+ }
246
+ const result = pptEditService.retry(chatId, source.id, {
247
+ projectPath: project.projectPath,
248
+ });
249
+ if (!result.ok)
250
+ return { status: 409, data: { detail: result.error } };
251
+ return {
252
+ status: 200,
253
+ data: {
254
+ accepted: true,
255
+ editId: result.edit.id,
256
+ status: result.edit.status,
257
+ position: result.edit.position,
258
+ retryOf: source.id,
259
+ },
260
+ };
261
+ },
262
+ },
263
+ // ─── PPT 单页修改:当前页历史备份 / 回滚 ─────────────────────────────
264
+ {
265
+ method: 'GET',
266
+ path: '/api/v2/ppt-preview/slide-history',
267
+ handler: async ({ query }) => {
268
+ const chatId = query.get('chatId') ?? '';
269
+ const project = query.get('project') ?? '';
270
+ const slide = query.get('slide') ?? '';
271
+ const backups = await listPptSlideHistory(chatId, project, slide);
272
+ return { status: 200, data: { backups } };
273
+ },
274
+ },
275
+ {
276
+ method: 'POST',
277
+ path: '/api/v2/ppt-preview/slide-restore',
278
+ handler: async ({ body }) => {
279
+ const payload = asRecord(body);
280
+ const chatId = String(payload.chatId ?? '');
281
+ const projectId = String(payload.projectId ?? '');
282
+ const slideName = String(payload.slideName ?? '');
283
+ const backupName = String(payload.backupName ?? '');
284
+ const ok = await restorePptSlideHistory(chatId, projectId, slideName, backupName);
285
+ if (!ok) {
286
+ return { status: 404, data: { detail: 'backup not found or invalid' } };
287
+ }
288
+ // 内容已变:先清清单缓存再广播,渲染端能立刻拿到新 mtime 并刷新本页。
289
+ invalidatePptPreviewsCache(chatId);
290
+ ctx.broadcast?.('ppt:updated', { chatId });
291
+ return { status: 200, data: { success: true } };
292
+ },
293
+ },
294
+ // ─── PPT 设计稿导出:生成 PPTX / PDF 文件,base64 返回渲染端下载 ─────
295
+ {
296
+ method: 'POST',
297
+ path: '/api/v2/ppt-preview/export',
298
+ handler: async ({ body }) => {
299
+ const payload = asRecord(body);
300
+ const chatId = String(payload.chatId ?? '');
301
+ const projectId = String(payload.projectId ?? '');
302
+ const format = String(payload.format ?? 'both');
303
+ // 队列里还有这个项目的修改没跑完就先拒绝:导出的是"当前 svg_output"
304
+ // 快照,边改边导只会得到一套半新半旧的设计稿(而且 final 质检报告
305
+ // 的指纹会在导出过程中被队列的收尾刷新改掉)。前端也会禁用按钮,
306
+ // 这里是权威守卫。
307
+ const busyEdits = (pptEditService?.list(chatId, projectId) ?? []).filter((edit) => edit.status === 'queued' || edit.status === 'running');
308
+ if (busyEdits.length > 0) {
309
+ return {
310
+ status: 409,
311
+ data: {
312
+ detail: `还有 ${busyEdits.length} 页正在修改,等修改队列跑完再导出`,
313
+ busy: busyEdits.length,
314
+ },
315
+ };
316
+ }
317
+ try {
318
+ const files = await generatePptExport(chatId, projectId, format);
319
+ return { status: 200, data: { files } };
320
+ }
321
+ catch (err) {
322
+ const message = err instanceof Error ? err.message : String(err);
323
+ const status = message.includes('不合法') || message.includes('不支持')
324
+ ? 400
325
+ : message.includes('没有可导出') ||
326
+ message.includes('未找到') ||
327
+ message.includes('读取设计稿失败')
328
+ ? 404
329
+ : 500;
330
+ return { status, data: { detail: message } };
331
+ }
332
+ },
333
+ },
334
+ ];
335
+ }
336
+ /**
337
+ * `/api/v2/local-settings/ppt-edit` 一批(并发上限的设置读写)。
338
+ * GET 顺带返回"当前值是哪来的"(设置 / 启动参数 / 默认),设置界面据此
339
+ * 如实说明;POST 保存后会立刻让队列重新调度——提高并发=马上多点火,
340
+ * 降低并发=只影响后续(在跑的流不杀,见 PptEditService.refreshConcurrency)。
341
+ */
342
+ export function createEtownSettingsRoutes(ctx) {
343
+ return [
344
+ {
345
+ method: 'GET',
346
+ path: '/api/v2/local-settings/ppt-edit',
347
+ handler: async () => {
348
+ const stored = await ctx.store.getPptEditSettings();
349
+ const resolved = resolvePptEditConcurrency(stored, process.env.DEEPPATH_PPT_EDIT_CONCURRENCY ?? null);
350
+ return {
351
+ status: 200,
352
+ data: { concurrency: resolved.concurrency, source: resolved.source, stored },
353
+ };
354
+ },
355
+ },
356
+ {
357
+ method: 'POST',
358
+ path: '/api/v2/local-settings/ppt-edit',
359
+ handler: async ({ body }) => {
360
+ const payload = asRecord(body);
361
+ if (payload.concurrency === undefined || payload.concurrency === null) {
362
+ return { status: 400, data: { detail: 'concurrency is required' } };
363
+ }
364
+ const saved = await ctx.store.setPptEditSettings({
365
+ concurrency: payload.concurrency,
366
+ });
367
+ ctx.onSettingsSaved?.(saved);
368
+ ctx.pptEditService?.refreshConcurrency();
369
+ return {
370
+ status: 200,
371
+ data: { concurrency: saved.concurrency, source: 'setting', stored: saved },
372
+ };
373
+ },
374
+ },
375
+ ];
376
+ }
@@ -0,0 +1,58 @@
1
+ /**
2
+ * PPT 单页修改队列的设置(并发上限)—— 纯逻辑:默认值 / 校验 / 归一。
3
+ *
4
+ * 与 `telemetry-settings.ts` 同样的拆分理由:不依赖 electron / better-sqlite3,
5
+ * 可在纯 Node/vitest 下直接单测。持久化在包存储(./store.ts)的 `settings_kv`
6
+ * 表(key = 'ppt_edit_settings'),由 `PptEditService` 每次调度时读取。
7
+ *
8
+ * 语义:
9
+ * - 并发 = 1(默认)= 严格排队:一次只改一页,后来提交的排队等待,**不会**
10
+ * 顶掉正在跑的那条;
11
+ * - 并发 2~3 = 不同页并行(墙钟时间接近最慢那一页而不是求和),同一页永远
12
+ * 串行(同页写同一个 SVG 文件,并行必然互相覆盖);
13
+ * - 上限硬夹到 3:每次修改都是一条完整的 agent 回合(ppt-master 上下文),
14
+ * 再高只是按倍数烧 token / 内存。
15
+ */
16
+ /** 并发下限。 */
17
+ export const PPT_EDIT_MIN_CONCURRENCY = 1;
18
+ /** 并发硬上限(见模块头注释的取舍)。 */
19
+ export const PPT_EDIT_MAX_CONCURRENCY = 3;
20
+ /** 缺省并发:严格排队。 */
21
+ export const DEFAULT_PPT_EDIT_CONCURRENCY = 1;
22
+ export const DEFAULT_PPT_EDIT_SETTINGS = {
23
+ concurrency: DEFAULT_PPT_EDIT_CONCURRENCY,
24
+ };
25
+ /**
26
+ * 把一个来路不明的值夹成合法并发数。非数字 / NaN / 空串 → 默认值;
27
+ * 越界夹到边界(不抛错——设置项坏掉不该让修改功能整体不可用)。
28
+ */
29
+ export function clampPptEditConcurrency(raw) {
30
+ const parsed = typeof raw === 'number'
31
+ ? raw
32
+ : typeof raw === 'string' && raw.trim()
33
+ ? Number.parseInt(raw.trim(), 10)
34
+ : Number.NaN;
35
+ if (!Number.isFinite(parsed))
36
+ return DEFAULT_PPT_EDIT_CONCURRENCY;
37
+ return Math.min(Math.max(PPT_EDIT_MIN_CONCURRENCY, Math.trunc(parsed)), PPT_EDIT_MAX_CONCURRENCY);
38
+ }
39
+ /** 合并/校验一份(可能残缺的)设置,落到合法 PptEditSettings。 */
40
+ export function mergePptEditSettings(settings) {
41
+ return { concurrency: clampPptEditConcurrency(settings?.concurrency) };
42
+ }
43
+ /**
44
+ * 解析当前生效的并发:**已保存的设置优先**,没有存过才退回启动参数
45
+ * `DEEPPATH_PPT_EDIT_CONCURRENCY`,再没有就是默认 1。
46
+ *
47
+ * 「设置优先」是刻意的:设置界面改了却不生效会让用户以为坏了;启动参数
48
+ * 只在首次(还没存过设置时)作为出厂默认。
49
+ */
50
+ export function resolvePptEditConcurrency(stored, envRaw) {
51
+ if (stored && typeof stored.concurrency === 'number') {
52
+ return { concurrency: clampPptEditConcurrency(stored.concurrency), source: 'setting' };
53
+ }
54
+ if (typeof envRaw === 'string' && envRaw.trim()) {
55
+ return { concurrency: clampPptEditConcurrency(envRaw), source: 'env' };
56
+ }
57
+ return { concurrency: DEFAULT_PPT_EDIT_CONCURRENCY, source: 'default' };
58
+ }
@@ -0,0 +1,134 @@
1
+ /**
2
+ * etown 包的异步、租户限定存储面。
3
+ *
4
+ * `EtownStore` holds only the restricted PackDbAccess supplied by the host.
5
+ * Records and settings include tenant and user ownership. Types live in
6
+ * ./tasks.ts / ./settings.ts
7
+ * (纯模块,不碰 better-sqlite3,供服务层与测试直接引用)。
8
+ */
9
+ import { mergePptEditSettings } from './settings.js';
10
+ export class EtownStore {
11
+ db;
12
+ constructor(db) {
13
+ this.db = db;
14
+ }
15
+ // ─── PPT 单页修改设置(并发上限)────────────────────────────────────
16
+ /** 读取 PPT 单页修改设置;从未配置过时返回 null(调用方按默认 1 处理)。 */
17
+ async getPptEditSettings() {
18
+ const row = await this.db.get(`SELECT value FROM ppt_edit_settings
19
+ WHERE tenant_id = ? AND user_id = ?`, [this.db.scope.tenantId, this.db.scope.userId]);
20
+ if (!row)
21
+ return null;
22
+ try {
23
+ return mergePptEditSettings(JSON.parse(row.value));
24
+ }
25
+ catch {
26
+ return null;
27
+ }
28
+ }
29
+ async setPptEditSettings(settings) {
30
+ const merged = mergePptEditSettings(settings);
31
+ await this.db.run(`INSERT INTO ppt_edit_settings (tenant_id, user_id, value)
32
+ VALUES (?, ?, ?)
33
+ ON CONFLICT(tenant_id, user_id) DO UPDATE SET value = excluded.value`, [this.db.scope.tenantId, this.db.scope.userId, JSON.stringify(merged)]);
34
+ return merged;
35
+ }
36
+ // ─── 单页修改的模型解析 ──────────────────────────────────────────────
37
+ /**
38
+ * 该会话最近一次真实 chat 回合使用的模型。
39
+ *
40
+ * 为什么需要:模型选择器的覆盖是「每轮请求」下发的,主聊天回合落用量事件
41
+ * 时会写入实际模型;但单页修改是独立后台流,不能拿全局设置里的旧模型去跑
42
+ * ——会出现「主任务用 qwen3.6-27b 正常,单页修改却拿 deepseek-flash 报
43
+ * model_not_found」的割裂。这里只读 usage_events 的最近一条 chat 记录,
44
+ * 过滤 title / ppt-edit 等辅助调用,避免被它们覆盖。
45
+ */
46
+ async getLatestChatModel(chatId) {
47
+ // develop: PackDbAccess 是异步 + 租户隔离的(get/all/run/exec),
48
+ // 查询必须带上 tenant/user 作用域。
49
+ const row = await this.db.get(`SELECT model FROM usage_events
50
+ WHERE tenant_id = ? AND user_id = ?
51
+ AND chat_id = ? AND kind = 'chat' AND model IS NOT NULL AND model <> ''
52
+ ORDER BY created_at DESC
53
+ LIMIT 1`, [this.db.scope.tenantId, this.db.scope.userId, chatId]);
54
+ const model = row?.model?.trim();
55
+ return model ? model : null;
56
+ }
57
+ // ─── PPT 单页修改队列(持久化:跨重启不丢队列)──────────────────────
58
+ /**
59
+ * 按 id UPSERT 一条修改任务。UPSERT 不动 rowid,所以一条任务从 queued
60
+ * 变成 running/completed 不会把它挤到队列末尾。
61
+ */
62
+ async savePptEditTask(record) {
63
+ await this.db.run(`INSERT INTO ppt_edit_tasks (
64
+ tenant_id, user_id,
65
+ id, chat_id, project_id, project_path, slide_name, instruction,
66
+ resources_json, chart_type, status, backup, answer, error,
67
+ failure_json, retry_of, trace_id, created_at, started_at, finished_at
68
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
69
+ ON CONFLICT(tenant_id, user_id, id) DO UPDATE SET
70
+ status = excluded.status,
71
+ backup = excluded.backup,
72
+ answer = excluded.answer,
73
+ error = excluded.error,
74
+ failure_json = excluded.failure_json,
75
+ trace_id = excluded.trace_id,
76
+ started_at = excluded.started_at,
77
+ finished_at = excluded.finished_at
78
+ `, [
79
+ this.db.scope.tenantId,
80
+ this.db.scope.userId,
81
+ record.id,
82
+ record.chatId,
83
+ record.projectId,
84
+ record.projectPath,
85
+ record.slideName,
86
+ record.instruction,
87
+ record.resourcesJson,
88
+ record.chartType,
89
+ record.status,
90
+ record.backup,
91
+ record.answer,
92
+ record.error,
93
+ record.failureJson,
94
+ record.retryOf,
95
+ record.traceId,
96
+ record.createdAt,
97
+ record.startedAt,
98
+ record.finishedAt,
99
+ ]);
100
+ }
101
+ /** 按插入顺序(rowid = 提交顺序)返回任务;缺省跨会话。 */
102
+ async listPptEditTasks(chatId) {
103
+ const rows = await (chatId
104
+ ? this.db.all(`SELECT * FROM ppt_edit_tasks
105
+ WHERE tenant_id = ? AND user_id = ? AND chat_id = ?
106
+ ORDER BY rowid ASC`, [this.db.scope.tenantId, this.db.scope.userId, chatId])
107
+ : this.db.all(`SELECT * FROM ppt_edit_tasks
108
+ WHERE tenant_id = ? AND user_id = ? ORDER BY rowid ASC`, [this.db.scope.tenantId, this.db.scope.userId]));
109
+ return rows.map((row) => ({
110
+ id: String(row.id),
111
+ chatId: String(row.chat_id),
112
+ projectId: String(row.project_id),
113
+ projectPath: String(row.project_path),
114
+ slideName: String(row.slide_name),
115
+ instruction: String(row.instruction),
116
+ resourcesJson: String(row.resources_json ?? '[]'),
117
+ chartType: String(row.chart_type ?? 'auto'),
118
+ status: String(row.status),
119
+ backup: row.backup == null ? null : String(row.backup),
120
+ answer: row.answer == null ? null : String(row.answer),
121
+ error: row.error == null ? null : String(row.error),
122
+ failureJson: row.failure_json == null ? null : String(row.failure_json),
123
+ retryOf: row.retry_of == null ? null : String(row.retry_of),
124
+ traceId: row.trace_id == null ? null : String(row.trace_id),
125
+ createdAt: Number(row.created_at),
126
+ startedAt: row.started_at == null ? null : Number(row.started_at),
127
+ finishedAt: row.finished_at == null ? null : Number(row.finished_at),
128
+ }));
129
+ }
130
+ async deletePptEditTask(id) {
131
+ await this.db.run(`DELETE FROM ppt_edit_tasks
132
+ WHERE tenant_id = ? AND user_id = ? AND id = ?`, [this.db.scope.tenantId, this.db.scope.userId, id]);
133
+ }
134
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * PPT 单页修改队列的**持久化形态** —— 行类型 + 服务需要的存储面。
3
+ *
4
+ * 单独一个纯模块(不碰 electron / better-sqlite3)的理由与
5
+ * `ppt-edit-settings.ts` 一样:`PptEditService` 要用这个类型,而它必须能在
6
+ * 纯 Node/vitest 下加载(`storage/index.ts` 会构造 better-sqlite3,普通 worker
7
+ * 加载不了)。生产实现见同包 `./store.ts`(EtownStore);测试与 e2e 用内存假实现。
8
+ *
9
+ * 设计取舍:
10
+ * - 复杂字段(resources / failure)以 **JSON 字符串**落库,服务层负责编解码
11
+ * ——storage 保持"哑"的,不认识 PptResource / PptEditFailure 这些领域类型。
12
+ * - 时间戳存 epoch 毫秒(不是 ISO 串):队列排序/比较都在宿主侧,少一次解析。
13
+ * - 队列 FIFO 顺序靠 **rowid**(插入顺序即提交顺序);UPSERT 更新不会改
14
+ * rowid,所以一条任务状态变化不会把它挤到队尾。因此这里没有 seq 列。
15
+ */
16
+ export {};