dsh-prompttab 5.0.0 → 5.1.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/src/client.js CHANGED
@@ -9,15 +9,108 @@ window.__ModuleLoader__.load({
9
9
  /** Internal Host command carrying one context-aware suggestion. */
10
10
  const SUGGEST_COMMAND = 'prompttab-suggestion'
11
11
  const EXPLAIN_COMMAND = 'prompttab-explain'
12
+ const WORKFLOW_COMMAND = 'prompttab-workflows'
12
13
  const EXPLAIN_TEXT_MAX = 1000
13
14
  const SUGGEST_CACHE_TTL = 5 * 60 * 1000
14
15
  const SUGGEST_CACHE_LIMIT = 20
15
16
  const SUGGEST_DRAFT_MAX = 2000
16
- const PLUGIN_VERSION = '5.0.0'
17
+ const PLUGIN_VERSION = '5.1.0'
17
18
 
18
19
  // #region Locale dictionaries -------------------------------------------------
19
20
 
20
21
  const EN = {
22
+ 'workflow.builtin.research-evidence': 'Research and Evidence Synthesis',
23
+ 'workflow.builtin.content-publishing': 'Content Creation and Publishing',
24
+ 'workflow.stage.research-scope': 'Frame the question',
25
+ 'workflow.stage.research-scopeHint': 'Set the question, scope, and criteria for evidence.',
26
+ 'workflow.stage.research-collect': 'Collect sources',
27
+ 'workflow.stage.research-collectHint': 'Find relevant sources and track where each came from.',
28
+ 'workflow.stage.research-verify': 'Verify sources',
29
+ 'workflow.stage.research-verifyHint': 'Trace key claims to original and independent evidence.',
30
+ 'workflow.stage.research-synthesize': 'Synthesize evidence',
31
+ 'workflow.stage.research-synthesizeHint': 'Compare supporting and conflicting evidence.',
32
+ 'workflow.stage.research-conclude': 'Form conclusions',
33
+ 'workflow.stage.research-concludeHint': 'Answer with citations, limitations, and open questions.',
34
+ 'workflow.stage.content-brief': 'Define audience and goal',
35
+ 'workflow.stage.content-briefHint': 'Clarify who the content serves and what it should do.',
36
+ 'workflow.stage.content-outline': 'Build the outline',
37
+ 'workflow.stage.content-outlineHint': 'Organize the message and mark where evidence is needed.',
38
+ 'workflow.stage.content-draft': 'Write the draft',
39
+ 'workflow.stage.content-draftHint': 'Draft for the audience and mark unresolved facts.',
40
+ 'workflow.stage.content-check': 'Edit and fact-check',
41
+ 'workflow.stage.content-checkHint': 'Improve the draft and trace claims to their sources.',
42
+ 'workflow.stage.content-finalize': 'Review and finalize',
43
+ 'workflow.stage.content-finalizeHint': 'Confirm outstanding checks and prepare the handoff.',
44
+ 'workflow.aiDraft': 'Draft with AI',
45
+ 'workflow.aiIntro': 'Describe the task and optionally provide a method or team guideline.',
46
+ 'workflow.aiTask': 'Task description',
47
+ 'workflow.aiTaskPlaceholder': 'Example: Build a bug-fix workflow for a small team.',
48
+ 'workflow.aiReference': 'Reference method (optional)',
49
+ 'workflow.aiReferencePlaceholder': 'Name a method or paste the relevant guidance.',
50
+ 'workflow.aiGenerate': 'Generate draft',
51
+ 'workflow.aiGenerating': 'Generating workflow draft…',
52
+ 'workflow.aiReview': 'AI suggestion. Edit the draft, try a stage in this conversation, then save when ready.',
53
+ 'workflow.aiReviewWithReference': 'AI draft with a reference supplied. Review how it was used and try a stage before saving.',
54
+ 'workflow.aiInvalid': 'Enter a task and check the reference length.',
55
+ 'workflow.aiOutput': 'The model did not return a usable workflow. Try again or refine the task.',
56
+ 'workflow.aiNoRoute': 'Select a model in this conversation to draft a workflow.',
57
+ 'workflow.aiTimeout': 'Draft generation timed out. Try again.',
58
+ 'workflow.intro': 'Choose how the next Tab suggestion should use this conversation.',
59
+ 'workflow.choose': 'Choose workflow',
60
+ 'workflow.current': 'Current',
61
+ 'workflow.openCurrent': 'Change workflow stage ({stage})',
62
+ 'workflow.clearHint': 'Use the conversation without a workflow stage.',
63
+ 'workflow.keysMove': 'Move',
64
+ 'workflow.keysSelect': 'Select',
65
+ 'workflow.stage.planHint': 'Clarify the need and prepare an intent record for review.',
66
+ 'workflow.stage.designHint': 'Turn reviewed intent into a spec with decisions and risks.',
67
+ 'workflow.stage.buildHint': 'Review the plan, then implement one step with its check.',
68
+ 'workflow.stage.testHint': 'Run repeatable checks and follow up on failures.',
69
+ 'workflow.stage.deployHint': 'Review the change, check CI and confirm release approval.',
70
+ 'workflow.stage.maintainHint': 'Investigate feedback and turn confirmed findings into new intent.',
71
+ 'workflow.title': 'Workflow stage',
72
+ 'workflow.key': 'Alt + Shift + W',
73
+ 'workflow.shortcut': 'Choose a workflow stage for this conversation.',
74
+ 'workflow.builtin': 'Software development',
75
+ 'workflow.stage.plan': 'Requirements',
76
+ 'workflow.stage.design': 'Design',
77
+ 'workflow.stage.build': 'Implementation',
78
+ 'workflow.stage.test': 'Testing',
79
+ 'workflow.stage.deploy': 'Delivery',
80
+ 'workflow.stage.maintain': 'Maintenance',
81
+ 'workflow.close': 'Close',
82
+ 'workflow.clear': 'No stage',
83
+ 'workflow.switch': 'Switch workflow',
84
+ 'workflow.manage': 'Manage workflows',
85
+ 'workflow.new': 'New workflow',
86
+ 'workflow.copy': 'Copy',
87
+ 'workflow.copyName': 'Copy of {name}',
88
+ 'workflow.edit': 'Edit',
89
+ 'workflow.delete': 'Delete workflow',
90
+ 'workflow.confirmDelete': 'Delete {name} and its stages ({stages})?',
91
+ 'workflow.name': 'Workflow name',
92
+ 'workflow.stageName': 'Stage name',
93
+ 'workflow.focus': 'Generation focus',
94
+ 'workflow.optional': 'Optional',
95
+ 'workflow.deliverable': 'Expected deliverable',
96
+ 'workflow.up': 'Move up',
97
+ 'workflow.down': 'Move down',
98
+ 'workflow.removeStage': 'Remove stage',
99
+ 'workflow.add': 'Add stage',
100
+ 'workflow.save': 'Save workflow',
101
+ 'workflow.saved': 'Workflow saved.',
102
+ 'workflow.useSaved': 'Select a stage to use in this conversation.',
103
+ 'workflow.back': 'Back',
104
+ 'workflow.trial': 'Try this stage',
105
+ 'workflow.trialTitle': 'Stage draft preview',
106
+ 'workflow.trialBlocked': 'Return to a ready composer with an empty or plain-text draft to try this stage.',
107
+ 'workflow.reloadHint': 'Saving may reload PromptTab. Reopen the selector to use your saved stage.',
108
+ 'workflow.loading': 'Loading…',
109
+ 'workflow.stale': 'Workflows changed. Reopen the selector to see the latest version.',
110
+ 'workflow.missing': 'The selected stage was removed. Choose another stage.',
111
+ 'workflow.invalid': 'Check required fields, stage names, and text limits.',
112
+ 'workflow.failed': 'Could not complete the workflow operation.',
113
+ 'workflow.readOnly': 'Workflow editing is unavailable in this profile.',
21
114
  'product.name': 'PromptTab',
22
115
  'action.copy': 'Copy',
23
116
  'notice.copied': 'Copied to the clipboard',
@@ -144,9 +237,145 @@ window.__ModuleLoader__.load({
144
237
  'tabActionList.polishDesc': 'Improves the language of the full text while keeping the original meaning.',
145
238
  'tabActionList.polishSelectionName': 'Polish selection',
146
239
  'tabActionList.polishSelectionDesc': 'Polishes only the language of the selected text.',
240
+ 'lab.title': 'Prompt lab',
241
+ 'lab.sections': 'Prompt sections',
242
+ 'lab.close': 'Close the prompt lab',
243
+ 'lab.hint': 'Alt+Shift+P opens this page. Saved sections apply to new Tab suggestions and live in plugin Config; built-in prompts, versions, and hashes stay untouched.',
244
+ 'lab.loading': 'Loading prompts…',
245
+ 'lab.statusBuiltin': 'Built-in',
246
+ 'lab.statusSaved': 'Saved',
247
+ 'lab.sectionLabel': 'Edit {section}',
248
+ 'lab.chars': '{count} / {max} characters',
249
+ 'lab.total': 'Total {total} / {max}',
250
+ 'lab.previewDiff': '{count} section(s) differ from the built-in text',
251
+ 'lab.previewTitle': 'Final system prompt',
252
+ 'lab.trialTitle': 'Trial run',
253
+ 'lab.trialRun': 'Run trial',
254
+ 'lab.trialRunning': 'Running…',
255
+ 'lab.trialText': 'Composer text for the trial',
256
+ 'lab.trialEmpty': 'No output yet. Edit a section, then run a trial.',
257
+ 'lab.trialNote': 'The trial uses the editor content and does not save it.',
258
+ 'lab.trialResult': '{chars} characters · {ms} ms',
259
+ 'lab.save': 'Save and apply',
260
+ 'lab.reset': 'Restore built-in',
261
+ 'lab.export': 'Export',
262
+ 'lab.resetSection': 'Restore this section',
263
+ 'lab.resetAll': 'Restore all',
264
+ 'lab.exported': 'Copied the nine sections to the clipboard.',
265
+ 'lab.savedApplied': 'Saved to plugin Config. The plugin reloads to apply it.',
266
+ 'lab.resetDone': 'Built-in prompts restored.',
267
+ 'lab.stampStale': 'These values were saved against different built-in text; review them.',
268
+ 'lab.stampUnknown': 'No saved baseline for these values; they may be outdated.',
269
+ 'lab.noEditor': 'This profile cannot persist plugin configuration.',
270
+ 'lab.errorUnavailable': 'The prompt lab is unavailable here. Reload the plugin (or restart DSH) and try again.',
271
+ 'lab.errorInvalidPayload': 'The lab request was malformed.',
272
+ 'lab.errorNoEditor': 'Plugin configuration cannot be saved in this profile.',
273
+ 'lab.errorOverridden': 'A higher configuration layer overrides these values, so the write was refused.',
274
+ 'lab.errorWriteFailed': 'The configuration write failed.',
275
+ 'lab.errorInvalidSections': 'The prompt sections are not a valid object.',
276
+ 'lab.errorUnknownSection': 'Unknown section “{section}” was ignored.',
277
+ 'lab.errorMissingSection': 'Section “{section}” is missing.',
278
+ 'lab.errorEmptySection': 'Section “{section}” is empty.',
279
+ 'lab.errorInvalidText': 'Section “{section}” contains control characters.',
280
+ 'lab.errorSectionTooLong': 'Section “{section}” exceeds 6,000 characters.',
281
+ 'lab.errorTotalTooLong': 'The sections exceed 30,000 characters in total.',
282
+ 'lab.errorClipboard': 'Could not copy to the clipboard.',
283
+ 'lab.errorFailed': 'The lab operation failed.',
147
284
  }
148
285
 
149
286
  const ZH = {
287
+ 'workflow.builtin.research-evidence': '资料调研与证据综合',
288
+ 'workflow.builtin.content-publishing': '内容创作与发布',
289
+ 'workflow.stage.research-scope': '界定问题',
290
+ 'workflow.stage.research-scopeHint': '明确问题、范围和证据标准。',
291
+ 'workflow.stage.research-collect': '搜集资料',
292
+ 'workflow.stage.research-collectHint': '搜集相关来源,记录出处和资料缺口。',
293
+ 'workflow.stage.research-verify': '核验来源',
294
+ 'workflow.stage.research-verifyHint': '追溯关键主张的原始出处,检查证据是否独立。',
295
+ 'workflow.stage.research-synthesize': '综合证据',
296
+ 'workflow.stage.research-synthesizeHint': '整理支持、冲突和待核实的证据。',
297
+ 'workflow.stage.research-conclude': '形成结论',
298
+ 'workflow.stage.research-concludeHint': '形成带出处的结论,标明局限和待确认问题。',
299
+ 'workflow.stage.content-brief': '明确受众与目标',
300
+ 'workflow.stage.content-briefHint': '明确受众、内容目标和发布渠道。',
301
+ 'workflow.stage.content-outline': '搭建提纲',
302
+ 'workflow.stage.content-outlineHint': '安排核心信息,标记所需证据和素材。',
303
+ 'workflow.stage.content-draft': '起草',
304
+ 'workflow.stage.content-draftHint': '为目标受众起草,标记待核实的事实。',
305
+ 'workflow.stage.content-check': '编辑与事实核查',
306
+ 'workflow.stage.content-checkHint': '编辑稿件,核对主张、数据和引用的出处。',
307
+ 'workflow.stage.content-finalize': '审阅定稿',
308
+ 'workflow.stage.content-finalizeHint': '确认核验、素材和审批状态,再准备发布交接。',
309
+ 'workflow.aiDraft': '用 AI 起草',
310
+ 'workflow.aiIntro': '描述想完成的任务,也可以提供参考方法或团队规范。',
311
+ 'workflow.aiTask': '任务描述',
312
+ 'workflow.aiTaskPlaceholder': '例如:为小团队生成一套 Bug 修复工作流。',
313
+ 'workflow.aiReference': '参考方法(可选)',
314
+ 'workflow.aiReferencePlaceholder': '填写方法名称,或粘贴相关规范。',
315
+ 'workflow.aiGenerate': '生成草案',
316
+ 'workflow.aiGenerating': '正在生成工作流草案…',
317
+ 'workflow.aiReview': 'AI 建议。你可以修改草案、在当前对话中试用阶段,确认后再保存。',
318
+ 'workflow.aiReviewWithReference': 'AI 草案。请核对参考方法是否用得合适,并试用阶段后再保存。',
319
+ 'workflow.aiInvalid': '请填写任务描述,并检查参考内容的长度。',
320
+ 'workflow.aiOutput': '模型未返回可用的工作流。可以重试,或补充任务描述。',
321
+ 'workflow.aiNoRoute': '请先为当前对话选择模型,再起草工作流。',
322
+ 'workflow.aiTimeout': '生成工作流草案超时,请重试。',
323
+ 'workflow.intro': '选择阶段,下一次 Tab 建议会结合当前对话。',
324
+ 'workflow.choose': '选择工作流',
325
+ 'workflow.current': '当前',
326
+ 'workflow.openCurrent': '切换工作流阶段({stage})',
327
+ 'workflow.clearHint': '使用当前对话生成一般建议。',
328
+ 'workflow.keysMove': '移动',
329
+ 'workflow.keysSelect': '选择',
330
+ 'workflow.stage.planHint': '澄清需求,形成可审阅的意图记录。',
331
+ 'workflow.stage.designHint': '将已确认的意图转成规格,记录决策和风险。',
332
+ 'workflow.stage.buildHint': '先确认实现计划,再推进一个可验证的改动。',
333
+ 'workflow.stage.testHint': '运行可重复的检查,跟进失败并记录结果。',
334
+ 'workflow.stage.deployHint': '审查改动,核对 CI、发布批准和回滚。',
335
+ 'workflow.stage.maintainHint': '诊断反馈,将确认的问题转成新的需求意图。',
336
+ 'workflow.title': '工作流阶段',
337
+ 'workflow.key': 'Alt + Shift + W',
338
+ 'workflow.shortcut': '为当前对话选择工作流阶段。',
339
+ 'workflow.builtin': '软件开发',
340
+ 'workflow.stage.plan': '需求',
341
+ 'workflow.stage.design': '设计',
342
+ 'workflow.stage.build': '实现',
343
+ 'workflow.stage.test': '测试',
344
+ 'workflow.stage.deploy': '交付',
345
+ 'workflow.stage.maintain': '维护',
346
+ 'workflow.close': '关闭',
347
+ 'workflow.clear': '未指定',
348
+ 'workflow.switch': '切换工作流',
349
+ 'workflow.manage': '管理工作流',
350
+ 'workflow.new': '新建工作流',
351
+ 'workflow.copy': '复制',
352
+ 'workflow.copyName': '{name}的副本',
353
+ 'workflow.edit': '编辑',
354
+ 'workflow.delete': '删除工作流',
355
+ 'workflow.confirmDelete': '删除「{name}」及其中阶段({stages})?',
356
+ 'workflow.name': '工作流名称',
357
+ 'workflow.stageName': '阶段名称',
358
+ 'workflow.focus': '生成重点',
359
+ 'workflow.optional': '可选项',
360
+ 'workflow.deliverable': '期望交付物',
361
+ 'workflow.up': '上移',
362
+ 'workflow.down': '下移',
363
+ 'workflow.removeStage': '删除阶段',
364
+ 'workflow.add': '添加阶段',
365
+ 'workflow.save': '保存工作流',
366
+ 'workflow.saved': '已保存工作流。',
367
+ 'workflow.useSaved': '选择一个阶段用于当前对话。',
368
+ 'workflow.back': '返回',
369
+ 'workflow.trial': '试用此阶段',
370
+ 'workflow.trialTitle': '阶段草稿预览',
371
+ 'workflow.trialBlocked': '请在输入框可用且内容为空或为纯文本时试用。',
372
+ 'workflow.reloadHint': '保存可能重载 PromptTab。重新打开选择器即可使用已保存的阶段。',
373
+ 'workflow.loading': '正在加载…',
374
+ 'workflow.stale': '工作流已更新。请重新打开选择器查看最新版本。',
375
+ 'workflow.missing': '所选阶段已删除,请重新选择。',
376
+ 'workflow.invalid': '请检查必填项、阶段名称和字数限制。',
377
+ 'workflow.failed': '工作流操作未完成,请重试。',
378
+ 'workflow.readOnly': '当前配置无法编辑工作流。',
150
379
  'product.name': 'PromptTab',
151
380
  'action.copy': '复制',
152
381
  'notice.copied': '已复制到剪贴板',
@@ -273,6 +502,50 @@ window.__ModuleLoader__.load({
273
502
  'tabActionList.polishDesc': '改善全文语言表达,保持原意。',
274
503
  'tabActionList.polishSelectionName': '选区润色',
275
504
  'tabActionList.polishSelectionDesc': '只润色选中文字的语言表达。',
505
+ 'lab.title': '提示词实验室',
506
+ 'lab.sections': '提示词分节',
507
+ 'lab.close': '关闭提示词实验室',
508
+ 'lab.hint': 'Alt+Shift+P 打开本页。保存的分节作用于新的 Tab 建议,并存放在插件 Config 中;内置提示词、版本号与哈希基线都不变。',
509
+ 'lab.loading': '正在读取提示词…',
510
+ 'lab.statusBuiltin': '内置',
511
+ 'lab.statusSaved': '已保存',
512
+ 'lab.sectionLabel': '编辑 {section}',
513
+ 'lab.chars': '{count} / {max} 字符',
514
+ 'lab.total': '合计 {total} / {max}',
515
+ 'lab.previewDiff': '有 {count} 个分节与内置文本不同',
516
+ 'lab.previewTitle': '最终 system prompt',
517
+ 'lab.trialTitle': '试跑',
518
+ 'lab.trialRun': '试跑',
519
+ 'lab.trialRunning': '正在试跑…',
520
+ 'lab.trialText': '试跑用的输入框文本',
521
+ 'lab.trialEmpty': '还没有输出。先修改分节,再试跑。',
522
+ 'lab.trialNote': '试跑使用编辑区当前内容,不会保存。',
523
+ 'lab.trialResult': '{chars} 字符 · {ms} ms',
524
+ 'lab.save': '保存并应用',
525
+ 'lab.reset': '恢复内置',
526
+ 'lab.export': '导出',
527
+ 'lab.resetSection': '恢复本段',
528
+ 'lab.resetAll': '全部恢复',
529
+ 'lab.exported': '九段提示词已复制到剪贴板。',
530
+ 'lab.savedApplied': '已保存到插件 Config,插件会重载以生效。',
531
+ 'lab.resetDone': '已恢复内置提示词。',
532
+ 'lab.stampStale': '这些内容基于旧版内置文本保存,建议复核。',
533
+ 'lab.stampUnknown': '这些内容没有保存基线,可能已经过期。',
534
+ 'lab.noEditor': '当前 profile 无法持久化插件配置。',
535
+ 'lab.errorUnavailable': '当前无法使用提示词实验室:请重新加载插件(或重启 DSH)后再试。',
536
+ 'lab.errorInvalidPayload': '实验室请求格式不正确。',
537
+ 'lab.errorNoEditor': '当前 profile 无法保存插件配置。',
538
+ 'lab.errorOverridden': '更高优先级的配置覆盖了这些值,写入被拒绝。',
539
+ 'lab.errorWriteFailed': '配置写入失败。',
540
+ 'lab.errorInvalidSections': '提示词分节不是有效的对象。',
541
+ 'lab.errorUnknownSection': '未知分节「{section}」已被忽略。',
542
+ 'lab.errorMissingSection': '缺少分节「{section}」。',
543
+ 'lab.errorEmptySection': '分节「{section}」为空。',
544
+ 'lab.errorInvalidText': '分节「{section}」含有控制字符。',
545
+ 'lab.errorSectionTooLong': '分节「{section}」超过 6,000 字符。',
546
+ 'lab.errorTotalTooLong': '九个分节合计超过 30,000 字符。',
547
+ 'lab.errorClipboard': '无法复制到剪贴板。',
548
+ 'lab.errorFailed': '实验室操作失败。',
276
549
  }
277
550
 
278
551
  function selectionText(value) {
@@ -542,6 +815,9 @@ window.__ModuleLoader__.load({
542
815
  .dsh-pt-tab-actions-panel,
543
816
  .dsh-pt-text-menu,
544
817
  .dsh-pt-explain-dialog,
818
+ .dsh-pt-lab,
819
+ .dsh-pt-workflow-dialog,
820
+ .dsh-pt-workflow-dock,
545
821
  .dsh-pt-toast{
546
822
  --dsh-pt-brand-black:#111113;
547
823
  --dsh-pt-brand-white:#FFFFFF;
@@ -1063,6 +1339,21 @@ window.__ModuleLoader__.load({
1063
1339
  return count
1064
1340
  }
1065
1341
 
1342
+ // Internal command rows are invisible to the Host transcript.
1343
+ function workflowConversationContext(order, nodes, previous) {
1344
+ const relevant = []
1345
+ for (const id of Array.isArray(order) ? order : []) {
1346
+ const node = nodes?.get(id)
1347
+ if (node?.kind === 'user' || node?.kind === 'assistant-step' || node?.kind === 'steering') relevant.push({ id, node })
1348
+ }
1349
+ const same = previous?.length === relevant.length && relevant.every(({ id, node }, index) => {
1350
+ const prior = previous[index]
1351
+ return id === prior.id && node.kind === prior.node.kind
1352
+ && (node.data === prior.node.data || JSON.stringify(node.data) === JSON.stringify(prior.node.data))
1353
+ })
1354
+ return same ? previous : relevant
1355
+ }
1356
+
1066
1357
  function isTabSuggestionPhase(phase) {
1067
1358
  return phase === 'plain' || phase === 'claimed'
1068
1359
  }
@@ -1370,6 +1661,11 @@ window.__ModuleLoader__.load({
1370
1661
  keyKey: 'tabActionList.openKey', whenKey: null,
1371
1662
  nameKey: 'tabActionList.openName', descriptionKey: 'tabActionList.openDesc',
1372
1663
  },
1664
+ {
1665
+ id: 'workflow', group: 'keys',
1666
+ keyKey: 'workflow.key', whenKey: null,
1667
+ nameKey: 'workflow.title', descriptionKey: 'workflow.shortcut',
1668
+ },
1373
1669
  ])
1374
1670
 
1375
1671
  const TAB_ACTION_LIST_SEARCH_FIELDS = Object.freeze(['id', 'action', 'key', 'name', 'when', 'description'])
@@ -1385,6 +1681,16 @@ window.__ModuleLoader__.load({
1385
1681
  return true
1386
1682
  }
1387
1683
 
1684
+ /** True only for Alt+Shift+P, the development prompt-lab shortcut. */
1685
+ function isPromptLabShortcut(event) {
1686
+ if (event === null || event === undefined) return false
1687
+ if (event.altKey !== true || event.shiftKey !== true) return false
1688
+ if (event.ctrlKey === true || event.metaKey === true) return false
1689
+ if (event.isComposing === true || event.keyCode === 229) return false
1690
+ if (event.code === 'KeyP') return true
1691
+ return typeof event.key === 'string' && event.key.toLowerCase() === 'p'
1692
+ }
1693
+
1388
1694
  /** Translate the read-only definitions into localized rows for the panel. */
1389
1695
 
1390
1696
  function tabActionListEntries(t) {
@@ -1715,7 +2021,924 @@ window.__ModuleLoader__.load({
1715
2021
 
1716
2022
  const promptHistoryEmptyOrder = []
1717
2023
 
1718
- function PromptSuggestionOverlay({ t, sessionId, inputActions, useInput, useChat, onSuggest }) {
2024
+ // #region Development prompt lab (TEMPORARY: remove with feature/prompt-lab) ---
2025
+
2026
+ const PROMPT_LAB_COMMAND = 'prompttab-lab'
2027
+ const LAB_SECTION_NAMES = Object.freeze([
2028
+ 'shared', 'suggest', 'optimize', 'enhance', 'continue', 'complete', 'expand', 'polish', 'polish-selection',
2029
+ ])
2030
+ const LAB_ACTION_NAMES = Object.freeze([
2031
+ 'suggest', 'optimize', 'enhance', 'continue', 'complete', 'expand', 'polish', 'polish-selection',
2032
+ ])
2033
+ const LAB_SECTION_MAX = 6000
2034
+ const LAB_TOTAL_MAX = 30000
2035
+ const LAB_TRIAL_DEFAULTS = Object.freeze({
2036
+ suggest: '',
2037
+ optimize: '请分析这份数据并给出结论。',
2038
+ enhance: '分析这份数据',
2039
+ continue: '请先说明背景,',
2040
+ complete: '请先说明背景,然后给出结论。',
2041
+ expand: '分析这份数据',
2042
+ polish: '那个啥 帮我看下 这个数据 分析一下',
2043
+ 'polish-selection': '那个啥 帮我看下',
2044
+ })
2045
+
2046
+ /** Frame-wide prompt-lab state; only one page is open at a time. */
2047
+ let promptLabState = { open: false, sessionId: '' }
2048
+ const promptLabListeners = new Set()
2049
+ let promptLabBridge = { request: null }
2050
+
2051
+ function subscribePromptLab(listener) {
2052
+ promptLabListeners.add(listener)
2053
+ return () => {
2054
+ promptLabListeners.delete(listener)
2055
+ }
2056
+ }
2057
+
2058
+ function getPromptLabSnapshot() {
2059
+ return promptLabState
2060
+ }
2061
+
2062
+ function emitPromptLab() {
2063
+ for (const listener of [...promptLabListeners]) listener()
2064
+ }
2065
+
2066
+ function openPromptLab(sessionId) {
2067
+ if (typeof sessionId !== 'string' || sessionId === '') return false
2068
+ if (promptLabState.open === true && promptLabState.sessionId === sessionId) return true
2069
+ promptLabState = { open: true, sessionId }
2070
+ emitPromptLab()
2071
+ return true
2072
+ }
2073
+
2074
+ function closePromptLab() {
2075
+ if (promptLabState.open !== true) return
2076
+ promptLabState = { open: false, sessionId: '' }
2077
+ emitPromptLab()
2078
+ }
2079
+
2080
+ /** Total characters across the nine sections. */
2081
+ function labTotalChars(sections) {
2082
+ if (sections === null || sections === undefined || typeof sections !== 'object') return 0
2083
+ let total = 0
2084
+ for (const name of LAB_SECTION_NAMES) {
2085
+ const value = sections[name]
2086
+ if (typeof value === 'string') total += value.length
2087
+ }
2088
+ return total
2089
+ }
2090
+
2091
+ /** How many sections differ from the built-in text. */
2092
+ function labChangedSections(sections, builtin) {
2093
+ if (sections === null || sections === undefined || typeof sections !== 'object') return 0
2094
+ if (builtin === null || builtin === undefined || typeof builtin !== 'object') return 0
2095
+ let count = 0
2096
+ for (const name of LAB_SECTION_NAMES) {
2097
+ if (sections[name] !== builtin[name]) count += 1
2098
+ }
2099
+ return count
2100
+ }
2101
+
2102
+ /** Compose the suggestion payload for one trial run. */
2103
+ function labTrialRequest(action, value) {
2104
+ const text = typeof value === 'string' ? value : ''
2105
+ if (action === 'suggest') return { mode: 'suggest', draft: '', extra: {} }
2106
+ if (action === 'complete') {
2107
+ const cut = Math.max(1, Math.floor(text.length / 2))
2108
+ return { mode: 'complete', draft: text, extra: { prefix: text.slice(0, cut), suffix: text.slice(cut) } }
2109
+ }
2110
+ return { mode: action, draft: text, extra: {} }
2111
+ }
2112
+
2113
+ /** One localized reason for a rejected lab operation. */
2114
+ function promptLabErrorMessage(t, result) {
2115
+ const code = result !== null && result !== undefined && typeof result.code === 'string' ? result.code : ''
2116
+ const section = result !== null && result !== undefined && typeof result.section === 'string' ? result.section : ''
2117
+ const suffixes = {
2118
+ unavailable: 'Unavailable',
2119
+ 'invalid-payload': 'InvalidPayload',
2120
+ 'no-editor': 'NoEditor',
2121
+ overridden: 'Overridden',
2122
+ 'write-failed': 'WriteFailed',
2123
+ 'invalid-sections': 'InvalidSections',
2124
+ 'unknown-section': 'UnknownSection',
2125
+ 'missing-section': 'MissingSection',
2126
+ 'empty-section': 'EmptySection',
2127
+ 'invalid-text': 'InvalidText',
2128
+ 'section-too-long': 'SectionTooLong',
2129
+ 'total-too-long': 'TotalTooLong',
2130
+ clipboard: 'Clipboard',
2131
+ }
2132
+ const suffix = suffixes[code] === undefined ? 'Failed' : suffixes[code]
2133
+ return t(`lab.error${suffix}`, { section })
2134
+ }
2135
+
2136
+ /**
2137
+ * Editor for nine prompt sections. Saving updates DSH Config. Trial
2138
+ * suggestions carry their own sections and are shown only on this page.
2139
+ */
2140
+ function PromptLabPage({ t, onSuggest }) {
2141
+ const state = React.useSyncExternalStore(subscribePromptLab, getPromptLabSnapshot)
2142
+ const [builtin, setBuiltin] = React.useState(null)
2143
+ const [saved, setSaved] = React.useState(null)
2144
+ const [effective, setEffective] = React.useState(null)
2145
+ const [stamp, setStamp] = React.useState(null)
2146
+ const [canSave, setCanSave] = React.useState(false)
2147
+ const [draft, setDraft] = React.useState(null)
2148
+ const [section, setSection] = React.useState('shared')
2149
+ const [previewAction, setPreviewAction] = React.useState('suggest')
2150
+ const [notice, setNotice] = React.useState(null)
2151
+ const [busy, setBusy] = React.useState(false)
2152
+ const [trialAction, setTrialAction] = React.useState('suggest')
2153
+ const [trialText, setTrialText] = React.useState(LAB_TRIAL_DEFAULTS.suggest)
2154
+ const [trial, setTrial] = React.useState(null)
2155
+ const rootRef = React.useRef(null)
2156
+ const open = state.open === true
2157
+ const sessionId = state.sessionId
2158
+
2159
+ const send = (op, extra) => {
2160
+ const bridge = promptLabBridge
2161
+ if (typeof bridge.request !== 'function') return Promise.resolve({ ok: false, code: 'unavailable' })
2162
+ return bridge.request(sessionId, op, extra)
2163
+ }
2164
+
2165
+ const absorb = (result) => {
2166
+ if (result === null || result === undefined || result.ok !== true) {
2167
+ setNotice(result === null || result === undefined ? { code: 'failed' } : result)
2168
+ return false
2169
+ }
2170
+ const data = result.data !== null && result.data !== undefined ? result.data : {}
2171
+ if (data.builtin !== undefined) setBuiltin(data.builtin)
2172
+ if (data.saved !== undefined) setSaved(data.saved)
2173
+ if (data.effective !== undefined) setEffective(data.effective)
2174
+ if (data.stamp !== undefined) setStamp(data.stamp)
2175
+ setCanSave(data.editor === true)
2176
+ const nextBuiltin = data.builtin !== undefined ? data.builtin : builtin
2177
+ const nextSaved = data.saved !== undefined ? data.saved : saved
2178
+ if (nextBuiltin !== null && nextBuiltin !== undefined) setDraft({ ...nextBuiltin, ...(nextSaved || {}) })
2179
+ setNotice(null)
2180
+ return true
2181
+ }
2182
+
2183
+ React.useEffect(() => {
2184
+ if (open !== true) return undefined
2185
+ let live = true
2186
+ send('read').then((result) => {
2187
+ if (live !== true) return
2188
+ if (result !== null && result !== undefined && result.ok === true) absorb(result)
2189
+ else setNotice(result)
2190
+ })
2191
+ return () => {
2192
+ live = false
2193
+ }
2194
+ }, [open])
2195
+
2196
+ React.useEffect(() => {
2197
+ if (open !== true) return undefined
2198
+ const previous = typeof document === 'undefined' ? null : document.activeElement
2199
+ const node = rootRef.current
2200
+ if (node !== null && typeof node.focus === 'function') node.focus()
2201
+ const onKey = (event) => {
2202
+ if (event.key !== 'Escape') return
2203
+ event.preventDefault()
2204
+ closePromptLab()
2205
+ }
2206
+ document.addEventListener('keydown', onKey, true)
2207
+ return () => {
2208
+ document.removeEventListener('keydown', onKey, true)
2209
+ if (previous !== null && previous !== undefined && typeof previous.focus === 'function') previous.focus()
2210
+ }
2211
+ }, [open])
2212
+
2213
+ if (open !== true) return null
2214
+
2215
+ const sections = draft
2216
+ const currentValue = sections !== null && typeof sections[section] === 'string' ? sections[section] : ''
2217
+ const builtinValue = builtin !== null && builtin !== undefined && typeof builtin[section] === 'string' ? builtin[section] : ''
2218
+ const total = labTotalChars(sections)
2219
+ const changed = labChangedSections(sections, builtin)
2220
+ const previewText = sections === null
2221
+ ? ''
2222
+ : `${typeof sections.shared === 'string' ? sections.shared : ''}\n\n${typeof sections[previewAction] === 'string' ? sections[previewAction] : ''}`
2223
+ const overSection = currentValue.length > LAB_SECTION_MAX
2224
+ const overTotal = total > LAB_TOTAL_MAX
2225
+ const hasSaved = saved !== null && Object.keys(saved).length > 0
2226
+ const stampStatus = stamp !== null && stamp !== undefined && typeof stamp.status === 'string' ? stamp.status : 'unknown'
2227
+ const staleText = hasSaved !== true
2228
+ ? ''
2229
+ : stampStatus === 'stale'
2230
+ ? t('lab.stampStale')
2231
+ : stampStatus === 'unknown'
2232
+ ? t('lab.stampUnknown')
2233
+ : ''
2234
+ const statusText = hasSaved === true ? t('lab.statusSaved') : t('lab.statusBuiltin')
2235
+
2236
+ const editSection = (value) => {
2237
+ if (sections === null) return
2238
+ setDraft({ ...sections, [section]: value })
2239
+ setNotice(null)
2240
+ }
2241
+
2242
+ const restoreSection = () => {
2243
+ if (sections !== null) setDraft({ ...sections, [section]: builtinValue })
2244
+ }
2245
+
2246
+ const restoreAll = () => {
2247
+ if (builtin !== null && builtin !== undefined) setDraft({ ...builtin })
2248
+ }
2249
+
2250
+ const saveAndApply = () => {
2251
+ if (sections === null || canSave !== true) return
2252
+ setBusy(true)
2253
+ send('apply', { sections }).then((result) => {
2254
+ setBusy(false)
2255
+ if (absorb(result) === true) setNotice({ ok: true, message: t('lab.savedApplied') })
2256
+ })
2257
+ }
2258
+
2259
+ const restoreBuiltIn = () => {
2260
+ if (canSave !== true) return
2261
+ setBusy(true)
2262
+ send('reset').then((result) => {
2263
+ setBusy(false)
2264
+ if (absorb(result) === true) setNotice({ ok: true, message: t('lab.resetDone') })
2265
+ })
2266
+ }
2267
+
2268
+ const exportPrompts = () => {
2269
+ const source = effective !== null && effective !== undefined ? effective : builtin
2270
+ if (source === null || source === undefined) return
2271
+ const markdown = `# PromptTab prompts\n\n${LAB_SECTION_NAMES.map((name) => `## ${name}\n\n${typeof source[name] === 'string' ? source[name] : ''}`).join('\n\n')}\n`
2272
+ const clipboard = typeof navigator !== 'undefined' ? navigator.clipboard : undefined
2273
+ if (clipboard === undefined || typeof clipboard.writeText !== 'function') {
2274
+ setNotice({ code: 'clipboard' })
2275
+ return
2276
+ }
2277
+ clipboard.writeText(markdown)
2278
+ .then(() => setNotice({ ok: true, message: t('lab.exported') }))
2279
+ .catch(() => setNotice({ code: 'clipboard' }))
2280
+ }
2281
+
2282
+ const runTrial = () => {
2283
+ if (sections === null) return
2284
+ if (typeof onSuggest !== 'function') {
2285
+ setNotice({ code: 'unavailable' })
2286
+ return
2287
+ }
2288
+ const request = labTrialRequest(trialAction, trialText)
2289
+ const started = Date.now()
2290
+ setBusy(true)
2291
+ setTrial({ status: 'loading', code: '' })
2292
+ onSuggest(sessionId, request.mode, request.draft, { ...request.extra, trialSections: sections })
2293
+ .then((result) => {
2294
+ const elapsed = Date.now() - started
2295
+ setBusy(false)
2296
+ if (result?.ok !== true) {
2297
+ setTrial({ status: 'error', code: result?.code ?? 'failed', section: result?.detail })
2298
+ return
2299
+ }
2300
+ setTrial({ status: 'ready', text: result.text, ms: elapsed })
2301
+ })
2302
+ .catch((error) => {
2303
+ console.error('prompttab: prompt lab trial failed', error)
2304
+ setBusy(false)
2305
+ setTrial({ status: 'error', code: 'failed' })
2306
+ })
2307
+ }
2308
+
2309
+ const noticeText = notice === null || notice === undefined
2310
+ ? ''
2311
+ : notice.ok === true
2312
+ ? notice.message
2313
+ : promptLabErrorMessage(t, notice)
2314
+ const noticeTone = notice !== null && notice !== undefined && notice.ok !== true ? 'error' : 'info'
2315
+ const trialTextLine = trial === null || trial === undefined
2316
+ ? t('lab.trialEmpty')
2317
+ : trial.status === 'loading'
2318
+ ? t('lab.trialRunning')
2319
+ : trial.status === 'error'
2320
+ ? promptLabErrorMessage(t, trial)
2321
+ : trial.text
2322
+
2323
+ return h(
2324
+ 'div',
2325
+ {
2326
+ ref: rootRef,
2327
+ tabIndex: -1,
2328
+ className: 'dsh-pt-lab',
2329
+ role: 'dialog',
2330
+ 'aria-modal': 'false',
2331
+ 'aria-label': t('lab.title'),
2332
+ onKeyDown: (event) => {
2333
+ if (event !== null && event !== undefined && event.key === 'Escape') {
2334
+ event.preventDefault()
2335
+ closePromptLab()
2336
+ }
2337
+ },
2338
+ },
2339
+ h('style', { key: 'style' }, PROMPT_LAB_CSS),
2340
+ h(
2341
+ 'div',
2342
+ { className: 'dsh-pt-lab-panel' },
2343
+ h(
2344
+ 'div',
2345
+ { className: 'dsh-pt-lab-head' },
2346
+ h('h2', { className: 'dsh-pt-lab-title' }, t('lab.title')),
2347
+ h('span', { className: 'dsh-pt-lab-status', 'data-applied': hasSaved === true ? 'true' : undefined }, statusText),
2348
+ h(
2349
+ 'button',
2350
+ {
2351
+ type: 'button',
2352
+ className: 'dsh-pt-lab-close',
2353
+ 'aria-label': t('lab.close'),
2354
+ title: t('lab.close'),
2355
+ onClick: () => closePromptLab(),
2356
+ },
2357
+ '×',
2358
+ ),
2359
+ ),
2360
+ h('p', { className: 'dsh-pt-lab-hint' }, t('lab.hint')),
2361
+ canSave === false && sections !== null
2362
+ ? h('p', { className: 'dsh-pt-lab-banner', role: 'status' }, t('lab.noEditor'))
2363
+ : null,
2364
+ staleText === '' ? null : h('p', { className: 'dsh-pt-lab-banner', role: 'status' }, staleText),
2365
+ h(
2366
+ 'div',
2367
+ { className: 'dsh-pt-lab-body' },
2368
+ h(
2369
+ 'div',
2370
+ { className: 'dsh-pt-lab-sections', role: 'tablist', 'aria-label': t('lab.sections') },
2371
+ LAB_SECTION_NAMES.map((name) => h(
2372
+ 'button',
2373
+ {
2374
+ key: name,
2375
+ type: 'button',
2376
+ role: 'tab',
2377
+ 'aria-selected': name === section ? 'true' : 'false',
2378
+ 'data-changed': sections !== null && builtin !== null && builtin !== undefined && sections[name] !== builtin[name] ? 'true' : undefined,
2379
+ className: 'dsh-pt-lab-section',
2380
+ onClick: () => setSection(name),
2381
+ },
2382
+ h('span', { className: 'dsh-pt-lab-section-name' }, name),
2383
+ h('span', { className: 'dsh-pt-lab-section-meta' }, `${sections !== null && typeof sections[name] === 'string' ? sections[name].length : 0}`),
2384
+ )),
2385
+ ),
2386
+ h(
2387
+ 'div',
2388
+ { className: 'dsh-pt-lab-editor' },
2389
+ sections === null
2390
+ ? h('p', { className: 'dsh-pt-lab-loading', role: 'status' }, t('lab.loading'))
2391
+ : null,
2392
+ h('textarea', {
2393
+ className: 'dsh-pt-lab-textarea',
2394
+ value: currentValue,
2395
+ spellCheck: false,
2396
+ disabled: sections === null ? true : undefined,
2397
+ onChange: (event) => editSection(event.target.value),
2398
+ 'aria-label': t('lab.sectionLabel', { section }),
2399
+ }),
2400
+ h(
2401
+ 'div',
2402
+ { className: 'dsh-pt-lab-meta' },
2403
+ h('span', { className: overSection === true ? 'dsh-pt-lab-over' : '' }, t('lab.chars', { count: currentValue.length, max: LAB_SECTION_MAX })),
2404
+ h('span', { className: overTotal === true ? 'dsh-pt-lab-over' : '' }, t('lab.total', { total, max: LAB_TOTAL_MAX })),
2405
+ h('span', null, t('lab.previewDiff', { count: changed })),
2406
+ ),
2407
+ ),
2408
+ ),
2409
+ h(
2410
+ 'div',
2411
+ { className: 'dsh-pt-lab-preview' },
2412
+ h(
2413
+ 'div',
2414
+ { className: 'dsh-pt-lab-preview-head' },
2415
+ h('span', { className: 'dsh-pt-lab-preview-title' }, t('lab.previewTitle')),
2416
+ h(
2417
+ 'select',
2418
+ {
2419
+ className: 'dsh-pt-lab-select',
2420
+ value: previewAction,
2421
+ 'aria-label': t('lab.previewTitle'),
2422
+ onChange: (event) => setPreviewAction(event.target.value),
2423
+ },
2424
+ LAB_ACTION_NAMES.map((name) => h('option', { key: name, value: name }, name)),
2425
+ ),
2426
+ ),
2427
+ h('pre', { className: 'dsh-pt-lab-pre' }, previewText),
2428
+ ),
2429
+ h(
2430
+ 'div',
2431
+ { className: 'dsh-pt-lab-trial' },
2432
+ h(
2433
+ 'div',
2434
+ { className: 'dsh-pt-lab-trial-head' },
2435
+ h('span', { className: 'dsh-pt-lab-preview-title' }, t('lab.trialTitle')),
2436
+ h(
2437
+ 'select',
2438
+ {
2439
+ className: 'dsh-pt-lab-select',
2440
+ value: trialAction,
2441
+ 'aria-label': t('lab.trialTitle'),
2442
+ onChange: (event) => {
2443
+ const next = event.target.value
2444
+ setTrialAction(next)
2445
+ setTrialText(LAB_TRIAL_DEFAULTS[next] || '')
2446
+ setTrial(null)
2447
+ },
2448
+ },
2449
+ LAB_ACTION_NAMES.map((name) => h('option', { key: name, value: name }, name)),
2450
+ ),
2451
+ h('button', { type: 'button', className: 'dsh-pt-lab-btn', disabled: busy === true || sections === null ? true : undefined, onClick: runTrial }, busy === true ? t('lab.trialRunning') : t('lab.trialRun')),
2452
+ ),
2453
+ h('p', { className: 'dsh-pt-lab-trial-note' }, t('lab.trialNote')),
2454
+ h('textarea', {
2455
+ className: 'dsh-pt-lab-trial-input',
2456
+ value: trialText,
2457
+ spellCheck: false,
2458
+ 'aria-label': t('lab.trialText'),
2459
+ onChange: (event) => setTrialText(event.target.value),
2460
+ }),
2461
+ h('pre', { className: 'dsh-pt-lab-trial-out', role: 'status' }, trialTextLine),
2462
+ trial !== null && trial !== undefined && trial.status === 'ready'
2463
+ ? h('p', { className: 'dsh-pt-lab-trial-meta' }, t('lab.trialResult', { chars: trial.text.length, ms: trial.ms }))
2464
+ : null,
2465
+ ),
2466
+ noticeText === ''
2467
+ ? null
2468
+ : h('p', { className: 'dsh-pt-lab-notice', 'data-tone': noticeTone, role: 'status' }, noticeText),
2469
+ h(
2470
+ 'div',
2471
+ { className: 'dsh-pt-lab-foot' },
2472
+ h('button', { type: 'button', className: 'dsh-pt-lab-btn', disabled: busy === true || canSave !== true || sections === null ? true : undefined, onClick: saveAndApply }, t('lab.save')),
2473
+ h('button', { type: 'button', className: 'dsh-pt-lab-btn', disabled: busy === true || canSave !== true || hasSaved !== true ? true : undefined, onClick: restoreBuiltIn }, t('lab.reset')),
2474
+ h('button', { type: 'button', className: 'dsh-pt-lab-btn', disabled: busy === true || effective === null ? true : undefined, onClick: exportPrompts }, t('lab.export')),
2475
+ h('button', { type: 'button', className: 'dsh-pt-lab-btn', disabled: sections === null, onClick: restoreSection }, t('lab.resetSection')),
2476
+ h('button', { type: 'button', className: 'dsh-pt-lab-btn', disabled: builtin === null, onClick: restoreAll }, t('lab.resetAll')),
2477
+ h('button', { type: 'button', className: 'dsh-pt-lab-btn dsh-pt-lab-btn-primary', onClick: () => closePromptLab() }, t('lab.close')),
2478
+ ),
2479
+ ),
2480
+ )
2481
+ }
2482
+
2483
+ const PROMPT_LAB_CSS = `${DESIGN_TOKENS_CSS}
2484
+ .dsh-pt-lab{position:fixed;inset:0;z-index:var(--dsh-pt-z-modal,60);display:flex;align-items:center;justify-content:center;padding:24px;box-sizing:border-box;background:var(--dsh-pt-surface-base)}
2485
+ .dsh-pt-lab-panel{display:flex;flex-direction:column;gap:8px;box-sizing:border-box;width:min(1080px,100%);max-height:calc(100vh - 48px);padding:12px;border:1px solid var(--dsh-pt-border-subtle);border-radius:var(--dsh-pt-radius-lg);background:var(--dsh-pt-surface-overlay);box-shadow:var(--dsh-pt-shadow-overlay);color:var(--dsh-pt-text-primary);font-family:var(--dsh-pt-font-sans);font-size:var(--dsh-pt-font-size-body);line-height:1.5;overflow:auto}
2486
+ .dsh-pt-lab-head{display:flex;align-items:center;gap:8px}
2487
+ .dsh-pt-lab-title{margin:0;font-size:var(--dsh-pt-font-size-title);font-weight:600}
2488
+ .dsh-pt-lab-status{margin-left:auto;padding:0 8px;border:1px solid var(--dsh-pt-border-subtle);border-radius:var(--dsh-pt-radius-pill);color:var(--dsh-pt-text-muted);font-size:var(--dsh-pt-font-size-caption);line-height:20px}
2489
+ .dsh-pt-lab-status[data-applied="true"]{color:var(--dsh-pt-text-primary);border-color:var(--dsh-pt-border-strong)}
2490
+ .dsh-pt-lab-close{flex:none;width:24px;height:24px;border:0;border-radius:var(--dsh-pt-radius-sm);background:var(--dsh-pt-surface-overlay);color:var(--dsh-pt-text-secondary);font:inherit;font-size:var(--dsh-pt-font-size-heading);line-height:1;cursor:pointer}
2491
+ .dsh-pt-lab-close:hover{background:var(--dsh-pt-surface-sunken);color:var(--dsh-pt-text-primary)}
2492
+ .dsh-pt-lab-hint{margin:0;color:var(--dsh-pt-text-muted);font-size:var(--dsh-pt-font-size-caption);line-height:16px}
2493
+ .dsh-pt-lab-loading{margin:0;padding:16px;color:var(--dsh-pt-text-secondary)}
2494
+ .dsh-pt-lab-body{display:flex;gap:8px;min-height:260px}
2495
+ .dsh-pt-lab-sections{flex:none;display:flex;flex-direction:column;gap:2px;width:200px;overflow:auto}
2496
+ .dsh-pt-lab-section{display:flex;align-items:center;gap:8px;box-sizing:border-box;width:100%;padding:4px 8px;border:1px solid var(--dsh-pt-border-subtle);border-radius:var(--dsh-pt-radius-md);background:var(--dsh-pt-surface-raised);color:var(--dsh-pt-text-secondary);font:inherit;font-size:var(--dsh-pt-font-size-small);text-align:left;cursor:pointer}
2497
+ .dsh-pt-lab-section:hover{background:var(--dsh-pt-surface-sunken)}
2498
+ .dsh-pt-lab-section[aria-selected="true"]{background:var(--dsh-pt-surface-sunken);border-color:var(--dsh-pt-border-strong);color:var(--dsh-pt-text-primary)}
2499
+ .dsh-pt-lab-section[data-changed="true"] .dsh-pt-lab-section-name::after{content:" •";color:var(--dsh-pt-text-primary)}
2500
+ .dsh-pt-lab-section-name{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
2501
+ .dsh-pt-lab-section-meta{flex:none;color:var(--dsh-pt-text-muted);font-size:var(--dsh-pt-font-size-caption);font-variant-numeric:tabular-nums}
2502
+ .dsh-pt-lab-editor{flex:1;min-width:0;display:flex;flex-direction:column;gap:4px}
2503
+ .dsh-pt-lab-textarea{box-sizing:border-box;width:100%;min-height:220px;flex:1;padding:8px;border:1px solid var(--dsh-pt-border-subtle);border-radius:var(--dsh-pt-radius-md);background:var(--dsh-pt-surface-base);color:var(--dsh-pt-text-primary);font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:var(--dsh-pt-font-size-caption);line-height:1.5;resize:vertical}
2504
+ .dsh-pt-lab-textarea:focus,.dsh-pt-lab-trial-input:focus{outline:none;border-color:var(--dsh-pt-focus-ring);box-shadow:0 0 0 1px var(--dsh-pt-focus-ring)}
2505
+ .dsh-pt-lab-meta{display:flex;flex-wrap:wrap;gap:12px;color:var(--dsh-pt-text-muted);font-size:var(--dsh-pt-font-size-caption);font-variant-numeric:tabular-nums}
2506
+ .dsh-pt-lab-over{color:var(--dsh-pt-state-error)}
2507
+ .dsh-pt-lab-preview,.dsh-pt-lab-trial{display:flex;flex-direction:column;gap:4px;min-width:0}
2508
+ .dsh-pt-lab-preview-head,.dsh-pt-lab-trial-head{display:flex;align-items:center;gap:8px}
2509
+ .dsh-pt-lab-preview-title{color:var(--dsh-pt-text-secondary);font-size:var(--dsh-pt-font-size-small);font-weight:600}
2510
+ .dsh-pt-lab-select{height:24px;border:1px solid var(--dsh-pt-border-subtle);border-radius:var(--dsh-pt-radius-sm);background:var(--dsh-pt-surface-raised);color:var(--dsh-pt-text-primary);font:inherit;font-size:var(--dsh-pt-font-size-caption)}
2511
+ .dsh-pt-lab-pre,.dsh-pt-lab-trial-out{box-sizing:border-box;margin:0;padding:8px;max-height:180px;overflow:auto;border:1px solid var(--dsh-pt-border-subtle);border-radius:var(--dsh-pt-radius-md);background:var(--dsh-pt-surface-sunken);color:var(--dsh-pt-text-secondary);font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:var(--dsh-pt-font-size-caption);line-height:1.5;white-space:pre-wrap;word-break:break-word}
2512
+ .dsh-pt-lab-trial-input{box-sizing:border-box;width:100%;min-height:60px;padding:8px;border:1px solid var(--dsh-pt-border-subtle);border-radius:var(--dsh-pt-radius-md);background:var(--dsh-pt-surface-base);color:var(--dsh-pt-text-primary);font:inherit;font-size:var(--dsh-pt-font-size-small);resize:vertical}
2513
+ .dsh-pt-lab-trial-meta{margin:0;color:var(--dsh-pt-text-muted);font-size:var(--dsh-pt-font-size-caption);font-variant-numeric:tabular-nums}
2514
+ .dsh-pt-lab-notice{margin:0;padding:4px 8px;border:1px solid var(--dsh-pt-border-subtle);border-radius:var(--dsh-pt-radius-md);background:var(--dsh-pt-surface-raised);color:var(--dsh-pt-text-secondary);font-size:var(--dsh-pt-font-size-small)}
2515
+ .dsh-pt-lab-notice[data-tone="error"]{color:var(--dsh-pt-state-error)}
2516
+ .dsh-pt-lab-foot{display:flex;flex-wrap:wrap;align-items:center;gap:8px}
2517
+ .dsh-pt-lab-btn{box-sizing:border-box;min-height:26px;padding:0 10px;border:1px solid var(--dsh-pt-border-subtle);border-radius:var(--dsh-pt-radius-md);background:var(--dsh-pt-surface-raised);color:var(--dsh-pt-text-primary);font:inherit;font-size:var(--dsh-pt-font-size-caption);font-weight:600;cursor:pointer}
2518
+ .dsh-pt-lab-btn:hover{background:var(--dsh-pt-surface-sunken)}
2519
+ .dsh-pt-lab-btn:focus-visible{outline:2px solid var(--dsh-pt-focus-ring);outline-offset:1px}
2520
+ .dsh-pt-lab-btn[disabled]{cursor:default;color:var(--dsh-pt-text-muted)}
2521
+ .dsh-pt-lab-btn-primary{margin-left:auto}
2522
+ .dsh-pt-lab-banner{margin:0;padding:4px 8px;border:1px solid var(--dsh-pt-border-subtle);border-radius:var(--dsh-pt-radius-md);background:var(--dsh-pt-surface-raised);color:var(--dsh-pt-text-secondary);font-size:var(--dsh-pt-font-size-caption);line-height:16px}
2523
+ .dsh-pt-lab-trial-note{margin:0;color:var(--dsh-pt-text-muted);font-size:var(--dsh-pt-font-size-caption);line-height:16px}
2524
+ `
2525
+
2526
+ // #endregion Development prompt lab
2527
+
2528
+
2529
+ function isWorkflowShortcut(event) {
2530
+ return event.code === 'KeyW' && event.altKey === true && event.shiftKey === true
2531
+ && !event.ctrlKey && !event.metaKey && !event.isComposing && event.keyCode !== 229
2532
+ }
2533
+
2534
+ const DEFAULT_WORKFLOW_ID = 'software-development'
2535
+ const BUILTIN_WORKFLOW_PREFIX = 'builtin:'
2536
+
2537
+ function isBuiltinWorkflow(workflow) {
2538
+ return workflow.id === DEFAULT_WORKFLOW_ID || workflow.id.startsWith(BUILTIN_WORKFLOW_PREFIX)
2539
+ }
2540
+
2541
+ function workflowName(t, workflow) {
2542
+ if (!isBuiltinWorkflow(workflow)) return workflow.name
2543
+ if (workflow.id === DEFAULT_WORKFLOW_ID) return t('workflow.builtin')
2544
+ return t(`workflow.builtin.${workflow.id.slice(BUILTIN_WORKFLOW_PREFIX.length)}`)
2545
+ }
2546
+
2547
+ function workflowStageName(t, workflow, stage) {
2548
+ return isBuiltinWorkflow(workflow) ? t(`workflow.stage.${stage.id}`) : stage.name
2549
+ }
2550
+
2551
+ function workflowError(t, code) {
2552
+ if (code === 'stale') return t('workflow.stale')
2553
+ if (code === 'no-editor') return t('workflow.readOnly')
2554
+ if (code === 'invalid-workflow') return t('workflow.invalid')
2555
+ if (code === 'invalid-draft') return t('workflow.aiInvalid')
2556
+ if (code === 'invalid-output') return t('workflow.aiOutput')
2557
+ if (code === 'no-route') return t('workflow.aiNoRoute')
2558
+ if (code === 'timeout') return t('workflow.aiTimeout')
2559
+ return t('workflow.failed')
2560
+ }
2561
+
2562
+ function newWorkflowId() {
2563
+ return Array.from(globalThis.crypto.getRandomValues(new Uint8Array(16)), (byte) => byte.toString(16).padStart(2, '0')).join('')
2564
+ }
2565
+
2566
+ function moveWorkflowStage(stages, index, shift) {
2567
+ const next = stages.slice()
2568
+ const [stage] = next.splice(index, 1)
2569
+ next.splice(index + shift, 0, stage)
2570
+ return next
2571
+ }
2572
+
2573
+ const WORKFLOW_CSS = `
2574
+ .dsh-pt-workflow-dialog{box-sizing:border-box;position:fixed;inset:0;width:min(520px,calc(100% - 32px));max-width:none;max-height:calc(100dvh - 32px);margin:auto;padding:0;overflow:hidden;border:1px solid var(--dsh-pt-border-strong);border-radius:var(--dsh-pt-radius-lg);background:var(--dsh-pt-surface-raised);color:var(--dsh-pt-text-primary);box-shadow:var(--dsh-pt-shadow-overlay);font-family:var(--dsh-pt-font-sans);font-size:var(--dsh-pt-font-size-body);line-height:1.5}
2575
+ .dsh-pt-workflow-shell{display:flex;flex-direction:column;max-height:calc(100dvh - 34px);min-width:0}
2576
+ .dsh-pt-workflow-dialog h2,.dsh-pt-workflow-dialog p{margin:0}
2577
+ .dsh-pt-workflow-head{display:grid;grid-template-columns:minmax(0,1fr) auto;align-items:start;gap:var(--dsh-pt-space-3);padding:var(--dsh-pt-space-4);border-bottom:1px solid var(--dsh-pt-border-subtle)}
2578
+ .dsh-pt-workflow-head h2{font-size:var(--dsh-pt-font-size-dialog);font-weight:650}
2579
+ .dsh-pt-workflow-head p{margin-top:var(--dsh-pt-space-1);color:var(--dsh-pt-text-secondary)}
2580
+ .dsh-pt-workflow-content{display:grid;gap:var(--dsh-pt-space-3);padding:var(--dsh-pt-space-3);overflow:auto;min-height:0;overscroll-behavior:contain}
2581
+ .dsh-pt-workflow-section,.dsh-pt-workflow-footer{display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:var(--dsh-pt-space-2)}
2582
+ .dsh-pt-workflow-section{padding:0 var(--dsh-pt-space-1)}
2583
+ .dsh-pt-workflow-section strong{min-width:0;overflow-wrap:anywhere}
2584
+ .dsh-pt-workflow-footer{padding:var(--dsh-pt-space-2) var(--dsh-pt-space-3);border-top:1px solid var(--dsh-pt-border-subtle)}
2585
+ .dsh-pt-workflow-keys{display:flex;align-items:center;gap:var(--dsh-pt-space-2);color:var(--dsh-pt-text-secondary);font-size:var(--dsh-pt-font-size-caption)}
2586
+ .dsh-pt-workflow-key-guide{display:inline-flex;align-items:center;gap:var(--dsh-pt-space-1);white-space:nowrap}
2587
+ .dsh-pt-workflow-list,.dsh-pt-workflow-stage,.dsh-pt-workflow-draft-form,.dsh-pt-workflow-dialog label{display:grid;gap:var(--dsh-pt-space-1)}
2588
+ .dsh-pt-workflow-stage{border:1px solid var(--dsh-pt-border-subtle);padding:var(--dsh-pt-space-3);border-radius:var(--dsh-pt-radius-md)}
2589
+ .dsh-pt-workflow-draft-form{gap:var(--dsh-pt-space-3)}
2590
+ .dsh-pt-workflow-controls{display:flex;flex-wrap:wrap;gap:var(--dsh-pt-space-2)}
2591
+ .dsh-pt-workflow-dialog input,.dsh-pt-workflow-dialog textarea,.dsh-pt-workflow-dialog button,.dsh-pt-workflow-trigger{box-sizing:border-box;padding:var(--dsh-pt-space-1) var(--dsh-pt-space-2);border:1px solid var(--dsh-pt-border-subtle);border-radius:var(--dsh-pt-radius-sm);background:var(--dsh-pt-surface-raised);color:var(--dsh-pt-text-primary);font:inherit}
2592
+ .dsh-pt-workflow-dialog input,.dsh-pt-workflow-dialog textarea{width:100%;background:var(--dsh-pt-surface-base)}
2593
+ .dsh-pt-workflow-dialog textarea{min-height:64px;resize:vertical}
2594
+ .dsh-pt-workflow-dialog button,.dsh-pt-workflow-trigger{cursor:pointer}
2595
+ .dsh-pt-workflow-dialog button:hover:not(:disabled),.dsh-pt-workflow-trigger:hover{background:var(--dsh-pt-surface-sunken)}
2596
+ .dsh-pt-workflow-dialog button:disabled{color:var(--dsh-pt-text-muted);cursor:default}
2597
+ .dsh-pt-workflow-dialog :focus-visible,.dsh-pt-workflow-trigger:focus-visible{outline:2px solid var(--dsh-pt-focus-ring);outline-offset:-2px}
2598
+ .dsh-pt-workflow-dialog .dsh-pt-workflow-quiet,.dsh-pt-workflow-dialog .dsh-pt-workflow-close{border-color:var(--dsh-pt-surface-raised);color:var(--dsh-pt-text-secondary)}
2599
+ .dsh-pt-workflow-dialog .dsh-pt-workflow-close{font-size:var(--dsh-pt-font-size-heading);line-height:1;min-height:28px}
2600
+ .dsh-pt-workflow-dialog .dsh-pt-workflow-primary{background:var(--dsh-pt-accent);color:var(--dsh-pt-accent-ink);font-weight:600}
2601
+ .dsh-pt-workflow-dialog .dsh-pt-workflow-primary:hover:not(:disabled){background:var(--dsh-pt-accent);box-shadow:var(--dsh-pt-shadow-control)}
2602
+ .dsh-pt-workflow-dialog .dsh-pt-workflow-option{display:grid;grid-template-columns:minmax(0,1fr) auto;align-items:center;gap:var(--dsh-pt-space-3);text-align:start;min-height:46px;padding:var(--dsh-pt-space-2) var(--dsh-pt-space-3);border-color:var(--dsh-pt-surface-raised);border-radius:var(--dsh-pt-radius-md)}
2603
+ .dsh-pt-workflow-dialog .dsh-pt-workflow-option[aria-current=true]{border-color:var(--dsh-pt-border-strong)}
2604
+ .dsh-pt-workflow-dialog .dsh-pt-workflow-option:focus-visible{background:var(--dsh-pt-surface-sunken)}
2605
+ .dsh-pt-workflow-option strong,.dsh-pt-workflow-option small{display:block;overflow-wrap:anywhere}
2606
+ .dsh-pt-workflow-option small{font-size:var(--dsh-pt-font-size-small);color:var(--dsh-pt-text-secondary);display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:2;overflow:hidden}
2607
+ .dsh-pt-workflow-current{border-radius:var(--dsh-pt-radius-pill);padding:0 var(--dsh-pt-space-2);background:var(--dsh-pt-surface-base);color:var(--dsh-pt-text-secondary);font-size:var(--dsh-pt-font-size-caption);white-space:nowrap}
2608
+ .dsh-pt-workflow-next{color:var(--dsh-pt-text-secondary);font-size:var(--dsh-pt-font-size-heading)}
2609
+ .dsh-pt-workflow-message{padding:var(--dsh-pt-space-2);border-radius:var(--dsh-pt-radius-sm);background:var(--dsh-pt-surface-base);color:var(--dsh-pt-text-secondary);overflow-wrap:anywhere}
2610
+ .dsh-pt-workflow-trigger{flex:none;pointer-events:auto;font-size:var(--dsh-pt-font-size-caption);max-width:45%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
2611
+ .dsh-pt-workflow-result{margin:0;white-space:pre-wrap;overflow-wrap:anywhere}
2612
+ `
2613
+
2614
+ const WORKFLOW_DOCK_CSS = `${DESIGN_TOKENS_CSS}
2615
+ /* Match InputBar's outer clearance and centred card width in the sibling dock slot. */
2616
+ .dsh-pt-workflow-dock{box-sizing:border-box;inline-size:100%;padding-inline:var(--dsh-composer-side-clearance,16px);display:flex;justify-content:center;min-width:0}
2617
+ .dsh-pt-workflow-dock-row{inline-size:100%;max-inline-size:var(--dsh-composer-card-max-width,100%);display:flex;align-items:center;min-width:0}
2618
+ .dsh-pt-workflow-chip{display:inline-flex;align-items:center;gap:var(--dsh-pt-space-1);min-width:0;max-width:100%;padding:var(--dsh-pt-space-1) var(--dsh-pt-space-2);border:1px solid var(--dsh-pt-border-subtle);border-radius:var(--dsh-pt-radius-pill);background:var(--dsh-pt-surface-raised);color:var(--dsh-pt-text-secondary);font:600 var(--dsh-pt-font-size-small)/1.35 var(--dsh-pt-font-sans);cursor:pointer}
2619
+ .dsh-pt-workflow-chip:hover{background:var(--dsh-pt-surface-sunken);color:var(--dsh-pt-text-primary)}
2620
+ .dsh-pt-workflow-chip:focus-visible{outline:2px solid var(--dsh-pt-focus-ring);outline-offset:1px}
2621
+ .dsh-pt-workflow-chip-label{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
2622
+ .dsh-pt-workflow-chip-caret{flex:none}
2623
+ `
2624
+
2625
+ function WorkflowStageDock({ t, sessionId, workflowControls }) {
2626
+ const current = React.useSyncExternalStore(workflowControls.subscribe, () => workflowControls.selections.get(sessionId))
2627
+ if (!current) return null
2628
+ return h('div', { className: 'dsh-pt-workflow-dock' },
2629
+ h('style', null, WORKFLOW_DOCK_CSS),
2630
+ h('div', { className: 'dsh-pt-workflow-dock-row' },
2631
+ h('button', {
2632
+ type: 'button',
2633
+ className: 'dsh-pt-workflow-chip',
2634
+ title: current.label,
2635
+ 'aria-label': t('workflow.openCurrent', { stage: current.label }),
2636
+ 'aria-haspopup': 'dialog',
2637
+ onMouseDown: (event) => event.preventDefault(),
2638
+ onClick: (event) => workflowControls.openers.get(sessionId)?.(event.currentTarget),
2639
+ }, h('span', { className: 'dsh-pt-workflow-chip-label' }, current.label),
2640
+ h('span', { className: 'dsh-pt-workflow-chip-caret', 'aria-hidden': 'true' }, '⌄'))))
2641
+ }
2642
+
2643
+ function WorkflowDialog({ t, sessionId, catalog, selection, initialError, draft, context, onClose, onChoose, onCatalog, onWorkflows, onSuggest }) {
2644
+ const [workflowId, setWorkflowId] = React.useState(selection?.workflowId || DEFAULT_WORKFLOW_ID)
2645
+ const [choosingWorkflow, setChoosingWorkflow] = React.useState(false)
2646
+ const [managing, setManaging] = React.useState(false)
2647
+ const [editing, setEditing] = React.useState(null)
2648
+ const [draftForm, setDraftForm] = React.useState(null)
2649
+ const [drafting, setDrafting] = React.useState(false)
2650
+ const [draftBasis, setDraftBasis] = React.useState(null)
2651
+ const [deleting, setDeleting] = React.useState(null)
2652
+ const [notice, setNotice] = React.useState(initialError)
2653
+ const [busy, setBusy] = React.useState(false)
2654
+ const [trial, setTrial] = React.useState(null)
2655
+ const [savedStage, setSavedStage] = React.useState(null)
2656
+ const panelRef = React.useRef(null)
2657
+ const initialFocusRef = React.useRef(null)
2658
+ const trialTicket = React.useRef(0)
2659
+ const draftTicket = React.useRef(0)
2660
+ const activeDraft = React.useRef(false)
2661
+ const mounted = React.useRef(false)
2662
+ const currentContext = React.useRef(context)
2663
+ const draftRef = React.useRef(draft)
2664
+ currentContext.current = context
2665
+ draftRef.current = draft
2666
+ const workflow = catalog?.workflows.find((item) => item.id === workflowId)
2667
+ const currentStage = workflow?.id === selection?.workflowId ? selection?.stageId : null
2668
+ const pickingStage = Boolean(workflow) && !choosingWorkflow && !managing
2669
+ const pickingOption = catalog !== null && !managing
2670
+
2671
+ React.useEffect(() => {
2672
+ mounted.current = true
2673
+ const panel = panelRef.current
2674
+ if (panel && !panel.open) panel.showModal()
2675
+ return () => {
2676
+ if (panel?.open) panel.close()
2677
+ mounted.current = false
2678
+ trialTicket.current += 1
2679
+ draftTicket.current += 1
2680
+ activeDraft.current = false
2681
+ }
2682
+ }, [])
2683
+ React.useEffect(() => {
2684
+ initialFocusRef.current?.focus()
2685
+ }, [workflowId, choosingWorkflow, managing, editing?.id, deleting?.id, draftForm !== null, Boolean(catalog)])
2686
+ React.useEffect(() => {
2687
+ setNotice(initialError)
2688
+ }, [initialError])
2689
+ React.useEffect(() => {
2690
+ trialTicket.current += 1
2691
+ setTrial(null)
2692
+ }, [context, draft])
2693
+
2694
+ const changeEditor = (value) => {
2695
+ trialTicket.current += 1
2696
+ setTrial(null)
2697
+ setNotice('')
2698
+ setSavedStage(null)
2699
+ setEditing(value)
2700
+ if (value === null) setDraftBasis(null)
2701
+ }
2702
+
2703
+ const closeDraftForm = () => {
2704
+ draftTicket.current += 1
2705
+ activeDraft.current = false
2706
+ setDrafting(false)
2707
+ setDraftForm(null)
2708
+ setNotice('')
2709
+ }
2710
+
2711
+ const draftWorkflow = async (event) => {
2712
+ event.preventDefault()
2713
+ if (activeDraft.current || !draftForm?.task.trim()) return
2714
+ activeDraft.current = true
2715
+ const ticket = ++draftTicket.current
2716
+ const task = draftForm.task.trim()
2717
+ const reference = draftForm.reference.trim()
2718
+ setNotice('')
2719
+ setDrafting(true)
2720
+ const result = await onWorkflows(sessionId, 'draft', { task, reference })
2721
+ if (!mounted.current || ticket !== draftTicket.current) return
2722
+ activeDraft.current = false
2723
+ setDrafting(false)
2724
+ if (!result.ok) {
2725
+ setNotice(workflowError(t, result.code))
2726
+ return
2727
+ }
2728
+ setDraftForm(null)
2729
+ changeEditor(result.data)
2730
+ setDraftBasis(reference ? 'workflow.aiReviewWithReference' : 'workflow.aiReview')
2731
+ }
2732
+
2733
+ const makeWorkflow = (source = null) => ({
2734
+ id: newWorkflowId(),
2735
+ name: source === null ? '' : t('workflow.copyName', { name: workflowName(t, source) }).slice(0, 40),
2736
+ stages: source === null
2737
+ ? [{ id: newWorkflowId(), name: '', focus: '', deliverable: '' }]
2738
+ : source.stages.map((stage) => ({
2739
+ id: newWorkflowId(), name: workflowStageName(t, source, stage), focus: stage.focus, deliverable: stage.deliverable || '',
2740
+ })),
2741
+ })
2742
+
2743
+ const updateStage = (index, patch) => {
2744
+ changeEditor({ ...editing, stages: editing.stages.map((stage, offset) => offset === index ? { ...stage, ...patch } : stage) })
2745
+ }
2746
+
2747
+ const write = async (op, value) => {
2748
+ if (busy || !catalog?.writable) return
2749
+ setBusy(true)
2750
+ trialTicket.current += 1
2751
+ setTrial(null)
2752
+ const result = await onWorkflows(sessionId, op, { ...value, revision: catalog.revision })
2753
+ if (!mounted.current) return
2754
+ setBusy(false)
2755
+ if (!result.ok) {
2756
+ setNotice(workflowError(t, result.code))
2757
+ return
2758
+ }
2759
+ onCatalog(result.data)
2760
+ setNotice(t('workflow.saved'))
2761
+ setDeleting(null)
2762
+ setEditing(null)
2763
+ setDraftBasis(null)
2764
+ setManaging(false)
2765
+ if (op === 'save') {
2766
+ setWorkflowId(value.workflow.id)
2767
+ setChoosingWorkflow(false)
2768
+ setSavedStage(value.workflow.id)
2769
+ } else if (workflowId === value.id) setWorkflowId(DEFAULT_WORKFLOW_ID)
2770
+ }
2771
+
2772
+ const runTrial = async (stage) => {
2773
+ if (draftRef.current === null) {
2774
+ setNotice(t('workflow.trialBlocked'))
2775
+ return
2776
+ }
2777
+ const ticket = ++trialTicket.current
2778
+ const contextSnapshot = context
2779
+ const draftSnapshot = draftRef.current
2780
+ setNotice('')
2781
+ setTrial({ stage, loading: true })
2782
+ const result = await onSuggest(sessionId, draftSnapshot === '' ? 'suggest' : 'optimize', draftSnapshot, { previewStage: stage })
2783
+ if (!mounted.current || ticket !== trialTicket.current || contextSnapshot !== currentContext.current || draftSnapshot !== draftRef.current) return
2784
+ setTrial({ stage, text: result.ok ? result.text : workflowError(t, result.code), loading: false })
2785
+ }
2786
+
2787
+ const closePanel = () => {
2788
+ if (panelRef.current?.open) panelRef.current.close()
2789
+ }
2790
+ const dismiss = () => {
2791
+ closePanel()
2792
+ onClose(true)
2793
+ }
2794
+ const chooseStage = (flow, stage) => {
2795
+ closePanel()
2796
+ onChoose(flow, stage)
2797
+ }
2798
+
2799
+ const optionKeys = (event) => {
2800
+ if (event.isComposing || event.keyCode === 229) return
2801
+ const keys = ['ArrowUp', 'ArrowLeft', 'ArrowDown', 'ArrowRight', 'Home', 'End']
2802
+ if (!keys.includes(event.key)) return
2803
+ const buttons = Array.from(event.currentTarget.querySelectorAll('button'))
2804
+ const index = buttons.indexOf(event.target)
2805
+ if (index < 0) return
2806
+ const offset = event.key === 'ArrowUp' || event.key === 'ArrowLeft' ? -1 : 1
2807
+ const next = event.key === 'Home' ? 0 : event.key === 'End' ? buttons.length - 1
2808
+ : (index + offset + buttons.length) % buttons.length
2809
+ event.preventDefault()
2810
+ buttons[next]?.focus()
2811
+ }
2812
+
2813
+ const button = (label, action, props = {}) => h('button', { type: 'button', onClick: action, ...props }, label)
2814
+ const quiet = (label, action, props = {}) => button(label, action, { className: 'dsh-pt-workflow-quiet', ...props })
2815
+ const option = (name, detail, action, { current = false, next = false, ...props } = {}) => h('button', {
2816
+ type: 'button', className: 'dsh-pt-workflow-option', onClick: action,
2817
+ 'aria-current': current ? 'true' : undefined, ...props,
2818
+ },
2819
+ h('span', null, h('strong', null, name), detail ? h('small', null, detail) : null),
2820
+ current ? h('span', { className: 'dsh-pt-workflow-current', 'aria-hidden': 'true' }, t('workflow.current'))
2821
+ : next ? h('span', { className: 'dsh-pt-workflow-next', 'aria-hidden': 'true' }, '›') : null)
2822
+ const controls = (...children) => h('div', { className: 'dsh-pt-workflow-controls' }, ...children)
2823
+ const field = (key, value, onChange, maxLength, multiline = false, ref = undefined) => h('label', null,
2824
+ t(key),
2825
+ h(multiline ? 'textarea' : 'input', { ref, value, maxLength, disabled: busy, onChange: (event) => onChange(event.target.value) }))
2826
+ const keyGuide = (key, label) => h('span', { className: 'dsh-pt-workflow-key-guide' }, h('kbd', { className: 'dsh-pt-kbd' }, key), t(label))
2827
+
2828
+ let body = null
2829
+ if (catalog === null) {
2830
+ body = h('p', { role: 'status' }, notice || t('workflow.loading'))
2831
+ } else if (editing !== null) {
2832
+ body = h(React.Fragment, null,
2833
+ draftBasis ? h('p', { className: 'dsh-pt-workflow-message', role: 'status' }, t(draftBasis)) : null,
2834
+ field('workflow.name', editing.name, (name) => changeEditor({ ...editing, name }), 40, false, initialFocusRef),
2835
+ ...editing.stages.map((stage, index) => h('section', { className: 'dsh-pt-workflow-stage', key: stage.id },
2836
+ field('workflow.stageName', stage.name, (name) => updateStage(index, { name }), 40),
2837
+ field('workflow.focus', stage.focus, (focus) => updateStage(index, { focus }), 500, true),
2838
+ h('details', { open: stage.deliverable ? true : undefined },
2839
+ h('summary', null, t('workflow.optional')),
2840
+ field('workflow.deliverable', stage.deliverable, (deliverable) => updateStage(index, { deliverable }), 200, true)),
2841
+ controls(
2842
+ button(t('workflow.up'), () => changeEditor({ ...editing, stages: moveWorkflowStage(editing.stages, index, -1) }), { disabled: busy || index === 0 }),
2843
+ button(t('workflow.down'), () => changeEditor({ ...editing, stages: moveWorkflowStage(editing.stages, index, 1) }), { disabled: busy || index + 1 === editing.stages.length }),
2844
+ button(t('workflow.removeStage'), () => changeEditor({ ...editing, stages: editing.stages.filter((item) => item.id !== stage.id) }), { disabled: busy || editing.stages.length < 2 }),
2845
+ button(t('workflow.trial'), () => runTrial(stage), { disabled: busy || trial?.loading || !stage.name.trim() || !stage.focus.trim() })),
2846
+ trial?.stage.id === stage.id ? h('div', { role: 'status' },
2847
+ h('strong', null, t('workflow.trialTitle')),
2848
+ h('p', { className: 'dsh-pt-workflow-result' }, trial.loading ? t('workflow.loading') : trial.text)) : null)),
2849
+ controls(
2850
+ button(t('workflow.add'), () => changeEditor({ ...editing, stages: [...editing.stages, { id: newWorkflowId(), name: '', focus: '', deliverable: '' }] }), { disabled: busy || editing.stages.length >= 12 }),
2851
+ button(t('workflow.save'), () => write('save', { workflow: editing }), { disabled: busy, className: 'dsh-pt-workflow-primary' }),
2852
+ button(t('workflow.back'), () => changeEditor(null), { disabled: busy })),
2853
+ h('p', null, t('workflow.reloadHint')))
2854
+ } else if (draftForm !== null) {
2855
+ body = h('form', { className: 'dsh-pt-workflow-draft-form', onSubmit: draftWorkflow, 'aria-busy': drafting },
2856
+ h('label', null, t('workflow.aiTask'), h('textarea', {
2857
+ ref: initialFocusRef, required: true, value: draftForm.task, maxLength: 2000, disabled: drafting,
2858
+ placeholder: t('workflow.aiTaskPlaceholder'),
2859
+ onChange: (event) => setDraftForm({ ...draftForm, task: event.target.value }),
2860
+ })),
2861
+ h('label', null, t('workflow.aiReference'), h('textarea', {
2862
+ value: draftForm.reference, maxLength: 3000, disabled: drafting,
2863
+ placeholder: t('workflow.aiReferencePlaceholder'),
2864
+ onChange: (event) => setDraftForm({ ...draftForm, reference: event.target.value }),
2865
+ })),
2866
+ controls(
2867
+ button(t('workflow.back'), closeDraftForm),
2868
+ button(t('workflow.aiGenerate'), undefined, {
2869
+ type: 'submit', className: 'dsh-pt-workflow-primary', disabled: drafting || !draftForm.task.trim(),
2870
+ })),
2871
+ drafting ? h('p', { role: 'status' }, t('workflow.aiGenerating')) : null)
2872
+ } else if (deleting !== null) {
2873
+ body = h(React.Fragment, null,
2874
+ h('p', null, t('workflow.confirmDelete', { name: workflowName(t, deleting), stages: deleting.stages.map((stage) => stage.name).join(' · ') })),
2875
+ controls(
2876
+ button(t('workflow.back'), () => setDeleting(null), { ref: initialFocusRef, disabled: busy }),
2877
+ button(t('workflow.delete'), () => write('delete', { id: deleting.id }), { disabled: busy })))
2878
+ } else if (managing) {
2879
+ body = h(React.Fragment, null,
2880
+ controls(
2881
+ button(t('workflow.aiDraft'), () => {
2882
+ setNotice('')
2883
+ setDraftForm({ task: '', reference: '' })
2884
+ }, { ref: initialFocusRef, className: 'dsh-pt-workflow-primary' }),
2885
+ button(t('workflow.new'), () => changeEditor(makeWorkflow())),
2886
+ button(t('workflow.back'), () => setManaging(false))),
2887
+ ...catalog.workflows.map((item) => h('section', { className: 'dsh-pt-workflow-stage', key: item.id },
2888
+ h('strong', null, workflowName(t, item)),
2889
+ controls(
2890
+ isBuiltinWorkflow(item) ? null : button(t('workflow.edit'), () => changeEditor(structuredClone(item))),
2891
+ button(t('workflow.copy'), () => changeEditor(makeWorkflow(item))),
2892
+ isBuiltinWorkflow(item) ? null : button(t('workflow.delete'), () => setDeleting(item))))))
2893
+ } else if (pickingStage) {
2894
+ const focusStage = currentStage || workflow.stages[0]?.id
2895
+ body = h(React.Fragment, null,
2896
+ h('div', { className: 'dsh-pt-workflow-section' },
2897
+ h('strong', null, workflowName(t, workflow)),
2898
+ quiet(t('workflow.switch'), () => setChoosingWorkflow(true))),
2899
+ h('div', { className: 'dsh-pt-workflow-list', role: 'group', 'aria-label': workflowName(t, workflow), onKeyDown: optionKeys },
2900
+ ...workflow.stages.map((stage) => option(
2901
+ workflowStageName(t, workflow, stage),
2902
+ isBuiltinWorkflow(workflow) ? t(`workflow.stage.${stage.id}Hint`) : stage.focus,
2903
+ () => chooseStage(workflow, stage),
2904
+ { key: stage.id, ref: stage.id === focusStage ? initialFocusRef : undefined, current: stage.id === currentStage },
2905
+ )),
2906
+ option(t('workflow.clear'), t('workflow.clearHint'), () => chooseStage(null, null), { current: !selection })),
2907
+ savedStage === workflow.id ? h('p', null, t('workflow.useSaved')) : null)
2908
+ } else {
2909
+ const initial = workflow?.id || catalog.workflows[0]?.id
2910
+ body = h('div', { className: 'dsh-pt-workflow-list', role: 'group', 'aria-label': t('workflow.choose'), onKeyDown: optionKeys },
2911
+ ...catalog.workflows.map((item) => option(workflowName(t, item), '', () => {
2912
+ setWorkflowId(item.id)
2913
+ setChoosingWorkflow(false)
2914
+ }, { key: item.id, ref: item.id === initial ? initialFocusRef : undefined, next: true })))
2915
+ }
2916
+
2917
+ const title = draftForm !== null ? t('workflow.aiDraft') : deleting !== null ? t('workflow.delete')
2918
+ : editing !== null ? t('workflow.edit') : managing ? t('workflow.manage') : pickingOption && !pickingStage ? t('workflow.choose') : t('workflow.title')
2919
+ return h('dialog', {
2920
+ className: 'dsh-pt-workflow-dialog', ref: panelRef, 'aria-label': title,
2921
+ onCancel: (event) => { event.preventDefault(); dismiss() },
2922
+ onClick: (event) => { if (event.target === event.currentTarget && !managing) dismiss() },
2923
+ }, h('div', { className: 'dsh-pt-workflow-shell' },
2924
+ h('header', { className: 'dsh-pt-workflow-head' },
2925
+ h('div', null, h('h2', null, title),
2926
+ pickingStage ? h('p', null, t('workflow.intro')) : draftForm !== null ? h('p', null, t('workflow.aiIntro')) : null),
2927
+ button('×', dismiss, {
2928
+ className: 'dsh-pt-workflow-close', 'aria-label': t('workflow.close'), title: t('workflow.close'),
2929
+ ref: !catalog ? initialFocusRef : undefined,
2930
+ })),
2931
+ h('div', { className: 'dsh-pt-workflow-content' }, body,
2932
+ catalog !== null && notice ? h('p', { className: 'dsh-pt-workflow-message', role: 'status' }, notice) : null,
2933
+ pickingOption && !catalog.writable ? h('p', { className: 'dsh-pt-workflow-message' }, t('workflow.readOnly')) : null),
2934
+ pickingOption ? h('footer', { className: 'dsh-pt-workflow-footer' },
2935
+ h('div', { className: 'dsh-pt-workflow-keys', 'aria-hidden': 'true' },
2936
+ keyGuide('↑ ↓', 'workflow.keysMove'), keyGuide('Enter', 'workflow.keysSelect'), keyGuide('Esc', 'workflow.close')),
2937
+ catalog.writable ? quiet(t('workflow.manage'), () => setManaging(true)) : null) : null))
2938
+ }
2939
+
2940
+ function PromptSuggestionOverlay({ t, sessionId, inputActions, useInput, useChat, onSuggest, onWorkflows, workflowControls }) {
2941
+ const workflowSelections = workflowControls.selections
1719
2942
  const input = useInput((snapshot) => snapshot)
1720
2943
  const messageCount = useChat(countSuggestionMessages)
1721
2944
  const chatOrder = useChat((snapshot) => snapshot === null || snapshot === undefined ? promptHistoryEmptyOrder : snapshot.order)
@@ -1737,7 +2960,7 @@ window.__ModuleLoader__.load({
1737
2960
  const cooldownRef = React.useRef(0)
1738
2961
  const graceTimerRef = React.useRef(null)
1739
2962
  const historyRef = React.useRef({ active: false, index: -1, originalDraft: '', expectedDraft: '' })
1740
- const historyCacheRef = React.useRef({ order: null, nodes: null, list: [] })
2963
+ const historyCacheRef = React.useRef({ order: null, nodes: null, list: [], context: [] })
1741
2964
  const tabNoticeTimerRef = React.useRef(null)
1742
2965
  const historyNoticeTimerRef = React.useRef(null)
1743
2966
  const [ghost, setGhost] = React.useState(null)
@@ -1747,6 +2970,15 @@ window.__ModuleLoader__.load({
1747
2970
  const [tabActionListOpen, setTabActionListOpen] = React.useState(false)
1748
2971
  const tabActionListOpenRef = React.useRef(false)
1749
2972
  const tabActionListReturnFocusRef = React.useRef(null)
2973
+ const [workflowOpen, setWorkflowOpen] = React.useState(false)
2974
+ const [catalog, setCatalog] = React.useState(null)
2975
+ const [catalogError, setCatalogError] = React.useState('')
2976
+ const [trialSelectionBlocked, setTrialSelectionBlocked] = React.useState(false)
2977
+ const workflowOpenRef = React.useRef(false)
2978
+ const workflowTicket = React.useRef(0)
2979
+ const workflowRequest = React.useRef(null)
2980
+ const editorRef = React.useRef(null)
2981
+ const workflowSelection = workflowSelections.get(sessionId)
1750
2982
 
1751
2983
  inputRef.current = input
1752
2984
  messageRef.current = messageCount
@@ -1757,9 +2989,13 @@ window.__ModuleLoader__.load({
1757
2989
  order: chatOrder,
1758
2990
  nodes: chatNodes,
1759
2991
  list: extractPromptHistory(chatOrder, chatNodes),
2992
+ context: workflowConversationContext(chatOrder, chatNodes, historyCacheRef.current.context),
1760
2993
  }
1761
2994
  }
1762
2995
  const promptHistory = historyCacheRef.current.list
2996
+ const conversationContext = historyCacheRef.current.context
2997
+ const currentSession = React.useRef(sessionId)
2998
+ currentSession.current = sessionId
1763
2999
 
1764
3000
  const clearHistoryNotice = () => {
1765
3001
  if (historyNoticeTimerRef.current !== null) {
@@ -1804,6 +3040,7 @@ window.__ModuleLoader__.load({
1804
3040
  tabRef.current = 'idle'
1805
3041
  requestRef.current += 1
1806
3042
  modeRef.current = null
3043
+ workflowRequest.current = null
1807
3044
  draftRef.current = ''
1808
3045
  cursorRef.current = null
1809
3046
  selectionRef.current = null
@@ -1852,6 +3089,80 @@ window.__ModuleLoader__.load({
1852
3089
  setTabActionListOpen(true)
1853
3090
  }
1854
3091
 
3092
+ const closeWorkflow = (restoreFocus) => {
3093
+ tabDownRef.current = false
3094
+ workflowOpenRef.current = false
3095
+ workflowTicket.current += 1
3096
+ setWorkflowOpen(false)
3097
+ if (restoreFocus) editorRef.current?.focus()
3098
+ }
3099
+
3100
+ const applyCatalog = (next) => {
3101
+ reset()
3102
+ setCatalog(next)
3103
+ for (const [id, selected] of workflowSelections) {
3104
+ const flow = next.workflows.find((item) => item.id === selected.workflowId)
3105
+ const stage = flow?.stages.find((item) => item.id === selected.stageId)
3106
+ if (!stage) {
3107
+ workflowControls.setSelection(id, undefined)
3108
+ if (id === sessionId) setCatalogError(t('workflow.missing'))
3109
+ } else if (selected.revision !== next.revision) {
3110
+ workflowControls.setSelection(id, {
3111
+ workflowId: flow.id, stageId: stage.id, revision: next.revision,
3112
+ label: `${workflowName(t, flow)} · ${workflowStageName(t, flow, stage)}`,
3113
+ })
3114
+ }
3115
+ }
3116
+ }
3117
+
3118
+ const openWorkflow = (editor) => {
3119
+ if (workflowOpenRef.current || typeof onWorkflows !== 'function' || !sessionId) return
3120
+ editorRef.current = editor
3121
+ try {
3122
+ const span = inputActions?.captureInsertion()
3123
+ setTrialSelectionBlocked(!span || span.start !== span.end)
3124
+ } catch (_error) {
3125
+ setTrialSelectionBlocked(true)
3126
+ }
3127
+ resetHistory()
3128
+ reset()
3129
+ clearTabNotice()
3130
+ setCatalog(null)
3131
+ setCatalogError('')
3132
+ workflowOpenRef.current = true
3133
+ setWorkflowOpen(true)
3134
+ const ticket = ++workflowTicket.current
3135
+ onWorkflows(sessionId, 'read').then((result) => {
3136
+ if (ticket !== workflowTicket.current || currentSession.current !== sessionId) return
3137
+ if (result.ok) applyCatalog(result.data)
3138
+ else setCatalogError(workflowError(t, result.code))
3139
+ })
3140
+ }
3141
+
3142
+ React.useEffect(() => {
3143
+ if (!sessionId) return
3144
+ const openFromDock = (button) => openWorkflow(editorRef.current || button)
3145
+ workflowControls.openers.set(sessionId, openFromDock)
3146
+ return () => {
3147
+ if (workflowControls.openers.get(sessionId) === openFromDock) workflowControls.openers.delete(sessionId)
3148
+ }
3149
+ }, [sessionId, inputActions, onWorkflows, workflowControls, t])
3150
+
3151
+ const chooseWorkflowStage = (flow, stage) => {
3152
+ if (!flow || !stage) workflowControls.setSelection(sessionId, undefined)
3153
+ else workflowControls.setSelection(sessionId, {
3154
+ workflowId: flow.id, stageId: stage.id, revision: catalog.revision,
3155
+ label: `${workflowName(t, flow)} · ${workflowStageName(t, flow, stage)}`,
3156
+ })
3157
+ cooldownRef.current = 0
3158
+ reset()
3159
+ closeWorkflow(true)
3160
+ }
3161
+
3162
+ const workflowRequestIsCurrent = (snapshot) => snapshot === null
3163
+ || (snapshot.sessionId === currentSession.current && snapshot.context === historyCacheRef.current.context
3164
+ && snapshot.selection === workflowSelections.get(snapshot.sessionId))
3165
+
1855
3166
  const eligibleMode = () => {
1856
3167
  if (Date.now() < cooldownRef.current) return null
1857
3168
  if (typeof sessionId !== 'string' || sessionId === '') return null
@@ -1888,7 +3199,7 @@ window.__ModuleLoader__.load({
1888
3199
  }
1889
3200
 
1890
3201
  const suggestionFor = (key, mode, draft, extra = {}) => {
1891
- const cached = cacheRef.current.get(key)
3202
+ const cached = extra.workflow ? undefined : cacheRef.current.get(key)
1892
3203
  if (cached !== undefined && Date.now() - cached.at < SUGGEST_CACHE_TTL) {
1893
3204
  return Promise.resolve({ ok: true, text: cached.text })
1894
3205
  }
@@ -1906,8 +3217,10 @@ window.__ModuleLoader__.load({
1906
3217
  }
1907
3218
  const value = typeof result.text === 'string' ? result.text.trim() : ''
1908
3219
  if (value === '') return { ok: false, code: 'empty-output' }
1909
- cacheRef.current.set(key, { text: value, at: Date.now() })
1910
- trimCache()
3220
+ if (!extra.workflow) {
3221
+ cacheRef.current.set(key, { text: value, at: Date.now() })
3222
+ trimCache()
3223
+ }
1911
3224
  return { ok: true, text: value }
1912
3225
  })
1913
3226
  .catch((error) => {
@@ -1965,16 +3278,21 @@ window.__ModuleLoader__.load({
1965
3278
  const ticket = requestRef.current + 1
1966
3279
  requestRef.current = ticket
1967
3280
  const meta = suggestionMetaFor(currentInput, span)
3281
+ const workflow = mode === 'suggest' || mode === 'optimize' ? workflowSelections.get(sessionId) : undefined
3282
+ const phaseRequest = workflow ? { sessionId, context: historyCacheRef.current.context, selection: workflow } : null
3283
+ workflowRequest.current = phaseRequest
1968
3284
  const baseKey = cacheKeyFor(mode, draft, { ...(cursor || selection || { start: 0, end: 0 }), meta })
1969
- const key = force ? `${baseKey}:regen:${ticket}` : baseKey
1970
- const cached = force ? undefined : cacheRef.current.get(key)
3285
+ // A stage request always revalidates its configuration revision on the Host.
3286
+ const key = force || workflow ? `${baseKey}:request:${ticket}` : baseKey
3287
+ const cached = force || workflow ? undefined : cacheRef.current.get(key)
1971
3288
  if (cached !== undefined && Date.now() - cached.at < SUGGEST_CACHE_TTL) {
1972
3289
  setGhost({ mode, text: stripCommandSuggestion(cached.text, activeCommandToken()), loading: false, error: null, prefix: cursor ? cursor.prefix : '', suffix: cursor ? cursor.suffix : '', selection })
1973
3290
  if (tabRef.current === 'grace') scheduleGrace()
1974
3291
  return
1975
3292
  }
1976
3293
  setGhost({ mode, text: '', loading: true, error: null, prefix: cursor ? cursor.prefix : '', suffix: cursor ? cursor.suffix : '', selection })
1977
- suggestionFor(key, mode, draft, { ...(cursor || {}), meta }).then((result) => {
3294
+ suggestionFor(key, mode, draft, { ...(cursor || {}), meta, workflow }).then((result) => {
3295
+ if (!workflowRequestIsCurrent(phaseRequest)) return
1978
3296
  if (ticket !== requestRef.current || (tabRef.current !== 'holding' && tabRef.current !== 'grace')) return
1979
3297
  if (!modeStillValid(mode)) return
1980
3298
  if (!result.ok) {
@@ -2062,6 +3380,10 @@ window.__ModuleLoader__.load({
2062
3380
  }
2063
3381
 
2064
3382
  const accept = (text) => {
3383
+ if (!workflowRequestIsCurrent(workflowRequest.current)) {
3384
+ reset()
3385
+ return
3386
+ }
2065
3387
  const mode = modeRef.current
2066
3388
  let accepted = false
2067
3389
  let notice = ''
@@ -2136,7 +3458,7 @@ window.__ModuleLoader__.load({
2136
3458
  const onKeyDown = (event) => {
2137
3459
  if (event.defaultPrevented) return
2138
3460
  if (event.isComposing || event.keyCode === 229) return
2139
- if (tabActionListOpenRef.current === true) return
3461
+ if (tabActionListOpenRef.current === true || workflowOpenRef.current) return
2140
3462
  const anchor = anchorRef.current
2141
3463
  if (anchor === null) return
2142
3464
  const target = event.target
@@ -2147,6 +3469,31 @@ window.__ModuleLoader__.load({
2147
3469
  const card = targetCard !== null ? targetCard : anchor.closest('[data-composer-card]')
2148
3470
  if (card === null || !card.contains(target)) return
2149
3471
 
3472
+ if (isWorkflowShortcut(event)) {
3473
+ const editor = target instanceof Element ? target.closest('[contenteditable="true"]') : null
3474
+ if (editor === null) return
3475
+ event.preventDefault()
3476
+ event.stopPropagation()
3477
+ if (!event.repeat) openWorkflow(editor)
3478
+ return
3479
+ }
3480
+
3481
+ if (isPromptLabShortcut(event)) {
3482
+ event.preventDefault()
3483
+ event.stopPropagation()
3484
+ if (event.repeat) return
3485
+ // Open the page only when the Host reports the lab command; otherwise stay silent.
3486
+ const labBridge = promptLabBridge
3487
+ if (typeof labBridge.request !== 'function') {
3488
+ showTabNotice(t('lab.errorUnavailable'))
3489
+ return
3490
+ }
3491
+ labBridge.request(sessionId, 'read').then((result) => {
3492
+ if (result !== null && result !== undefined && result.ok === true) openPromptLab(sessionId)
3493
+ else showTabNotice(t('lab.errorUnavailable'))
3494
+ }).catch(() => showTabNotice(t('lab.errorUnavailable')))
3495
+ return
3496
+ }
2150
3497
 
2151
3498
  if (isTabActionListShortcut(event, tabDownRef.current)) {
2152
3499
  const targetEditor = target instanceof HTMLElement && target.isContentEditable === true
@@ -2172,6 +3519,7 @@ window.__ModuleLoader__.load({
2172
3519
  ? target.closest('[contenteditable="true"]')
2173
3520
  : null
2174
3521
  if (editor === null || !(editor instanceof HTMLElement)) return
3522
+ editorRef.current = editor
2175
3523
  if (!event.repeat) tabDownRef.current = true
2176
3524
  if (event.repeat && tabDownRef.current && tabRef.current === 'idle') {
2177
3525
  event.preventDefault()
@@ -2310,7 +3658,7 @@ window.__ModuleLoader__.load({
2310
3658
  if (anchor === null) return
2311
3659
  const target = event.target
2312
3660
  if (typeof Node === 'undefined' || !(target instanceof Node)) return
2313
- if (target instanceof Element && target.closest('[data-dsh-pt-regenerate]') !== null) return
3661
+ if (target instanceof Element && target.closest('[data-dsh-pt-regenerate], [data-dsh-pt-workflow]') !== null) return
2314
3662
  const card = anchor.closest('[data-composer-card]')
2315
3663
  if (card !== null && card.contains(target)) reset()
2316
3664
  }
@@ -2336,7 +3684,7 @@ window.__ModuleLoader__.load({
2336
3684
  window.removeEventListener('blur', onBlur)
2337
3685
  document.removeEventListener('visibilitychange', onVisibility)
2338
3686
  }
2339
- }, [input, messageCount, sessionId, onSuggest, inputActions, t])
3687
+ }, [input, messageCount, sessionId, onSuggest, onWorkflows, inputActions, t])
2340
3688
 
2341
3689
  React.useEffect(() => {
2342
3690
  const onHistoryKeyDown = (event) => {
@@ -2485,8 +3833,14 @@ window.__ModuleLoader__.load({
2485
3833
  resetHistory()
2486
3834
  clearTabNotice()
2487
3835
  closeTabActionList(false)
3836
+ closeWorkflow(false)
3837
+ editorRef.current = null
2488
3838
  }, [sessionId])
2489
3839
 
3840
+ React.useEffect(() => {
3841
+ if (workflowRequest.current !== null && !workflowRequestIsCurrent(workflowRequest.current)) reset()
3842
+ }, [conversationContext])
3843
+
2490
3844
  React.useEffect(() => {
2491
3845
  if (modeRef.current !== 'optimize') reset()
2492
3846
  resetHistory()
@@ -2546,6 +3900,8 @@ window.__ModuleLoader__.load({
2546
3900
  if (base === 'empty-output') return t('suggestion.emptyOutput')
2547
3901
  if (base === 'aborted') return t('suggestion.aborted')
2548
3902
  if (base === 'invalid-payload' || base === 'remote' || base === 'command-failed') return t('suggestion.hostOutdated')
3903
+ if (base === 'workflow-stale') return t('workflow.stale')
3904
+ if (base === 'workflow-missing') return t('workflow.missing')
2549
3905
  if (base === 'bad-draft') return t('suggestion.badDraft')
2550
3906
  if (base === 'no-session') return t('suggestion.noSession')
2551
3907
  if (base === 'unavailable') return t('suggestion.unavailable')
@@ -2597,6 +3953,18 @@ window.__ModuleLoader__.load({
2597
3953
  ? null
2598
3954
  : h('span', { className: 'dsh-pt-confirm', role: 'note', 'aria-label': t('suggestion.confirmPrimary') }, t('suggestion.confirmPrimary'))
2599
3955
 
3956
+ const stageLabel = ghost !== null && (ghost.mode === 'suggest' || ghost.mode === 'optimize')
3957
+ ? workflowSelection?.label
3958
+ : undefined
3959
+ const workflowButton = ghost === null || !sessionId || typeof onWorkflows !== 'function' ? null : h('button', {
3960
+ type: 'button', className: 'dsh-pt-workflow-trigger', 'data-dsh-pt-workflow': 'true',
3961
+ title: stageLabel || t('workflow.title'), 'aria-label': stageLabel || t('workflow.title'),
3962
+ onPointerDown: (event) => event.preventDefault(),
3963
+ onClick: () => openWorkflow(editorRef.current),
3964
+ }, stageLabel || t('workflow.title'))
3965
+ const trialDraft = workflowOpen && !trialSelectionBlocked && suggestionMode(input) !== null && !hasNonTextComposerContext(input)
3966
+ && !commandTokenForInput(input) ? input.draft : null
3967
+
2600
3968
  const ghostView = ghost === null
2601
3969
  ? null
2602
3970
  : ghostIsPreview
@@ -2629,6 +3997,7 @@ window.__ModuleLoader__.load({
2629
3997
  ),
2630
3998
  ),
2631
3999
  h(PromptTabBadge, { label: t('suggestion.badge') }),
4000
+ workflowButton,
2632
4001
  ),
2633
4002
  ghost.loading
2634
4003
  ? h('div', { className: 'dsh-pt-suggest-preview-body-slot', 'aria-hidden': 'true' })
@@ -2734,6 +4103,7 @@ window.__ModuleLoader__.load({
2734
4103
  ghost.error === null ? ghost.text : suggestionErrorMessage(ghost.error),
2735
4104
  ),
2736
4105
  h(PromptTabBadge, { label: t('suggestion.badge') }),
4106
+ workflowButton,
2737
4107
  ghost.loading
2738
4108
  ? null
2739
4109
  : h(
@@ -2752,7 +4122,7 @@ window.__ModuleLoader__.load({
2752
4122
  return h(
2753
4123
  React.Fragment,
2754
4124
  null,
2755
- h('style', { key: 'style' }, SUGGEST_CSS),
4125
+ h('style', { key: 'style' }, SUGGEST_CSS + WORKFLOW_CSS),
2756
4126
  h('div', { ref: anchorRef, className: 'dsh-pt-suggest-anchor' },
2757
4127
  ghostView,
2758
4128
  historyView === null
@@ -2774,6 +4144,11 @@ window.__ModuleLoader__.load({
2774
4144
  tabActionListOpen === false
2775
4145
  ? null
2776
4146
  : h(TabActionList, { t, onClose: closeTabActionList }),
4147
+ workflowOpen && sessionId ? h(WorkflowDialog, {
4148
+ key: sessionId, t, sessionId, catalog, selection: workflowSelection,
4149
+ initialError: catalogError, draft: trialDraft, context: conversationContext,
4150
+ onClose: closeWorkflow, onChoose: chooseWorkflowStage, onCatalog: applyCatalog, onWorkflows, onSuggest,
4151
+ }) : null,
2777
4152
  )
2778
4153
  }
2779
4154
 
@@ -2843,11 +4218,87 @@ window.__ModuleLoader__.load({
2843
4218
 
2844
4219
  explainCommandBridge = { request: requestExplanation }
2845
4220
 
4221
+ /** Prompt-lab bridge: read/save the Config-backed sections and run trials. */
4222
+ const requestPromptLab = (sessionId, op, extra = {}) => {
4223
+ if (typeof sessionId !== 'string' || sessionId === '' || remoteCommands === null) {
4224
+ return Promise.resolve({ ok: false, code: 'unavailable' })
4225
+ }
4226
+ const payload = { v: 1, op }
4227
+ if (op === 'apply' && extra !== null && extra !== undefined && extra.sections) {
4228
+ payload.sections = extra.sections
4229
+ }
4230
+ const line = `/${PROMPT_LAB_COMMAND} ${encodePayload(payload)}`
4231
+ return remoteCommands
4232
+ .execute(sessionId, line, [])
4233
+ .then((result) => {
4234
+ if (result === undefined || result === null || result.ok !== true) {
4235
+ return { ok: false, code: 'unavailable' }
4236
+ }
4237
+ const execution = result.value
4238
+ const commandResult = execution && execution.result
4239
+ if (commandResult === undefined || commandResult === null) return { ok: false, code: 'unavailable' }
4240
+ if (commandResult.kind !== 'success') {
4241
+ const message = typeof commandResult.text === 'string' ? commandResult.text.trim() : ''
4242
+ const match = /^lab:([a-z-]+)(?::([a-z0-9-]+))?$/u.exec(message)
4243
+ return {
4244
+ ok: false,
4245
+ code: match === null ? 'failed' : match[1],
4246
+ section: match === null || match[2] === undefined ? '' : match[2],
4247
+ }
4248
+ }
4249
+ let data = null
4250
+ try {
4251
+ data = JSON.parse(commandResult.text)
4252
+ } catch (_error) {
4253
+ data = null
4254
+ }
4255
+ return { ok: true, data }
4256
+ })
4257
+ .catch((error) => {
4258
+ console.error('prompttab: prompt lab request failed', error)
4259
+ return { ok: false, code: 'failed' }
4260
+ })
4261
+ }
4262
+ if (explainCommandBridge.request === requestExplanation) promptLabBridge = { request: requestPromptLab }
4263
+
4264
+ const workflowListeners = new Set()
4265
+ const workflowSelections = new Map()
4266
+ const workflowControls = {
4267
+ selections: workflowSelections,
4268
+ openers: new Map(),
4269
+ subscribe(listener) {
4270
+ workflowListeners.add(listener)
4271
+ return () => workflowListeners.delete(listener)
4272
+ },
4273
+ setSelection(sessionId, selection) {
4274
+ if (selection === undefined) workflowSelections.delete(sessionId)
4275
+ else workflowSelections.set(sessionId, selection)
4276
+ for (const listener of workflowListeners) listener()
4277
+ },
4278
+ }
4279
+ const requestWorkflows = async (sessionId, op, extra = {}) => {
4280
+ if (!sessionId || remoteCommands === null) return { ok: false, code: 'unavailable' }
4281
+ try {
4282
+ const result = await remoteCommands.execute(sessionId, `/${WORKFLOW_COMMAND} ${encodePayload({ v: 1, op, ...extra })}`, [])
4283
+ const command = result?.value?.result
4284
+ if (result?.ok !== true || !command) return { ok: false, code: 'unavailable' }
4285
+ if (command.kind !== 'success') return { ok: false, code: /^workflow:([a-z-]+)$/u.exec(command.text)?.[1] || 'failed' }
4286
+ const data = JSON.parse(command.text)
4287
+ if (op === 'draft') {
4288
+ if (typeof data?.id !== 'string' || typeof data.name !== 'string' || !Array.isArray(data.stages)) return { ok: false, code: 'invalid-output' }
4289
+ } else if (!Array.isArray(data?.workflows) || typeof data.revision !== 'string') return { ok: false, code: 'failed' }
4290
+ return { ok: true, data }
4291
+ } catch (_error) {
4292
+ return { ok: false, code: 'failed' }
4293
+ }
4294
+ }
4295
+
2846
4296
  const requestSuggestion = (sessionId, mode, draft, extra = {}) => {
2847
4297
  if (typeof sessionId !== 'string' || sessionId === '' || remoteCommands === null) {
2848
4298
  return Promise.resolve({ ok: false, code: 'unavailable' })
2849
4299
  }
2850
4300
  let line = `/${SUGGEST_COMMAND}`
4301
+ const trial = extra?.trialSections === undefined ? {} : { v: 3, trialSections: extra.trialSections }
2851
4302
  const meta = extra !== null && extra !== undefined && typeof extra.meta === 'object' && extra.meta !== null
2852
4303
  ? {
2853
4304
  hasAttachments: extra.meta.hasAttachments === true,
@@ -2856,8 +4307,12 @@ window.__ModuleLoader__.load({
2856
4307
  hasSelection: extra.meta.hasSelection === true,
2857
4308
  }
2858
4309
  : undefined
4310
+ const stageFields = extra.previewStage ? { v: 4, previewStage: extra.previewStage }
4311
+ : extra.workflow ? {
4312
+ v: 4, workflowId: extra.workflow.workflowId, stageId: extra.workflow.stageId, revision: extra.workflow.revision,
4313
+ } : { v: 2, ...trial }
2859
4314
  if (mode === 'suggest') {
2860
- line = `/${SUGGEST_COMMAND} ${encodePayload({ v: 2, mode, meta })}`
4315
+ line = `/${SUGGEST_COMMAND} ${encodePayload({ ...stageFields, mode, meta })}`
2861
4316
  } else if (mode === 'complete') {
2862
4317
  const prefix = typeof extra.prefix === 'string' ? extra.prefix : ''
2863
4318
  const suffix = typeof extra.suffix === 'string' ? extra.suffix : ''
@@ -2866,12 +4321,12 @@ window.__ModuleLoader__.load({
2866
4321
  || prefix + suffix !== draft) {
2867
4322
  return Promise.resolve({ ok: false, code: 'bad-draft' })
2868
4323
  }
2869
- line = `/${SUGGEST_COMMAND} ${encodePayload({ v: 2, mode, draft, prefix, suffix, meta })}`
4324
+ line = `/${SUGGEST_COMMAND} ${encodePayload({ v: 2, mode, draft, prefix, suffix, meta, ...trial })}`
2870
4325
  } else if (mode === 'optimize' || mode === 'enhance' || mode === 'continue' || mode === 'expand' || mode === 'polish' || mode === 'polish-selection') {
2871
4326
  if (typeof draft !== 'string' || draft.trim() === '' || draft.length > SUGGEST_DRAFT_MAX) {
2872
4327
  return Promise.resolve({ ok: false, code: 'bad-draft' })
2873
4328
  }
2874
- line = `/${SUGGEST_COMMAND} ${encodePayload({ v: 2, mode, draft, meta })}`
4329
+ line = `/${SUGGEST_COMMAND} ${encodePayload({ ...stageFields, mode, draft, meta })}`
2875
4330
  }
2876
4331
  return remoteCommands
2877
4332
  .execute(sessionId, line, [])
@@ -2916,6 +4371,9 @@ window.__ModuleLoader__.load({
2916
4371
  if (explainCommandBridge.request === requestExplanation) {
2917
4372
  explainCommandBridge = { request: null }
2918
4373
  }
4374
+ if (promptLabBridge.request === requestPromptLab) {
4375
+ promptLabBridge = { request: null }
4376
+ }
2919
4377
  }
2920
4378
  })
2921
4379
  } catch (error) {
@@ -2947,6 +4405,8 @@ window.__ModuleLoader__.load({
2947
4405
  locale: NS,
2948
4406
  inject: () => ({
2949
4407
  onSuggest: requestSuggestion,
4408
+ onWorkflows: requestWorkflows,
4409
+ workflowControls,
2950
4410
  }),
2951
4411
  },
2952
4412
  PromptSuggestionOverlay,
@@ -2955,6 +4415,23 @@ window.__ModuleLoader__.load({
2955
4415
  'prompttab: inline prompt suggestion',
2956
4416
  )
2957
4417
 
4418
+ ctx.effect(
4419
+ () =>
4420
+ ctx.slots.inject('conversation.input.dock', () =>
4421
+ ctx.slots.register(
4422
+ {
4423
+ name: 'conversation.input.dock',
4424
+ id: 'prompttab-workflow-stage',
4425
+ order: 20,
4426
+ locale: NS,
4427
+ inject: () => ({ workflowControls }),
4428
+ },
4429
+ WorkflowStageDock,
4430
+ ),
4431
+ ),
4432
+ 'prompttab: selected workflow stage',
4433
+ )
4434
+
2958
4435
  ctx.effect(
2959
4436
  () =>
2960
4437
  ctx.slots.inject('conversation.chat.text-interaction', () =>
@@ -2987,6 +4464,23 @@ window.__ModuleLoader__.load({
2987
4464
  'prompttab: explanation page',
2988
4465
  )
2989
4466
 
4467
+ ctx.effect(
4468
+ () =>
4469
+ ctx.slots.inject('shell.overlay', () =>
4470
+ ctx.slots.register(
4471
+ {
4472
+ name: 'shell.overlay',
4473
+ id: 'prompttab-lab',
4474
+ order: 39,
4475
+ locale: NS,
4476
+ inject: () => ({ t, onSuggest: requestSuggestion }),
4477
+ },
4478
+ PromptLabPage,
4479
+ ),
4480
+ ),
4481
+ 'prompttab: development prompt lab page',
4482
+ )
4483
+
2990
4484
  ctx.effect(
2991
4485
  () =>
2992
4486
  ctx.slots.inject('shell.overlay', () =>
@@ -3034,7 +4528,22 @@ window.__ModuleLoader__.load({
3034
4528
  'prompttab: hide internal explanation command',
3035
4529
  )
3036
4530
 
3037
- const hideLegacyCommand = (name) => ctx.effect(
4531
+ ctx.effect(
4532
+ () =>
4533
+ ctx.slots.inject('conversation.chat.commandview', () =>
4534
+ ctx.slots.register(
4535
+ {
4536
+ name: 'conversation.chat.commandview',
4537
+ key: PROMPT_LAB_COMMAND,
4538
+ locale: NS,
4539
+ },
4540
+ SuggestionCommandView,
4541
+ ),
4542
+ ),
4543
+ 'prompttab: hide internal prompt lab command',
4544
+ )
4545
+
4546
+ const hideCommand = (name) => ctx.effect(
3038
4547
  () =>
3039
4548
  ctx.slots.inject('conversation.chat.commandview', () =>
3040
4549
  ctx.slots.register(
@@ -3046,10 +4555,11 @@ window.__ModuleLoader__.load({
3046
4555
  SuggestionCommandView,
3047
4556
  ),
3048
4557
  ),
3049
- `prompttab: hide legacy command ${name}`,
4558
+ `prompttab: hide command ${name}`,
3050
4559
  )
3051
- for (const name of LEGACY_LIBRARY_COMMANDS) hideLegacyCommand(name)
3052
- for (const name of LEGACY_INTERACTION_COMMANDS) hideLegacyCommand(name)
4560
+ hideCommand(WORKFLOW_COMMAND)
4561
+ for (const name of LEGACY_LIBRARY_COMMANDS) hideCommand(name)
4562
+ for (const name of LEGACY_INTERACTION_COMMANDS) hideCommand(name)
3053
4563
  }
3054
4564
 
3055
4565
  const pluginExports = { inject: ['slots', 'locale', 'uiConversation'], apply }
@@ -3092,6 +4602,17 @@ window.__ModuleLoader__.load({
3092
4602
  tabActionListEntries,
3093
4603
  filterTabActionList,
3094
4604
  TabActionList,
4605
+ isPromptLabShortcut,
4606
+ openPromptLab,
4607
+ closePromptLab,
4608
+ getPromptLabSnapshot,
4609
+ PromptLabPage,
4610
+ labTrialRequest,
4611
+ labTotalChars,
4612
+ labChangedSections,
4613
+ PROMPT_LAB_COMMAND,
4614
+ LAB_SECTION_NAMES,
4615
+ LAB_ACTION_NAMES,
3095
4616
  PromptSuggestionOverlay,
3096
4617
  PromptTextMenu,
3097
4618
  PromptExplainOverlay,