@restregular/dsh-powerup 0.17.0 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -454,8 +454,9 @@ only scopes that actually contain requirements are listed. Each record can be
454
454
  enabled/disabled, edited and deleted. When generating progress you **check the
455
455
  requirements you want** — checked ones fill an editable text box that you may
456
456
  freely modify, and generation/refresh uses the full box text verbatim. The panel
457
- also has a **New requirement** entry with a modal pinned to the session's
458
- workspace (like the prompt picker).
457
+ also has a **New requirement** entry with a modal: pick the workspace (or "all
458
+ workspaces") there, and clicks inside the modal no longer close the progress
459
+ panel.
459
460
  The panel uses **tabs** below the header: **Progress**, **Requirements** and
460
461
  **Raw output** — requirements and the raw AI text are no longer embedded in the
461
462
  progress body. Stage cards (checklist steps, phases, milestones and tree nodes)
@@ -472,9 +473,13 @@ An **icon-only** lightning button in the composer opens a floating DSH-styled
472
473
  chat window. Drag the title bar to move it and the bottom-right corner to
473
474
  resize it (position and size persist). It supports **continuous multi-turn Q&A**.
474
475
  The chat window uses two **tabs** — **Chat** and **History** — instead of
475
- embedding the history over the conversation. Your message appears in the thread
476
- immediately as a pending bubble; the answer replaces the pending state in place
477
- (and failures render there too). Continuous Q&A flattens prior turns into a
476
+ embedding the history over the conversation. History is stored per **conversation**
477
+ (not per message), each with a **title** you can edit inline. A settings toggle
478
+ can ask the model to generate the title from the first message — one tiny,
479
+ token-capped request; otherwise the first question becomes the title. Your
480
+ message appears in the thread immediately as a pending bubble; the answer
481
+ replaces the pending state in place and is **rendered as Markdown** (headings,
482
+ lists, code blocks, inline formatting); failures render there too. Continuous Q&A flattens prior turns into a
478
483
  single user message before each call, so no hand-built assistant message ever
479
484
  reaches the model adapter — this fixes the "LLM_FAILED" error on the second
480
485
  message. "+" starts a new chat. Attach text files with the "+" chip in the
package/client.js CHANGED
@@ -85,7 +85,7 @@
85
85
  const requirementCreateDraft = { workspaceId: null, title: '', text: '', scope: 'current' };
86
86
  /** Fallback bucket when the hero cannot resolve an owning workspace yet. */
87
87
  const UNSCOPED_WORKSPACE = '__unscoped__';
88
- const VERSION = '0.17.0';
88
+ const VERSION = '0.18.0';
89
89
  const MENU_GAP = 8;
90
90
  const MENU_WIDTH = 248;
91
91
  /** Reference scheme understood by the Host's `powerup_step_read` tool. */
@@ -393,8 +393,7 @@
393
393
  'progress.reqHint': '每条要求可设置语言、结构、必须包含的数据、额外展示区要回答的问题等;按工作区隔离,留空工作区则对所有工作区生效。生成进度时可勾选本次要应用哪些要求。',
394
394
  'progress.reqNew': '新建要求',
395
395
  'progress.reqSelect': '本次应用的要求',
396
- 'progress.reqSelectHint': '勾选要求后内容会填入下方输入框,可自由修改;生成/刷新时会使用输入框里的完整要求。',
397
- 'progress.reqEditPlaceholder': '在这里编辑本次生成要使用的要求…',
396
+ 'progress.reqEditPlaceholder': '勾选要求后内容会填入这里,可自由修改;生成/刷新时使用此处完整要求…',
398
397
  'progress.reqTextLabel': '要求内容',
399
398
  'progress.sectionTitle': '生成要求',
400
399
  'progress.reqGlobal': '通用要求(设置页)',
@@ -412,6 +411,8 @@
412
411
  'page.directAskHow': '点底部输入区的闪电按钮,输入问题后发送;回答会显示在一个可开关的弹窗里。这个能力不是 Agent,不能调用工具或加载技能。',
413
412
  'page.directAskToggle': '启用轻量问答按钮',
414
413
  'page.directAskToggleHint': '关闭后底部输入区不再显示该按钮。',
414
+ 'page.directAskAutoTitle': '自动生成会话标题',
415
+ 'page.directAskAutoTitleHint': '开启后,新对话会用第一个问题让大模型生成简短标题(仅一条短请求,严格限制 token);关闭则用第一句问题作标题。标题都可随时手动修改。',
415
416
  'directAsk.label': '直接问答',
416
417
  'directAsk.hint': '不启动 Agent,直接问模型(无工具/技能)',
417
418
  'directAsk.title': '轻量问答',
@@ -432,6 +433,8 @@
432
433
  'directAsk.newChat': '新对话',
433
434
  'directAsk.tabChat': '问答',
434
435
  'directAsk.noAnswer': '(无回答)',
436
+ 'directAsk.editTitle': '修改标题',
437
+ 'directAsk.untitled': '未命名对话',
435
438
  'directAsk.history': '历史记录',
436
439
  'directAsk.historyEmpty': '还没有历史对话',
437
440
  'directAsk.clearHistory': '清空历史',
@@ -789,8 +792,7 @@
789
792
  'progress.reqHint': 'Each requirement sets language, structure, required data, questions for the display area, etc. Scoped per workspace; a blank workspace applies everywhere. Choose which ones to apply when generating progress.',
790
793
  'progress.reqNew': 'New requirement',
791
794
  'progress.reqSelect': 'Requirements for this run',
792
- 'progress.reqSelectHint': 'Checked requirements fill the box below; edit freely. Generation uses the full text in the box.',
793
- 'progress.reqEditPlaceholder': 'Edit the requirements to use for this generation…',
795
+ 'progress.reqEditPlaceholder': 'Checked requirements fill this box; edit freely. Generation uses the full text here…',
794
796
  'progress.reqTextLabel': 'Requirement text',
795
797
  'progress.sectionTitle': 'Generation requirements',
796
798
  'progress.reqGlobal': 'Global requirements (settings)',
@@ -808,6 +810,8 @@
808
810
  'page.directAskHow': 'Click the lightning button in the composer, type a question and send; the answer appears in a dialog you can show or hide. This is not an Agent — it cannot call tools or load skills.',
809
811
  'page.directAskToggle': 'Enable direct-ask button',
810
812
  'page.directAskToggleHint': 'When off, the composer button is hidden.',
813
+ 'page.directAskAutoTitle': 'Generate conversation titles',
814
+ 'page.directAskAutoTitleHint': 'When on, a new chat asks the model for a short title from the first message (one small, token-capped request). When off, the first question is used. Titles are always editable.',
811
815
  'directAsk.label': 'Direct ask',
812
816
  'directAsk.hint': 'Ask the model without an Agent (no tools or skills)',
813
817
  'directAsk.title': 'Direct ask',
@@ -828,6 +832,8 @@
828
832
  'directAsk.newChat': 'New chat',
829
833
  'directAsk.tabChat': 'Chat',
830
834
  'directAsk.noAnswer': '(no answer)',
835
+ 'directAsk.editTitle': 'Edit title',
836
+ 'directAsk.untitled': 'Untitled chat',
831
837
  'directAsk.history': 'History',
832
838
  'directAsk.historyEmpty': 'No saved conversations yet',
833
839
  'directAsk.clearHistory': 'Clear history',
@@ -931,6 +937,7 @@
931
937
  workspacePrompts: true,
932
938
  taskProgress: true,
933
939
  directAsk: true,
940
+ directAskAutoTitle: false,
934
941
  oneClickEnable: true,
935
942
  oneClickRestart: true,
936
943
  };
@@ -955,6 +962,7 @@
955
962
  workspacePrompts: parsed.workspacePrompts !== false,
956
963
  taskProgress: parsed.taskProgress !== false,
957
964
  directAsk: parsed.directAsk !== false,
965
+ directAskAutoTitle: parsed.directAskAutoTitle === true,
958
966
  oneClickEnable: parsed.oneClickEnable !== false,
959
967
  oneClickRestart: parsed.oneClickRestart !== false,
960
968
  };
@@ -4667,7 +4675,11 @@ html[data-platform="darwin"] .dsh-powerup-scrolltop:hover{background:var(--dsw-s
4667
4675
  .dsh-powerup-directask-btn:hover,.dsh-powerup-directask-btn.on{border-color:var(--dsw-alias-brand-primary);color:var(--dsw-alias-brand-primary)}
4668
4676
  .dsh-powerup-directask-window{position:fixed;z-index:1600;box-sizing:border-box;display:flex;flex-direction:column;min-width:360px;min-height:280px;border-radius:var(--dsw-radius-panel,14px);background:var(--dsw-alias-bg-layer-2);box-shadow:var(--dsw-elevation-prominent);--dsw-elevation-stroke-color:var(--dsw-alias-border-l2);color:var(--dsw-alias-label-primary);font-size:13px;line-height:1.6;overflow:hidden;animation:dsh-powerup-progress-in .15s ease-out}
4669
4677
  .dsh-powerup-directask-titlebar{display:flex;align-items:center;gap:8px;flex:none;padding:10px 12px;border-bottom:.5px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-bg-layer-3);cursor:move;user-select:none}
4670
- .dsh-powerup-directask-title{font-size:13px;font-weight:600;white-space:nowrap}
4678
+ .dsh-powerup-directask-title{font-size:13px;font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:240px}
4679
+ .dsh-powerup-directask-title-input{flex:1 1 auto;min-width:0;height:24px;padding:0 8px;border:.5px solid var(--dsw-alias-brand-primary);border-radius:6px;background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-label-primary);font:inherit;font-size:13px;outline:0}
4680
+ .dsh-powerup-directask-history-list button{display:flex;flex-direction:column;align-items:flex-start;gap:2px;width:100%;padding:6px 8px;border:0;border-radius:6px;background:transparent;color:var(--dsw-alias-label-secondary);font:inherit;font-size:11.5px;text-align:left;cursor:pointer}
4681
+ .dsh-powerup-directask-history-title{color:var(--dsw-alias-label-primary);font-size:12px;font-weight:500;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:100%}
4682
+ .dsh-powerup-directask-history-meta{color:var(--dsw-alias-label-tertiary);font-size:10px}
4671
4683
  .dsh-powerup-directask-subtitle{flex:1 1 auto;min-width:0;color:var(--dsw-alias-label-tertiary);font-size:10.5px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
4672
4684
  .dsh-powerup-directask-titlebtn,.dsh-powerup-directask-close{flex:none;display:inline-flex;align-items:center;justify-content:center;width:24px;height:24px;padding:0;border:0;border-radius:var(--dsw-radius-sm,6px);background:transparent;color:var(--dsw-alias-label-secondary);font:inherit;font-size:15px;line-height:1;cursor:pointer}
4673
4685
  .dsh-powerup-directask-titlebtn:hover,.dsh-powerup-directask-titlebtn.on,.dsh-powerup-directask-close:hover{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-primary)}
@@ -4679,7 +4691,6 @@ html[data-platform="darwin"] .dsh-powerup-scrolltop:hover{background:var(--dsw-s
4679
4691
  .dsh-powerup-directask-history{flex:none;max-height:180px;overflow-y:auto;padding:10px 14px;border-bottom:.5px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-bg-layer-1)}
4680
4692
  .dsh-powerup-directask-history-head{display:flex;align-items:center;justify-content:space-between;margin-bottom:6px;font-size:11.5px}
4681
4693
  .dsh-powerup-directask-history-list{margin:0;padding:0;list-style:none}
4682
- .dsh-powerup-directask-history-list button{width:100%;padding:5px 8px;border:0;border-radius:6px;background:transparent;color:var(--dsw-alias-label-secondary);font:inherit;font-size:11px;text-align:left;cursor:pointer;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
4683
4694
  .dsh-powerup-directask-history-list button:hover{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-primary)}
4684
4695
  .dsh-powerup-directask-thread{flex:1 1 auto;min-height:0;overflow-y:auto;padding:14px 16px;display:flex;flex-direction:column;gap:12px;--dsh-scrollbar-thumb:var(--dsw-alias-scrollbar-bg-l2)}
4685
4696
  .dsh-powerup-directask-welcome{margin:auto;color:var(--dsw-alias-label-tertiary);font-size:12px;text-align:center}
@@ -4692,6 +4703,16 @@ html[data-platform="darwin"] .dsh-powerup-scrolltop:hover{background:var(--dsw-s
4692
4703
  .dsh-powerup-directask-msg.assistant .dsh-powerup-directask-msg-body{border-bottom-left-radius:3px}
4693
4704
  .dsh-powerup-directask-msg.assistant.is-pending .dsh-powerup-directask-msg-body{color:var(--dsw-alias-label-tertiary);font-style:italic}
4694
4705
  .dsh-powerup-directask-msg.assistant.is-error .dsh-powerup-directask-msg-body{border:1px solid color-mix(in srgb,var(--dsw-alias-state-error-primary) 40%,transparent);color:var(--dsw-alias-state-error-primary)}
4706
+ .dsh-powerup-md-p{margin:0 0 8px}
4707
+ .dsh-powerup-md-p:last-child{margin-bottom:0}
4708
+ .dsh-powerup-md-heading{margin:10px 0 6px;font-size:13px;line-height:1.5}
4709
+ .dsh-powerup-md-heading:first-child{margin-top:0}
4710
+ .dsh-powerup-md-ul,.dsh-powerup-md-ol{margin:6px 0;padding-left:22px}
4711
+ .dsh-powerup-md-ul li,.dsh-powerup-md-ol li{margin:2px 0}
4712
+ .dsh-powerup-md-code{margin:6px 0;padding:8px 10px;border-radius:8px;background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-primary);font-family:var(--dsw-font-family-code,ui-monospace,SFMono-Regular,Consolas,monospace);font-size:11.5px;line-height:1.6;overflow-x:auto;white-space:pre-wrap;overflow-wrap:anywhere}
4713
+ .dsh-powerup-md-inline-code{padding:1px 5px;border-radius:4px;background:var(--dsw-alias-bg-layer-3);font-family:var(--dsw-font-family-code,ui-monospace,SFMono-Regular,Consolas,monospace);font-size:11.5px}
4714
+ .dsh-powerup-md-quote{margin:6px 0;padding:4px 10px;border-left:2px solid var(--dsw-alias-border-l3);color:var(--dsw-alias-label-secondary)}
4715
+ .dsh-powerup-md-hr{margin:8px 0;border:0;border-top:.5px solid var(--dsw-alias-border-l2)}
4695
4716
  .dsh-powerup-directask-ctx{display:flex;flex-wrap:wrap;gap:4px;align-self:flex-end}
4696
4717
  .dsh-powerup-directask-ctx span{padding:2px 7px;border-radius:999px;background:var(--dsw-alias-bg-layer-3);color:var(--dsw-alias-label-tertiary);font-size:10px}
4697
4718
  .dsh-powerup-directask-files{display:flex;flex-wrap:wrap;gap:6px;padding:0 14px 6px}
@@ -9210,6 +9231,139 @@ html[data-platform="darwin"] .dsh-powerup-scrolltop:hover{background:var(--dsw-s
9210
9231
  return behavior;
9211
9232
  }
9212
9233
 
9234
+ /**
9235
+ * Minimal, self-contained Markdown renderer for short model answers.
9236
+ * The host exposes no markdown service, so this handles the common subset:
9237
+ * fenced code, headings, lists, blockquotes, rules, inline code/bold/italic
9238
+ * and plain paragraphs (line breaks preserved). Returns React nodes.
9239
+ */
9240
+ function renderInlineMarkdown(text, keyPrefix) {
9241
+ if (typeof text !== 'string' || text === '') return null;
9242
+ // Split out inline code first so its contents are never formatted.
9243
+ const segments = [];
9244
+ const codeRe = /`([^`]+)`/gu;
9245
+ let last = 0;
9246
+ let match;
9247
+ let i = 0;
9248
+ while ((match = codeRe.exec(text)) !== null) {
9249
+ if (match.index > last) segments.push({ kind: 'text', value: text.slice(last, match.index) });
9250
+ segments.push({ kind: 'code', value: match[1] });
9251
+ last = match.index + match[0].length;
9252
+ }
9253
+ if (last < text.length) segments.push({ kind: 'text', value: text.slice(last) });
9254
+ const nodes = [];
9255
+ for (const seg of segments) {
9256
+ if (seg.kind === 'code') {
9257
+ nodes.push(h('code', { key: `${keyPrefix}-c${i++}`, className: 'dsh-powerup-md-inline-code' }, seg.value));
9258
+ continue;
9259
+ }
9260
+ // Bold/italic within a plain segment.
9261
+ const parts = [];
9262
+ const re = /(\*\*[^*]+\*\*|\*[^*]+\*|__[^_]+__|_[^_]+_)/gu;
9263
+ let cursor = 0;
9264
+ let m;
9265
+ while ((m = re.exec(seg.value)) !== null) {
9266
+ if (m.index > cursor) parts.push(seg.value.slice(cursor, m.index));
9267
+ const token = m[0];
9268
+ const strong = (token.startsWith('**') && token.endsWith('**')) || (token.startsWith('__') && token.endsWith('__'));
9269
+ const inner = strong ? token.slice(2, -2) : token.slice(1, -1);
9270
+ parts.push(strong
9271
+ ? h('strong', { key: `${keyPrefix}-b${i++}` }, inner)
9272
+ : h('em', { key: `${keyPrefix}-i${i++}` }, inner));
9273
+ cursor = m.index + token.length;
9274
+ }
9275
+ if (cursor < seg.value.length) parts.push(seg.value.slice(cursor));
9276
+ nodes.push(...parts);
9277
+ }
9278
+ return nodes.length === 1 && typeof nodes[0] === 'string' ? nodes[0] : nodes;
9279
+ }
9280
+
9281
+ function renderMarkdown(text) {
9282
+ if (typeof text !== 'string' || text.trim() === '') return null;
9283
+ const lines = text.replace(/\r\n?/gu, '\n').split('\n');
9284
+ const out = [];
9285
+ let i = 0;
9286
+ let key = 0;
9287
+ const k = () => `md-${key++}`;
9288
+ while (i < lines.length) {
9289
+ const line = lines[i];
9290
+ // Fenced code block.
9291
+ if (/^\s*```/u.test(line)) {
9292
+ const lang = line.trim().slice(3).trim();
9293
+ const code = [];
9294
+ i += 1;
9295
+ while (i < lines.length && !/^\s*```/u.test(lines[i])) {
9296
+ code.push(lines[i]);
9297
+ i += 1;
9298
+ }
9299
+ if (i < lines.length) i += 1; // closing fence
9300
+ out.push(h('pre', { key: k(), className: 'dsh-powerup-md-code' + (lang ? ` lang-${lang}` : '') },
9301
+ h('code', null, code.join('\n'))));
9302
+ continue;
9303
+ }
9304
+ // Horizontal rule.
9305
+ if (/^\s*(---+|\*\*\*+|___+)\s*$/u.test(line)) {
9306
+ out.push(h('hr', { key: k(), className: 'dsh-powerup-md-hr' }));
9307
+ i += 1;
9308
+ continue;
9309
+ }
9310
+ // Heading.
9311
+ const heading = /^\s*(#{1,6})\s+(.*)$/u.exec(line);
9312
+ if (heading !== null) {
9313
+ const level = Math.min(6, heading[1].length);
9314
+ const Tag = `h${level + 2}`;
9315
+ out.push(h(Tag, { key: k(), className: 'dsh-powerup-md-heading' }, renderInlineMarkdown(heading[2], k())));
9316
+ i += 1;
9317
+ continue;
9318
+ }
9319
+ // Blockquote (consecutive > lines).
9320
+ if (/^\s*>\s?/u.test(line)) {
9321
+ const quote = [];
9322
+ while (i < lines.length && /^\s*>\s?/u.test(lines[i])) {
9323
+ quote.push(lines[i].replace(/^\s*>\s?/u, ''));
9324
+ i += 1;
9325
+ }
9326
+ out.push(h('blockquote', { key: k(), className: 'dsh-powerup-md-quote' }, quote.map((q, j) => h('div', { key: j }, renderInlineMarkdown(q, k())))));
9327
+ continue;
9328
+ }
9329
+ // Unordered / ordered list.
9330
+ const ul = /^\s*[-*+]\s+(.*)$/u.exec(line);
9331
+ const ol = /^\s*\d+[.)]\s+(.*)$/u.exec(line);
9332
+ if (ul !== null || ol !== null) {
9333
+ const ordered = ol !== null;
9334
+ const items = [];
9335
+ const itemRe = ordered ? /^\s*\d+[.)]\s+(.*)$/u : /^\s*[-*+]\s+(.*)$/u;
9336
+ while (i < lines.length) {
9337
+ const m = itemRe.exec(lines[i]);
9338
+ if (m === null) break;
9339
+ items.push(h('li', { key: k() }, renderInlineMarkdown(m[1], k())));
9340
+ i += 1;
9341
+ }
9342
+ out.push(h(ordered ? 'ol' : 'ul', {
9343
+ key: k(), className: ordered ? 'dsh-powerup-md-ol' : 'dsh-powerup-md-ul',
9344
+ }, items));
9345
+ continue;
9346
+ }
9347
+ // Blank line: skip.
9348
+ if (line.trim() === '') { i += 1; continue; }
9349
+ // Paragraph: gather consecutive plain lines until a block starter.
9350
+ const para = [];
9351
+ while (i < lines.length && lines[i].trim() !== ''
9352
+ && !/^\s*```/u.test(lines[i]) && !/^\s*>/u.test(lines[i])
9353
+ && !/^\s*(#{1,6})\s/u.test(lines[i])
9354
+ && !/^\s*[-*+]\s/u.test(lines[i]) && !/^\s*\d+[.)]\s/u.test(lines[i])
9355
+ && !/^\s*(---+|\*\*\*+|___+)\s*$/u.test(lines[i])) {
9356
+ para.push(lines[i]);
9357
+ i += 1;
9358
+ }
9359
+ if (para.length > 0) {
9360
+ out.push(h('p', { key: k(), className: 'dsh-powerup-md-p' },
9361
+ para.map((p, j) => h(React.Fragment, { key: j }, renderInlineMarkdown(p, k()), j < para.length - 1 ? h('br') : null))));
9362
+ }
9363
+ }
9364
+ return out.length === 1 ? out[0] : h('div', { className: 'dsh-powerup-md' }, out);
9365
+ }
9366
+
9213
9367
  /**
9214
9368
  * Lightning-bolt button in the composer (icon only). Opens a floating,
9215
9369
  * draggable + resizable DSH-styled Q&A window that talks straight to the
@@ -9224,13 +9378,28 @@ html[data-platform="darwin"] .dsh-powerup-scrolltop:hover{background:var(--dsw-s
9224
9378
  const [busy, setBusy] = useState(false);
9225
9379
  const [error, setError] = useState('');
9226
9380
  const [copied, setCopied] = useState(false);
9227
- /** Current conversation: [{question, answer, context, at}]. */
9228
- const [turns, setTurns] = useState([]);
9229
- /** Archived conversations, newest first: [{id, at, turns}]. */
9381
+ /** Current conversation: {id, title, turns, at}. */
9382
+ const [conversation, setConversation] = useState(() => ({
9383
+ id: `c-${Date.now()}`,
9384
+ title: '',
9385
+ turns: [],
9386
+ at: Date.now(),
9387
+ }));
9388
+ /** Archived conversations, newest first: [{id, title, at, turns}]. */
9230
9389
  const [history, setHistory] = useState(() => {
9231
- try { return JSON.parse(localStorage.getItem('dsh-powerup:directask:history:v1') || '[]'); }
9232
- catch { return []; }
9390
+ try {
9391
+ const parsed = JSON.parse(localStorage.getItem('dsh-powerup:directask:history:v1') || '[]');
9392
+ return (Array.isArray(parsed) ? parsed : []).map((h) => ({
9393
+ id: h.id ?? `c-${Math.random().toString(36).slice(2)}`,
9394
+ title: typeof h.title === 'string' ? h.title : String(h.turns?.[0]?.question ?? '').slice(0, 40),
9395
+ at: h.at ?? Date.now(),
9396
+ turns: Array.isArray(h.turns) ? h.turns : [],
9397
+ }));
9398
+ } catch { return []; }
9233
9399
  });
9400
+ const [editingTitle, setEditingTitle] = useState(false);
9401
+ const [titleDraft, setTitleDraft] = useState('');
9402
+ const turns = conversation.turns;
9234
9403
  const [activeTab, setActiveTab] = useState('chat');
9235
9404
  const [pos, setPos] = useState(() => {
9236
9405
  try {
@@ -9259,6 +9428,10 @@ html[data-platform="darwin"] .dsh-powerup-scrolltop:hover{background:var(--dsw-s
9259
9428
  setHistory(next);
9260
9429
  try { localStorage.setItem('dsh-powerup:directask:history:v1', JSON.stringify(next.slice(0, 30))); } catch { /* ignore */ }
9261
9430
  }, []);
9431
+ /** Update the current conversation's turns immutably. */
9432
+ const updateTurns = useCallback((fn) => {
9433
+ setConversation((cur) => ({ ...cur, turns: typeof fn === 'function' ? fn(cur.turns) : fn }));
9434
+ }, []);
9262
9435
 
9263
9436
  useEffect(() => {
9264
9437
  if (!open) return undefined;
@@ -9327,8 +9500,24 @@ html[data-platform="darwin"] .dsh-powerup-scrolltop:hover{background:var(--dsw-s
9327
9500
  setQuestion('');
9328
9501
  setFiles([]);
9329
9502
  setCopied(false);
9330
- setTurns((cur) => [...cur, pending]);
9503
+ updateTurns((cur) => [...cur, pending]);
9331
9504
  setActiveTab('chat');
9505
+ // Title: first message wins if empty. Auto-generate via LLM only when
9506
+ // the user opted in — one tiny, token-capped request.
9507
+ if (!conversation.title) {
9508
+ const fallback = q.slice(0, 40);
9509
+ setConversation((cur) => ({ ...cur, title: fallback }));
9510
+ if (settings.directAskAutoTitle) {
9511
+ void fetch(ASK_TITLE_API, {
9512
+ method: 'POST', headers: { 'content-type': 'application/json' },
9513
+ body: JSON.stringify({ firstMessage: q }),
9514
+ }).then((r) => r.json()).then((body) => {
9515
+ if (body?.ok && typeof body.title === 'string' && body.title.trim() !== '') {
9516
+ setConversation((cur) => ({ ...cur, title: body.title.trim().slice(0, 60) }));
9517
+ }
9518
+ }).catch(() => { /* keep the fallback title */ });
9519
+ }
9520
+ }
9332
9521
  try {
9333
9522
  const response = await fetch(DIRECT_ASK_API, {
9334
9523
  method: 'POST',
@@ -9342,32 +9531,60 @@ html[data-platform="darwin"] .dsh-powerup-scrolltop:hover{background:var(--dsw-s
9342
9531
  });
9343
9532
  const body = await response.json();
9344
9533
  if (!body?.ok) throw new Error(body?.error ?? `HTTP ${response.status}`);
9345
- setTurns((cur) => cur.map((t) => (t.id === pendingId
9534
+ updateTurns((cur) => cur.map((t) => (t.id === pendingId
9346
9535
  ? { ...t, answer: typeof body.answer === 'string' ? body.answer : '', pending: false }
9347
9536
  : t)));
9348
9537
  } catch (err) {
9349
9538
  // Render the failure in the thread like a normal assistant reply.
9350
- setTurns((cur) => cur.map((t) => (t.id === pendingId
9539
+ updateTurns((cur) => cur.map((t) => (t.id === pendingId
9351
9540
  ? { ...t, answer: String(err?.message ?? err), pending: false, error: true }
9352
9541
  : t)));
9353
9542
  } finally {
9354
9543
  setBusy(false);
9355
9544
  }
9356
- }, [question, files, turns, t]);
9545
+ }, [question, files, turns, t, conversation.title, settings.directAskAutoTitle, updateTurns]);
9546
+
9547
+ const archiveCurrent = useCallback(() => {
9548
+ if (conversation.turns.length === 0) return history;
9549
+ const record = {
9550
+ id: conversation.id,
9551
+ title: conversation.title || String(conversation.turns[0]?.question ?? '').slice(0, 40),
9552
+ at: conversation.at,
9553
+ turns: conversation.turns,
9554
+ };
9555
+ return [record, ...history.filter((h) => h.id !== record.id)];
9556
+ }, [conversation, history]);
9357
9557
 
9358
9558
  const newChat = useCallback(() => {
9359
- if (turns.length > 0) persistHistory([{ id: String(Date.now()), at: Date.now(), turns }, ...history]);
9360
- setTurns([]);
9559
+ persistHistory(archiveCurrent());
9560
+ setConversation({ id: `c-${Date.now()}`, title: '', turns: [], at: Date.now() });
9561
+ setEditingTitle(false);
9361
9562
  setError('');
9362
9563
  setActiveTab('chat');
9363
- }, [turns, history, persistHistory]);
9564
+ }, [archiveCurrent, persistHistory]);
9364
9565
 
9365
9566
  const openArchived = useCallback((entry) => {
9366
- if (turns.length > 0) persistHistory([{ id: String(Date.now()), at: Date.now(), turns }, ...history.filter((h) => h.id !== entry.id)]);
9367
- else persistHistory(history.filter((h) => h.id !== entry.id));
9368
- setTurns(Array.isArray(entry.turns) ? entry.turns : []);
9567
+ persistHistory(archiveCurrent().filter((h) => h.id !== entry.id));
9568
+ setConversation({
9569
+ id: entry.id,
9570
+ title: entry.title || String(entry.turns?.[0]?.question ?? '').slice(0, 40),
9571
+ turns: Array.isArray(entry.turns) ? entry.turns : [],
9572
+ at: entry.at ?? Date.now(),
9573
+ });
9574
+ setEditingTitle(false);
9369
9575
  setActiveTab('chat');
9370
- }, [turns, history, persistHistory]);
9576
+ }, [archiveCurrent, persistHistory]);
9577
+
9578
+ const saveTitle = useCallback(() => {
9579
+ const next = titleDraft.trim().slice(0, 60);
9580
+ if (next !== '') {
9581
+ setConversation((cur) => ({ ...cur, title: next }));
9582
+ // Also update the archived copy if this conversation is in history.
9583
+ setHistory((cur) => cur.map((h) => (h.id === conversation.id ? { ...h, title: next } : h)));
9584
+ try { localStorage.setItem('dsh-powerup:directask:history:v1', JSON.stringify(history.map((h) => (h.id === conversation.id ? { ...h, title: next } : h)).slice(0, 30))); } catch { /* ignore */ }
9585
+ }
9586
+ setEditingTitle(false);
9587
+ }, [titleDraft, conversation.id, history]);
9371
9588
 
9372
9589
  const clearHistory = useCallback(() => {
9373
9590
  if (typeof window !== 'undefined' && typeof window.confirm === 'function'
@@ -9417,7 +9634,27 @@ html[data-platform="darwin"] .dsh-powerup-scrolltop:hover{background:var(--dsw-s
9417
9634
  dragRef.current = { kind: 'move', x: event.clientX, y: event.clientY, px: pos.x, py: pos.y };
9418
9635
  },
9419
9636
  },
9420
- h('span', { className: 'dsh-powerup-directask-title' }, t('directAsk.title')),
9637
+ editingTitle
9638
+ ? h('input', {
9639
+ className: 'dsh-powerup-directask-title-input',
9640
+ value: titleDraft,
9641
+ autoFocus: true,
9642
+ maxLength: 60,
9643
+ onChange: (event) => setTitleDraft(event.target.value),
9644
+ onKeyDown: (event) => {
9645
+ if (event.key === 'Enter') { event.preventDefault(); saveTitle(); }
9646
+ else if (event.key === 'Escape') { event.preventDefault(); setEditingTitle(false); }
9647
+ },
9648
+ onBlur: saveTitle,
9649
+ onPointerDown: (event) => event.stopPropagation(),
9650
+ })
9651
+ : h('span', { className: 'dsh-powerup-directask-title', title: conversation.title || t('directAsk.title') },
9652
+ conversation.title || t('directAsk.title')),
9653
+ h('button', {
9654
+ type: 'button', className: 'dsh-powerup-directask-titlebtn',
9655
+ title: t('directAsk.editTitle'),
9656
+ onClick: () => { setTitleDraft(conversation.title || ''); setEditingTitle(true); },
9657
+ }, '✎'),
9421
9658
  h('span', { className: 'dsh-powerup-directask-subtitle' }, t('directAsk.subtitle')),
9422
9659
  h('button', {
9423
9660
  type: 'button', className: 'dsh-powerup-directask-titlebtn',
@@ -9451,8 +9688,10 @@ html[data-platform="darwin"] .dsh-powerup-scrolltop:hover{background:var(--dsw-s
9451
9688
  : h('ul', { className: 'dsh-powerup-directask-history-list' },
9452
9689
  history.map((entry) => h('li', { key: entry.id },
9453
9690
  h('button', { type: 'button', onClick: () => openArchived(entry) },
9454
- new Date(entry.at ?? Date.now()).toLocaleString(),
9455
- ' · ', String(entry.turns?.[0]?.question ?? '').slice(0, 40),
9691
+ h('span', { className: 'dsh-powerup-directask-history-title' }, entry.title || t('directAsk.untitled')),
9692
+ h('span', { className: 'dsh-powerup-directask-history-meta' },
9693
+ new Date(entry.at ?? Date.now()).toLocaleString(),
9694
+ ),
9456
9695
  ),
9457
9696
  )),
9458
9697
  ),
@@ -9472,7 +9711,8 @@ html[data-platform="darwin"] .dsh-powerup-scrolltop:hover{background:var(--dsw-s
9472
9711
  + (turn.pending ? ' is-pending' : '') + (turn.error ? ' is-error' : ''),
9473
9712
  },
9474
9713
  h('div', { className: 'dsh-powerup-directask-msg-body' },
9475
- turn.pending ? t('directAsk.sending') : (turn.answer || t('directAsk.noAnswer')),
9714
+ turn.pending ? t('directAsk.sending')
9715
+ : (turn.answer ? renderMarkdown(turn.answer) : t('directAsk.noAnswer')),
9476
9716
  ),
9477
9717
  !turn.pending && turn.answer ? h('button', {
9478
9718
  type: 'button', className: 'dsh-powerup-progress-mini',
@@ -9486,7 +9726,7 @@ html[data-platform="darwin"] .dsh-powerup-scrolltop:hover{background:var(--dsw-s
9486
9726
  h('div', { ref: bottomRef }),
9487
9727
  ),
9488
9728
  error ? h('p', { className: 'dsh-powerup-progress-error' }, error) : null,
9489
- h('div', { className: 'dsh-powerup-directask-composer' },
9729
+ activeTab === 'chat' ? h('div', { className: 'dsh-powerup-directask-composer' },
9490
9730
  files.length > 0 ? h('div', { className: 'dsh-powerup-directask-files' },
9491
9731
  files.map((f, i) => h('span', { key: i, className: 'dsh-powerup-directask-file' },
9492
9732
  f.name,
@@ -9522,7 +9762,7 @@ html[data-platform="darwin"] .dsh-powerup-scrolltop:hover{background:var(--dsw-s
9522
9762
  }, h('svg', { viewBox: '0 0 16 16', width: 16, height: 16, 'aria-hidden': 'true' },
9523
9763
  h('path', { d: 'M3 8h9M8.5 4.5 12 8l-3.5 3.5', fill: 'none', stroke: 'currentColor', strokeWidth: 1.4, strokeLinecap: 'round', strokeLinejoin: 'round' }))),
9524
9764
  ),
9525
- ),
9765
+ ) : null,
9526
9766
  h('div', {
9527
9767
  className: 'dsh-powerup-directask-resizer',
9528
9768
  onPointerDown: (event) => {
@@ -10262,6 +10502,7 @@ html[data-platform="darwin"] .dsh-powerup-scrolltop:hover{background:var(--dsw-s
10262
10502
  featureCard('directAsk', TagIcon, 'page.directAskTitle', 'page.directAskDesc', 'page.directAskHow',
10263
10503
  h('div', { className: 'dsh-powerup-card-detail' },
10264
10504
  settingRow('directAsk', settings.directAsk !== false, t('page.directAskToggle'), t('page.directAskToggleHint')),
10505
+ settingRow('directAskAutoTitle', settings.directAskAutoTitle === true, t('page.directAskAutoTitle'), t('page.directAskAutoTitleHint')),
10265
10506
  ),
10266
10507
  ),
10267
10508
  featureCard('workspacePrompts', TagIcon, 'page.promptsTitle', 'page.promptsDesc', 'page.promptsHow'),
@@ -10326,6 +10567,7 @@ html[data-platform="darwin"] .dsh-powerup-scrolltop:hover{background:var(--dsw-s
10326
10567
  const REQUIREMENTS_API = '/dsh-powerup/api/progress-requirements';
10327
10568
  const HISTORY_API = '/dsh-powerup/api/progress-history';
10328
10569
  const DIRECT_ASK_API = '/dsh-powerup/api/direct-ask';
10570
+ const ASK_TITLE_API = '/dsh-powerup/api/ask-title';
10329
10571
 
10330
10572
  /** Module-level requirements cache: flat records [{id,title,text,workspaceId,enabled}]. */
10331
10573
  let requirementsCache = [];
@@ -10543,17 +10785,21 @@ html[data-platform="darwin"] .dsh-powerup-scrolltop:hover{background:var(--dsw-s
10543
10785
  const t = (key, params) => translateCurrent(key, params);
10544
10786
  const fixedScope = typeof workspaceId !== 'string' || workspaceId === '';
10545
10787
  const key = fixedScope ? '' : workspaceId;
10546
- if (requirementCreateDraft.workspaceId !== key) {
10547
- requirementCreateDraft.workspaceId = key;
10548
- requirementCreateDraft.title = '';
10549
- requirementCreateDraft.text = '';
10550
- requirementCreateDraft.scope = fixedScope ? 'all' : 'current';
10551
- }
10788
+ // Reset the draft to this session's workspace whenever the modal opens.
10789
+ requirementCreateDraft.workspaceId = key;
10790
+ requirementCreateDraft.title = '';
10791
+ requirementCreateDraft.text = '';
10552
10792
  const [title, setTitle] = useState(requirementCreateDraft.title);
10553
10793
  const [text, setText] = useState(requirementCreateDraft.text);
10554
- const [scope, setScope] = useState(requirementCreateDraft.scope);
10794
+ const [targetWorkspace, setTargetWorkspace] = useState(requirementCreateDraft.workspaceId ?? key);
10555
10795
  const [closing, setClosing] = useState(false);
10556
10796
  const closingRef = useRef(false);
10797
+ const workspaces = (() => {
10798
+ try {
10799
+ const snapshot = ctxRef.current?.get?.('workspaces')?.list?.getSnapshot?.();
10800
+ return Array.isArray(snapshot?.items) ? snapshot.items : [];
10801
+ } catch { return []; }
10802
+ })();
10557
10803
  const requestClose = () => {
10558
10804
  if (closingRef.current) return;
10559
10805
  closingRef.current = true;
@@ -10563,8 +10809,8 @@ html[data-platform="darwin"] .dsh-powerup-scrolltop:hover{background:var(--dsw-s
10563
10809
  useEffect(() => {
10564
10810
  requirementCreateDraft.title = title;
10565
10811
  requirementCreateDraft.text = text;
10566
- requirementCreateDraft.scope = scope;
10567
- }, [title, text, scope]);
10812
+ requirementCreateDraft.workspaceId = targetWorkspace;
10813
+ }, [title, text, targetWorkspace]);
10568
10814
  useEffect(() => {
10569
10815
  const onKey = (event) => { if (event.key === 'Escape') { event.preventDefault(); requestClose(); } };
10570
10816
  document.addEventListener('keydown', onKey, true);
@@ -10577,18 +10823,19 @@ html[data-platform="darwin"] .dsh-powerup-scrolltop:hover{background:var(--dsw-s
10577
10823
  id: newId(),
10578
10824
  title: typeof title === 'string' ? title.trim() : '',
10579
10825
  text: body,
10580
- workspaceId: scope === 'current' && typeof workspaceId === 'string' ? workspaceId : '',
10826
+ workspaceId: typeof targetWorkspace === 'string' ? targetWorkspace : '',
10581
10827
  enabled: true,
10582
10828
  };
10583
10829
  saveRequirements([...requirementsCache, record]);
10584
10830
  requirementCreateDraft.title = '';
10585
10831
  requirementCreateDraft.text = '';
10586
- requirementCreateDraft.scope = fixedScope ? 'all' : 'current';
10832
+ requirementCreateDraft.workspaceId = key;
10587
10833
  if (!closingRef.current) { closingRef.current = true; setClosing(true); }
10588
10834
  setTimeout(() => { try { onCreated(record); } catch { /* ignore */ } }, 140);
10589
10835
  };
10590
10836
  return renderInBody(h('div', {
10591
10837
  className: 'dsh-powerup-prompt-modal-mask' + (closing ? ' is-closing' : ''),
10838
+ 'data-powerup-req-modal': '',
10592
10839
  onPointerDown: (event) => { if (event.target === event.currentTarget) requestClose(); },
10593
10840
  },
10594
10841
  h('div', { className: 'dsh-powerup-prompt-modal' + (closing ? ' is-closing' : ''), role: 'dialog', 'aria-modal': 'true' },
@@ -10604,20 +10851,18 @@ html[data-platform="darwin"] .dsh-powerup-scrolltop:hover{background:var(--dsw-s
10604
10851
  h('span', { className: 'dsh-powerup-prompt-field-label' }, t('prompts.titleLabel')),
10605
10852
  h('input', { className: 'dsh-powerup-prompt-input', type: 'text', value: title, placeholder: t('prompts.titlePlaceholder'), onChange: (e) => setTitle(e.target.value) }),
10606
10853
  ),
10607
- !fixedScope
10608
- ? h('label', { className: 'dsh-powerup-prompt-field' },
10609
- h('span', { className: 'dsh-powerup-prompt-field-label' }, t('prompts.workspaceLabel')),
10610
- h(WorkspaceSelect, {
10611
- value: scope,
10612
- options: [
10613
- { value: 'current', label: t('prompts.workspaceCurrent'), hint: workspaceTitle },
10614
- { value: 'all', label: t('prompts.anyWorkspace') },
10615
- ],
10616
- onChange: setScope,
10617
- t,
10618
- }),
10619
- )
10620
- : null,
10854
+ h('label', { className: 'dsh-powerup-prompt-field' },
10855
+ h('span', { className: 'dsh-powerup-prompt-field-label' }, t('prompts.workspaceLabel')),
10856
+ h(WorkspaceSelect, {
10857
+ value: targetWorkspace,
10858
+ options: [
10859
+ { value: '', label: t('prompts.anyWorkspace') },
10860
+ ...workspaces.map((ws) => ({ value: ws.workspaceId, label: ws.title || ws.workspaceId, hint: ws.title ? ws.workspaceId : undefined })),
10861
+ ],
10862
+ onChange: setTargetWorkspace,
10863
+ t,
10864
+ }),
10865
+ ),
10621
10866
  h('label', { className: 'dsh-powerup-prompt-field' },
10622
10867
  h('span', { className: 'dsh-powerup-prompt-field-label' }, t('progress.reqTextLabel')),
10623
10868
  h('textarea', { className: 'dsh-powerup-prompt-input dsh-powerup-prompt-textarea', value: text, placeholder: t('progress.reqPlaceholder'), onChange: (e) => setText(e.target.value) }),
@@ -10938,7 +11183,9 @@ html[data-platform="darwin"] .dsh-powerup-scrolltop:hover{background:var(--dsw-s
10938
11183
 
10939
11184
  const close = useCallback(() => setOpen(false), []);
10940
11185
 
10941
- // Esc and outside click close the panel.
11186
+ // Esc and outside click close the panel. The create-requirement modal is
11187
+ // a body portal, so treat its nodes as "inside" while it is open —
11188
+ // otherwise every click in the modal closes the progress panel.
10942
11189
  useEffect(() => {
10943
11190
  if (!open) return undefined;
10944
11191
  const onKey = (event) => {
@@ -10949,6 +11196,7 @@ html[data-platform="darwin"] .dsh-powerup-scrolltop:hover{background:var(--dsw-s
10949
11196
  const button = buttonRef.current;
10950
11197
  if (panel !== null && event.target instanceof Node && panel.contains(event.target)) return;
10951
11198
  if (button !== null && event.target instanceof Node && button.contains(event.target)) return;
11199
+ if (creatingReq && event.target instanceof Element && event.target.closest('[data-powerup-req-modal]')) return;
10952
11200
  close();
10953
11201
  };
10954
11202
  document.addEventListener('keydown', onKey, true);
@@ -10957,7 +11205,7 @@ html[data-platform="darwin"] .dsh-powerup-scrolltop:hover{background:var(--dsw-s
10957
11205
  document.removeEventListener('keydown', onKey, true);
10958
11206
  document.removeEventListener('pointerdown', onPointer, true);
10959
11207
  };
10960
- }, [open, close]);
11208
+ }, [open, close, creatingReq]);
10961
11209
 
10962
11210
  // Bottom-right resize handle: ordinary pointer events on the panel node.
10963
11211
  useEffect(() => {
@@ -11093,7 +11341,6 @@ html[data-platform="darwin"] .dsh-powerup-scrolltop:hover{background:var(--dsw-s
11093
11341
  })();
11094
11342
 
11095
11343
  const requirementsBody = h('div', { className: 'dsh-powerup-progress-req-tab' },
11096
- h('p', { className: 'dsh-powerup-setting-hint' }, t('progress.reqSelectHint')),
11097
11344
  h(RequirementPicker, {
11098
11345
  reqs: visibleReqs,
11099
11346
  selectedIds: selectedReqIds,
@@ -11366,6 +11613,8 @@ html[data-platform="darwin"] .dsh-powerup-scrolltop:hover{background:var(--dsw-s
11366
11613
  RequirementPicker,
11367
11614
  requirementForWorkspace: requirementsForWorkspace,
11368
11615
  DirectAskButton,
11616
+ renderMarkdown,
11617
+ renderInlineMarkdown,
11369
11618
  progressRequest,
11370
11619
  PROMPTS_LAST_KEY,
11371
11620
  promptCreateDraft,
package/index.js CHANGED
@@ -50,7 +50,7 @@ import {
50
50
  } from './lib/task-resume.js';
51
51
  import { createStepReadTool } from './lib/step-tool.js';
52
52
  import { createProgressManager } from './lib/progress-manager.js';
53
- import { buildAskPrompt, cleanAskText, directAsk } from './lib/direct-ask.js';
53
+ import { buildAskPrompt, cleanAskText, directAsk, generateTitle } from './lib/direct-ask.js';
54
54
 
55
55
  /** Prefix owned by this plugin. */
56
56
  const ROUTE = '/dsh-powerup/api';
@@ -473,7 +473,7 @@ async function handle(req, res, ctx) {
473
473
 
474
474
  const url = new URL(req.url ?? ROUTE, 'http://localhost');
475
475
  const op = url.pathname.slice(ROUTE.length).replace(/^\/+/u, '') || url.searchParams.get('op') || '';
476
- if (op !== '' && op !== 'restart' && op !== 'close' && op !== 'self-update' && op !== 'audit' && op !== 'job-kill' && op !== 'prompts' && op !== 'mask-rules' && op !== 'progress' && op !== 'progress-requirements' && op !== 'progress-history' && op !== 'direct-ask') {
476
+ if (op !== '' && op !== 'restart' && op !== 'close' && op !== 'self-update' && op !== 'audit' && op !== 'job-kill' && op !== 'prompts' && op !== 'mask-rules' && op !== 'progress' && op !== 'progress-requirements' && op !== 'progress-history' && op !== 'direct-ask' && op !== 'ask-title') {
477
477
  sendJson(res, { ok: false, error: 'not-found' }, 404);
478
478
  return;
479
479
  }
@@ -603,6 +603,46 @@ async function handle(req, res, ctx) {
603
603
  return;
604
604
  }
605
605
 
606
+ if (op === 'ask-title') {
607
+ if (req.method !== 'POST') {
608
+ sendJson(res, { ok: false, error: 'method-not-allowed' }, 405);
609
+ return;
610
+ }
611
+ let body;
612
+ try {
613
+ body = await readJsonBody(req);
614
+ } catch (error) {
615
+ sendJson(res, { ok: false, error: String(error?.message ?? error) }, 400);
616
+ return;
617
+ }
618
+ const firstMessage = cleanAskText(body?.firstMessage);
619
+ if (firstMessage === '') {
620
+ sendJson(res, { ok: false, code: 'invalid-request', error: 'firstMessage is required' }, 400);
621
+ return;
622
+ }
623
+ const llm = ctx?.get?.('llm');
624
+ if (llm === null || typeof llm?.prepareCall !== 'function') {
625
+ sendJson(res, { ok: false, code: 'llm-unavailable', error: 'the llm service is unavailable' }, 503);
626
+ return;
627
+ }
628
+ const defaults = ctx?.get?.('agentDefaultModel');
629
+ const selection = typeof defaults?.currentSelection === 'function' ? defaults.currentSelection() : undefined;
630
+ const route = selection !== null && typeof selection === 'object' && typeof selection.provider === 'string'
631
+ ? selection : undefined;
632
+ const controller = new AbortController();
633
+ const timer = setTimeout(() => controller.abort(), 20_000);
634
+ timer.unref?.();
635
+ try {
636
+ const result = await generateTitle({ llm, route, firstMessage, signal: controller.signal });
637
+ sendJson(res, { ok: true, title: result.title });
638
+ } catch (error) {
639
+ sendJson(res, { ok: false, code: error?.code ?? 'title-failed', error: String(error?.message ?? error) }, 500);
640
+ } finally {
641
+ clearTimeout(timer);
642
+ }
643
+ return;
644
+ }
645
+
606
646
  if (op === 'progress') {
607
647
  if (req.method !== 'POST') {
608
648
  sendJson(res, { ok: false, error: 'method-not-allowed' }, 405);
package/lib/direct-ask.js CHANGED
@@ -24,6 +24,55 @@ export const DIRECT_ASK_INPUT_LIMIT = 24_000;
24
24
  /** Default output cap for a one-shot answer. */
25
25
  export const DIRECT_ASK_MAX_TOKENS = 2048;
26
26
 
27
+ /** Max characters of the first question used to generate a title. */
28
+ export const TITLE_INPUT_LIMIT = 800;
29
+ /** Hard cap for title generation tokens. */
30
+ export const TITLE_MAX_TOKENS = 64;
31
+ /** Max characters kept for a generated/edited title. */
32
+ export const TITLE_LIMIT = 60;
33
+
34
+ /**
35
+ * Generate a short conversation title from its first message, with a strict
36
+ * token cap. Returns a plain string (never throws to the caller UI).
37
+ */
38
+ export async function generateTitle({ llm, route, firstMessage, signal }) {
39
+ if (llm === null || typeof llm !== 'object' || typeof llm.prepareCall !== 'function') {
40
+ throw new DirectAskError('LLM_UNAVAILABLE', 'the llm service is unavailable');
41
+ }
42
+ if (route === null || typeof route !== 'object' || typeof route.provider !== 'string' || typeof route.model !== 'string') {
43
+ throw new DirectAskError('NO_ROUTE', 'no provider/model route is available');
44
+ }
45
+ const text = cleanAskText(firstMessage, TITLE_INPUT_LIMIT);
46
+ if (text === '') throw new DirectAskError('EMPTY', 'the first message is empty');
47
+ const config = {
48
+ provider: route.provider,
49
+ model: route.model,
50
+ maxTokens: TITLE_MAX_TOKENS,
51
+ };
52
+ const call = await llm.prepareCall(config, signal);
53
+ const options = {
54
+ ...call.config,
55
+ messages: [{ role: 'user', content: [{ type: 'text', text: `给下面这条用户消息起一个简短标题(不超过 ${TITLE_LIMIT} 个字符),只输出标题本身,不要引号或解释:\n\n${text}` }] }],
56
+ system: 'You write very short conversation titles. Output only the title, no quotes, no punctuation wrapper.',
57
+ purpose: 'powerup-direct-ask-title',
58
+ ...(signal === undefined ? {} : { signal }),
59
+ };
60
+ let raw = '';
61
+ let finish;
62
+ for await (const chunk of call.stream(options)) {
63
+ if (signal?.aborted) throw new DirectAskError('ABORTED', 'title generation cancelled');
64
+ if (chunk === null || typeof chunk !== 'object') continue;
65
+ if (chunk.type === 'text-delta' && typeof chunk.text === 'string') raw += chunk.text;
66
+ else if (chunk.type === 'finish') finish = chunk.reason;
67
+ }
68
+ if (finish?.kind === 'error' || finish?.kind === 'aborted') {
69
+ throw new DirectAskError('LLM_FAILED', `the title call ${finish.kind ?? 'failed'}`);
70
+ }
71
+ // Normalize: strip quotes, collapse whitespace, cap length.
72
+ const title = raw.trim().replace(/^["'「『]|["'」』]$/gu, '').replace(/\s+/gu, ' ').trim().slice(0, TITLE_LIMIT);
73
+ return { title: title || text.slice(0, TITLE_LIMIT), finish };
74
+ }
75
+
27
76
  /** Error with a stable machine code. */
28
77
  export class DirectAskError extends Error {
29
78
  constructor(code, message, options = {}) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@restregular/dsh-powerup",
3
- "version": "0.17.0",
3
+ "version": "0.18.0",
4
4
  "description": "为 DeepSeek Harness 提供一组可选的小型增强:轨迹右键菜单与步骤引用、后台任务停止原因、插件一键安装、侧边栏图标网格、会话切换、定位当前会话、工作区提示词、旁路模型生成的结构化任务进度;所有功能均可在 Power-Up 页面独立开关。 · Opt-in upgrades for DeepSeek Harness: Trajectory context menu and step references, job stop reasons, one-click plugin install, an adaptive sidebar launcher, session switching, locating the current session, workspace prompts, and non-blocking model-generated structured task progress — each toggled independently on the Power-Up page.",
5
5
  "icon": "./icon.svg",
6
6
  "type": "module",