dsh-mcviseron-plugin 0.6.1 → 0.6.3

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/lib/restart.js CHANGED
@@ -106,6 +106,23 @@ function makeTaskScript(target, taskName, delaySeconds) {
106
106
  ""
107
107
  ].join("\n");
108
108
  }
109
+ function launchRestart(target) {
110
+ launchHelper(target);
111
+ }
112
+ function closeDesktop(target) {
113
+ const pid = target?.mainPid ?? process.ppid;
114
+ setTimeout(() => {
115
+ try {
116
+ if (target !== void 0 || process.platform === "win32") process.kill(pid);
117
+ else process.exit(0);
118
+ } catch {
119
+ try {
120
+ process.exit(0);
121
+ } catch {
122
+ }
123
+ }
124
+ }, 300);
125
+ }
109
126
  function launchHelper(target) {
110
127
  const logFile = restartLogPath();
111
128
  try {
@@ -218,8 +235,10 @@ export {
218
235
  DEFAULT_RESTART_CONFIG,
219
236
  RESTART_API,
220
237
  apply,
238
+ closeDesktop,
221
239
  deriveDesktopAppPath,
222
240
  inject,
241
+ launchRestart,
223
242
  makeRestartRoutes,
224
243
  makeTaskScript,
225
244
  resolveRestartTarget
package/lib/task-guard.js CHANGED
@@ -41,7 +41,10 @@ var INTENT_MARKERS = [
41
41
  /\b(?:now|next|then)\s*,?\s*i(?:'ll| will| am going to|'m going to)\b([^\n]{2,160})/gi,
42
42
  /\bi(?:'ll| will| am going to|'m going to)\s+(?:now\s+)?([^\n]{2,160})/gi,
43
43
  /\blet me\s+(?:now\s+)?([^\n]{2,160})/gi,
44
- /(?:接下来|下一步|现在|然后|下面)(?:我会|我将|我要|我来|就开始|开始|准备)([^\n。;;]{2,120})/g
44
+ /\b(?:now|next|then)\s+(?!i(?:'ll| will| am|'m)\b)([a-z][^\n]{2,160})/gi,
45
+ /\b(?:next step|next,)\s*[:\-]?\s*([^\n]{2,160})/gi,
46
+ /(?:接下来|下一步|现在|然后|下面)(?:我会|我将|我要|我来|就开始|开始|准备)([^\n。;;]{2,120})/g,
47
+ /(?:接下来|下一步|现在|然后|下面)(?:开始|进行|做|处理|继续|检查|运行|绘制|布局|布线|导出|放置|连接)([^\n。;;]{2,120})/g
45
48
  ];
46
49
  function intentPhrases(text) {
47
50
  const found = [];
@@ -58,6 +61,24 @@ function intentPhrases(text) {
58
61
  found.sort((left, right) => left.index - right.index);
59
62
  return found.map((item) => item.phrase);
60
63
  }
64
+ var PHASE_PATTERNS = [
65
+ { id: "schematic", pattern: /schematic|原理图/ },
66
+ { id: "library", pattern: /library|footprint|器件库|元件库|封装/ },
67
+ { id: "board", pattern: /board\s*(?:outline|shape)|板框|边框|外形/ },
68
+ { id: "placement", pattern: /placement|layout|布局|摆放/ },
69
+ { id: "routing", pattern: /rout(?:e|ing|ed)|track|走线|布线|连线/ },
70
+ { id: "drc", pattern: /\bdrc\b|\berc\b|design[_ ]audit|校验|检查/ },
71
+ { id: "power", pattern: /power|电源|加粗/ },
72
+ { id: "copper", pattern: /copper|pour|铺铜|覆铜/ },
73
+ { id: "gerber", pattern: /gerber|export|导出|出图/ },
74
+ { id: "usb", pattern: /usb|type-?c/ },
75
+ { id: "mcu", pattern: /stm32|\bmcu\b|主控|单片机/ }
76
+ ];
77
+ function phasesOf(value) {
78
+ const phases = /* @__PURE__ */ new Set();
79
+ for (const { id, pattern } of PHASE_PATTERNS) if (pattern.test(value)) phases.add(id);
80
+ return phases;
81
+ }
61
82
  function detectStepIntent(text, todos) {
62
83
  if (text.length === 0 || todos.length === 0) return void 0;
63
84
  const phrases = intentPhrases(text).slice(-3);
@@ -66,11 +87,15 @@ function detectStepIntent(text, todos) {
66
87
  for (const phrase of phrases) {
67
88
  const phraseNormalized = normalizeText(phrase);
68
89
  const phraseTokens = new Set(tokensOf(phrase));
90
+ const phrasePhases = phasesOf(phrase);
69
91
  for (const todo of todos) {
70
92
  if (todo.status !== "pending") continue;
71
93
  const contentNormalized = normalizeText(todo.content);
94
+ const todoPhases = phasesOf(todo.content);
72
95
  let score = 0;
73
- if (contentNormalized.length >= 4 && (phraseNormalized.includes(contentNormalized) || contentNormalized.includes(phraseNormalized))) {
96
+ if ([...phrasePhases].some((phase) => todoPhases.has(phase))) {
97
+ score = 1;
98
+ } else if (contentNormalized.length >= 4 && (phraseNormalized.includes(contentNormalized) || contentNormalized.includes(phraseNormalized))) {
74
99
  score = 1;
75
100
  } else {
76
101
  const contentTokens = tokensOf(todo.content);
@@ -85,6 +110,56 @@ function detectStepIntent(text, todos) {
85
110
  }
86
111
  return best;
87
112
  }
113
+ var COMPLETION_PATTERNS = [
114
+ /\ball\b[^.!?\n]{0,100}\b(?:routed|connected|placed|done|complete|completed)\b/i,
115
+ /\b(?:schematic|layout|placement|routing|board|design|work|check|drc|erc)\b[^.!?\n]{0,50}\b(?:complete|completed|done|finished|passed|passes|clean)\b/i,
116
+ /\b(?:drc|erc|check|validation)\b[^.!?\n]{0,40}\b(?:passes|passed|clean|0\s+(?:errors?|violations?))\b/i,
117
+ /(?:全部|所有)[^。!?\n]{0,50}(?:布通|连通|完成|通过)|(?:完成|已完成|搞定|通过|布通|连通|无(?:错误|违规)|0\s*(?:错误|违规))/
118
+ ];
119
+ function isCompletionSentence(sentence) {
120
+ return COMPLETION_PATTERNS.some((pattern) => pattern.test(sentence));
121
+ }
122
+ function detectCompletion(text, todos) {
123
+ if (text.length === 0 || todos.length === 0) return void 0;
124
+ const active = todos.filter((todo) => todo.status === "in_progress");
125
+ if (active.length > 1) return void 0;
126
+ const pool = active.length === 1 ? active : todos.filter((todo) => todo.status === "pending");
127
+ if (pool.length === 0) return void 0;
128
+ const sentences = text.split(/(?<=[.!?。!?])\s+|\n+/).map((sentence) => sentence.trim()).filter((sentence) => sentence.length > 0);
129
+ for (const sentence of sentences) {
130
+ if (!isCompletionSentence(sentence)) continue;
131
+ const sentencePhases = phasesOf(sentence);
132
+ let best;
133
+ let bestScore = 0;
134
+ for (const todo of pool) {
135
+ const todoPhases = phasesOf(todo.content);
136
+ let score = 0;
137
+ for (const phase of sentencePhases) if (todoPhases.has(phase)) score += 1;
138
+ if (score > bestScore) {
139
+ best = todo;
140
+ bestScore = score;
141
+ }
142
+ }
143
+ if (best === void 0 && active.length === 1 && sentencePhases.size === 0) {
144
+ best = active[0];
145
+ bestScore = 0.5;
146
+ }
147
+ if (best !== void 0) return { todo: best, phrase: sentence.slice(0, 120), score: bestScore };
148
+ }
149
+ return void 0;
150
+ }
151
+ function completionPayload(todos, matched) {
152
+ const active = todos.filter((todo) => todo.status === "in_progress");
153
+ if (active.length > 1) return void 0;
154
+ const index = todos.findIndex((todo) => todo.content === matched.content);
155
+ if (index < 0) return void 0;
156
+ const next = todos.find((todo, at) => at > index && todo.status === "pending") ?? todos.find((todo, at) => at !== index && todo.status === "pending");
157
+ const updated = todos.map((todo, at) => ({
158
+ content: todo.content,
159
+ status: at === index ? "completed" : next !== void 0 && todo.content === next.content ? "in_progress" : todo.status === "in_progress" && at !== index ? "completed" : todo.status
160
+ }));
161
+ return JSON.stringify({ todos: updated });
162
+ }
88
163
  function serviceOf(scope, name) {
89
164
  try {
90
165
  const direct = scope[name];
@@ -269,7 +344,20 @@ function installTaskGuard(ctx, input) {
269
344
  if (state?.todos == null || !hasUnfinished(state.todos)) return downstream;
270
345
  state.callsSinceWrite += 1;
271
346
  if (config.detectStepIntent && !state.intentNotifiedThisStep) {
272
- const match = detectStepIntent(intentBuffers.get(sessionId) ?? "", state.todos);
347
+ const buffer = intentBuffers.get(sessionId) ?? "";
348
+ const completed = detectCompletion(buffer, state.todos);
349
+ if (completed !== void 0) {
350
+ state.intentNotifiedThisStep = true;
351
+ const notice = await buildCompletionNotice(
352
+ state,
353
+ completed,
354
+ config,
355
+ sourceKindFor(exec.agent, config),
356
+ noticeContext(exec.agent, config, ctx)
357
+ );
358
+ return attachContext(downstream, notice);
359
+ }
360
+ const match = detectStepIntent(buffer, state.todos);
273
361
  if (match !== void 0) {
274
362
  state.intentNotifiedThisStep = true;
275
363
  const notice = await buildIntentNotice(
@@ -501,22 +589,49 @@ async function buildReminder(state, config, sourceKind, context) {
501
589
  const quoted = remaining.slice(0, config.maxListItems).map((todo, index) => (todo.status === "in_progress" ? "[~] " : "[ ] ") + truncate(display[index], 60)).join("\n");
502
590
  const omitted = remaining.length - config.maxListItems;
503
591
  const items = omitted > 0 ? quoted + "\n\u2026 +" + omitted : quoted;
592
+ const activeOne = active.length === 1 ? active[0] : void 0;
593
+ const suggested = activeOne === void 0 ? void 0 : completionPayload(todos, activeOne);
504
594
  const text = config.locale === "en" ? [
505
595
  "[Todo sync] " + state.callsSinceWrite + " tool calls have run since the last todo_write.",
506
596
  "In progress: " + activeText,
507
597
  "Remaining:\n" + items,
508
- "If the current phase is not finished yet, ignore this reminder. The moment it is finished, call todo_write: mark it completed and the next task in_progress (never leave pending work with no active task).",
598
+ activeOne === void 0 ? "If the current phase is finished, call todo_write: mark completed work completed and the next task in_progress (never leave pending work with no active task)." : suggested === void 0 ? "If the current phase is finished, call todo_write: mark it completed and the next task in_progress (never leave pending work with no active task)." : "If the current phase is finished, send this todo_write now; if it is still running, keep that task in_progress and leave the list unchanged:",
599
+ suggested ?? "",
509
600
  "(Tip: todo titles can be written in Chinese.)"
510
- ].join("\n") : [
601
+ ].filter((line) => line !== "").join("\n") : [
511
602
  "\u3010todo \u540C\u6B65\u3011\u8DDD\u4E0A\u6B21 todo_write \u5DF2\u8FC7 " + state.callsSinceWrite + " \u6B21\u5DE5\u5177\u8C03\u7528\u3002",
512
603
  "\u8FDB\u884C\u4E2D\uFF1A" + activeText,
513
604
  "\u5269\u4F59\uFF1A\n" + items,
514
- "\u5982\u679C\u5F53\u524D\u9636\u6BB5\u8FD8\u6CA1\u5B8C\u6210\uFF0C\u8BF7\u5FFD\u7565\u672C\u63D0\u9192\uFF1B\u4E00\u65E6\u5B8C\u6210\uFF0C\u8BF7\u7ACB\u523B\u8C03\u7528 todo_write\uFF1A\u628A\u8BE5\u9636\u6BB5\u6807\u4E3A completed\uFF0C\u5E76\u628A\u4E0B\u4E00\u9636\u6BB5\u6807\u4E3A in_progress\uFF08\u6709\u5269\u4F59\u4EFB\u52A1\u65F6\u4E0D\u8981\u7559\u7A7A\uFF09\u3002",
605
+ activeOne === void 0 ? "\u5982\u679C\u5F53\u524D\u9636\u6BB5\u5DF2\u7ECF\u5B8C\u6210\uFF0C\u8BF7\u8C03\u7528 todo_write\uFF1A\u628A\u5DF2\u5B8C\u6210\u9636\u6BB5\u6807\u4E3A completed\uFF0C\u5E76\u628A\u4E0B\u4E00\u9636\u6BB5\u6807\u4E3A in_progress\uFF08\u6709\u5269\u4F59\u4EFB\u52A1\u65F6\u4E0D\u8981\u7559\u7A7A\uFF09\u3002" : suggested === void 0 ? "\u5982\u679C\u5F53\u524D\u9636\u6BB5\u5DF2\u7ECF\u5B8C\u6210\uFF0C\u8BF7\u8C03\u7528 todo_write\uFF1A\u628A\u8BE5\u9636\u6BB5\u6807\u4E3A completed\uFF0C\u5E76\u628A\u4E0B\u4E00\u9636\u6BB5\u6807\u4E3A in_progress\uFF08\u6709\u5269\u4F59\u4EFB\u52A1\u65F6\u4E0D\u8981\u7559\u7A7A\uFF09\u3002" : "\u5982\u679C\u5F53\u524D\u9636\u6BB5\u5DF2\u7ECF\u5B8C\u6210\uFF0C\u8BF7\u76F4\u63A5\u53D1\u9001\u4EE5\u4E0B todo_write\uFF1B\u5982\u679C\u4ECD\u5728\u8FDB\u884C\uFF0C\u8BF7\u4FDD\u6301\u8BE5\u5F85\u529E\u4E3A in_progress\uFF0C\u65E0\u9700\u6539\u52A8\u6E05\u5355\uFF1A",
606
+ suggested ?? "",
515
607
  "\uFF08\u63D0\u793A\uFF1Atodo \u5185\u5BB9\u53EF\u4EE5\u76F4\u63A5\u7528\u4E2D\u6587\u4E66\u5199\u3002\uFF09"
516
- ].join("\n");
608
+ ].filter((line) => line !== "").join("\n");
517
609
  const summary = config.locale === "en" ? "todo stale \xB7 " + state.callsSinceWrite + " calls" : "todo \u672A\u66F4\u65B0 \xB7 " + state.callsSinceWrite + " \u6B21\u8C03\u7528";
518
610
  return createNotice(text, summary, sourceKind);
519
611
  }
612
+ async function buildCompletionNotice(state, match, config, sourceKind, context) {
613
+ const todos = state.todos ?? [];
614
+ const [display] = await displayTodoContents([match.todo.content], context);
615
+ const suggested = completionPayload(todos, match.todo);
616
+ const phrase = truncate(match.phrase, 80);
617
+ const text = config.locale === "en" ? [
618
+ '[Todo sync] The assistant text looks like a completed phase: "' + display + '".',
619
+ "Source: " + phrase,
620
+ suggested === void 0 ? "If that phase is finished, call todo_write: mark it completed and the next task in_progress." : "If that phase is finished, send this todo_write now:",
621
+ suggested ?? "",
622
+ "If it is still running, keep that task in_progress; do not mark it completed yet.",
623
+ "(Tip: todo titles can be written in Chinese.)"
624
+ ].filter((line) => line !== "").join("\n") : [
625
+ "\u3010todo \u540C\u6B65\u3011\u68C0\u6D4B\u5230\u9636\u6BB5\u5B8C\u6210\uFF1A\u300C" + display + "\u300D",
626
+ "\u4F9D\u636E\uFF1A" + phrase,
627
+ suggested === void 0 ? "\u5982\u679C\u8BE5\u9636\u6BB5\u5DF2\u5B8C\u6210\uFF0C\u8BF7\u8C03\u7528 todo_write\uFF1A\u628A\u8BE5\u5F85\u529E\u6807\u4E3A completed\uFF0C\u5E76\u628A\u4E0B\u4E00\u9636\u6BB5\u6807\u4E3A in_progress\u3002" : "\u5982\u679C\u8BE5\u9636\u6BB5\u786E\u5B9E\u5DF2\u5B8C\u6210\uFF0C\u8BF7\u76F4\u63A5\u53D1\u9001\u4EE5\u4E0B todo_write\uFF1A",
628
+ suggested ?? "",
629
+ "\u5982\u679C\u4ECD\u5728\u8FDB\u884C\uFF0C\u8BF7\u4FDD\u6301\u8BE5\u5F85\u529E\u4E3A in_progress\uFF0C\u4E0D\u8981\u63D0\u524D\u6807 completed\u3002",
630
+ "\uFF08\u63D0\u793A\uFF1Atodo \u5185\u5BB9\u53EF\u4EE5\u76F4\u63A5\u7528\u4E2D\u6587\u4E66\u5199\u3002\uFF09"
631
+ ].filter((line) => line !== "").join("\n");
632
+ const summary = config.locale === "en" ? "todo complete \xB7 " + truncate(display, 40) : "todo \u5B8C\u6210 \xB7 " + truncate(display, 40);
633
+ return createNotice(text, summary, sourceKind);
634
+ }
520
635
  async function buildIntentNotice(state, match, config, sourceKind, context) {
521
636
  const todos = state.todos ?? [];
522
637
  const [display] = await displayTodoContents([match.todo.content], context);
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-mcviseron-plugin",
3
- "version": "0.6.1",
4
- "description": "DeepSeek Harness (DSH) master plugin — one package hosting MCviseron's DSH components as separate bundle entries: a time-based light/dark Appearance schedule, an Auto-review fix (shutdown preset guard + Chinese approval-reason translation), and a todo plan guard that keeps multi-stage work advancing.",
3
+ "version": "0.6.3",
4
+ "description": "DeepSeek Harness (DSH) master plugin — one package hosting MCviseron's DSH components as separate bundle entries: a time-based light/dark Appearance schedule, an Auto-review fix (shutdown preset guard + Chinese approval-reason translation), and a todo plan guard that keeps multi-stage work advancing, and one-shot after-session restart/close actions with task-aware waiting.",
5
5
  "license": "Apache-2.0",
6
6
  "author": {
7
7
  "name": "MCviseron",
@@ -78,7 +78,7 @@
78
78
  "scripts": {
79
79
  "build": "node build.mjs",
80
80
  "typecheck": "tsc --noEmit",
81
- "test": "node --experimental-strip-types test/schedule.test.ts && node --experimental-strip-types test/routes.test.ts && node --experimental-strip-types test/config.test.ts && node --experimental-strip-types test/auto-review-fix.test.ts && node --experimental-strip-types test/auto-review-fix-cordis.test.ts && node --experimental-strip-types test/task-guard.test.ts && node --experimental-strip-types test/task-guard-cordis.test.ts && node --experimental-strip-types test/restart.test.ts && node --experimental-strip-types test/plugin.test.ts",
81
+ "test": "node --experimental-strip-types test/schedule.test.ts && node --experimental-strip-types test/routes.test.ts && node --experimental-strip-types test/config.test.ts && node --experimental-strip-types test/auto-review-fix.test.ts && node --experimental-strip-types test/auto-review-fix-cordis.test.ts && node --experimental-strip-types test/task-guard.test.ts && node --experimental-strip-types test/task-guard-cordis.test.ts && node --experimental-strip-types test/session-end.test.ts && node --experimental-strip-types test/restart.test.ts && node --experimental-strip-types test/plugin.test.ts",
82
82
  "check": "pnpm typecheck && pnpm test && pnpm build",
83
83
  "prepare": "pnpm build",
84
84
  "prepublishOnly": "pnpm check",
@@ -128,15 +128,6 @@
128
128
  }
129
129
  },
130
130
  "devDependencies": {
131
- "@types/node": "^22.20.0",
132
- "@types/react": "~18.3.1",
133
- "@types/react-dom": "^18.3.5",
134
- "esbuild": "^0.24.0",
135
- "immer": "10.2.0",
136
- "zustand": "4.4.7",
137
- "react": "^18.3.1",
138
- "react-dom": "^18.3.1",
139
- "typescript": "~5.7.2",
140
131
  "@deepseek-ai/cordis": "^4.0.5",
141
132
  "@deepseek-ai/dsh-client-connection": "^0.2.1-rc.2",
142
133
  "@deepseek-ai/dsh-client-locale": "^0.2.1-rc.2",
@@ -145,6 +136,17 @@
145
136
  "@deepseek-ai/dsh-client-ui-settings": "^0.2.1-rc.2",
146
137
  "@deepseek-ai/dsh-client-ui-slots": "^0.2.1-rc.2",
147
138
  "@deepseek-ai/dsh-host-webserver": "^0.2.1-rc.2",
148
- "@deepseek-ai/dsh-settings": "^0.2.1-rc.2"
139
+ "@deepseek-ai/dsh-settings": "^0.2.1-rc.2",
140
+ "@types/node": "^22.20.0",
141
+ "@types/nodemailer": "^6.4.15",
142
+ "@types/react": "~18.3.1",
143
+ "@types/react-dom": "^18.3.5",
144
+ "esbuild": "^0.24.0",
145
+ "immer": "10.2.0",
146
+ "nodemailer": "^6.9.13",
147
+ "react": "^18.3.1",
148
+ "react-dom": "^18.3.1",
149
+ "typescript": "~5.7.2",
150
+ "zustand": "4.4.7"
149
151
  }
150
152
  }
package/src/api.ts CHANGED
@@ -3,3 +3,9 @@ export const MCVISERON_API = {
3
3
  describe: '/api/dsh-mcviseron/settings/describe',
4
4
  mutate: '/api/dsh-mcviseron/settings/mutate',
5
5
  } as const
6
+
7
+ /** Session-end action endpoints used by the composer control. */
8
+ export const SESSION_END_API = {
9
+ state: '/api/dsh-mcviseron/session-end/state',
10
+ set: '/api/dsh-mcviseron/session-end/set',
11
+ } as const
@@ -5,7 +5,7 @@ import { Switch } from '@deepseek-ai/dsh-client-ui-primitives'
5
5
  import { pageStyles } from './styles.ts'
6
6
 
7
7
  type Status = 'loading' | 'ready' | 'saving' | 'saved' | 'failed' | 'unavailable'
8
- type FieldKind = 'switch' | 'number' | 'text' | 'select' | 'list'
8
+ type FieldKind = 'switch' | 'number' | 'text' | 'textarea' | 'select' | 'list'
9
9
 
10
10
  /** One editable config field backed by a nested entry path. */
11
11
  export interface ConfigField {
@@ -89,6 +89,25 @@ function TextControl({ value, disabled, onCommit }: {
89
89
  )
90
90
  }
91
91
 
92
+ function TextareaControl({ value, disabled, onCommit }: {
93
+ value: string
94
+ disabled: boolean
95
+ onCommit: (value: string) => void
96
+ }) {
97
+ const [draft, setDraft] = useState(value)
98
+ useEffect(() => { setDraft(value) }, [value])
99
+ return (
100
+ <textarea
101
+ value={draft}
102
+ disabled={disabled}
103
+ rows={4}
104
+ onChange={(event) => { setDraft(event.target.value) }}
105
+ onBlur={() => { if (draft !== value) onCommit(draft) }}
106
+ style={{ ...pageStyles.formControl, minHeight: 88, resize: 'vertical' }}
107
+ />
108
+ )
109
+ }
110
+
92
111
  function ListControl({ value, disabled, onCommit }: {
93
112
  value: string[]
94
113
  disabled: boolean
@@ -144,6 +163,8 @@ function renderControl(
144
163
  )
145
164
  case 'text':
146
165
  return <TextControl value={typeof value === 'string' ? value : ''} disabled={disabled} onCommit={commit} />
166
+ case 'textarea':
167
+ return <TextareaControl value={typeof value === 'string' ? value : ''} disabled={disabled} onCommit={commit} />
147
168
  case 'list':
148
169
  return (
149
170
  <ListControl
@@ -282,3 +303,12 @@ export const TASK_GUARD_FIELDS: readonly ConfigField[] = [
282
303
  { path: ['taskGuard', 'include'], label: 'form.taskGuard.include', hint: 'form.taskGuard.listHint', kind: 'list' },
283
304
  { path: ['taskGuard', 'exclude'], label: 'form.taskGuard.exclude', hint: 'form.taskGuard.listHint', kind: 'list' },
284
305
  ]
306
+
307
+ /** Session-end action fields. */
308
+ export const SESSION_END_FIELDS: readonly ConfigField[] = [
309
+ { path: ['sessionEnd', 'enabled'], label: 'form.sessionEnd.enabled', hint: 'form.sessionEnd.enabledHint', kind: 'switch' },
310
+ { path: ['sessionEnd', 'graceMs'], label: 'form.sessionEnd.grace', hint: 'form.sessionEnd.graceHint', kind: 'number', min: 0, max: 15000 },
311
+ { path: ['sessionEnd', 'notifyEmailOnAi'], label: 'form.sessionEnd.notifyEmail', hint: 'form.sessionEnd.notifyEmailHint', kind: 'switch' },
312
+ { path: ['sessionEnd', 'emailSubject'], label: 'form.sessionEnd.emailSubject', kind: 'text' },
313
+ { path: ['sessionEnd', 'emailBody'], label: 'form.sessionEnd.emailBody', hint: 'form.sessionEnd.emailBodyHint', kind: 'textarea' },
314
+ ]
@@ -0,0 +1,332 @@
1
+ import { useEffect, useRef, useState, type CSSProperties } from 'react'
2
+ import type { PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'
3
+ import { SESSION_END_API } from '../api.ts'
4
+ import type { McviseronKey } from './locales.ts'
5
+
6
+ type Mode = 'off' | 'restart' | 'close' | 'shutdown'
7
+ type RequestedBy = 'none' | 'user' | 'ai'
8
+
9
+ interface State {
10
+ enabled: boolean
11
+ mode: Mode
12
+ requestedBy: RequestedBy
13
+ waiting: boolean
14
+ runningAgents: number
15
+ runningJobs: number
16
+ available: { restart: boolean; close: boolean; shutdown: boolean }
17
+ }
18
+
19
+ const INITIAL: State = {
20
+ enabled: true,
21
+ mode: 'off',
22
+ requestedBy: 'none',
23
+ waiting: false,
24
+ runningAgents: 0,
25
+ runningJobs: 0,
26
+ available: { restart: true, close: true, shutdown: true },
27
+ }
28
+
29
+ export type SessionEndControlProps =
30
+ PropsRuntime<'conversation.input.left'>
31
+ & PropsLocale<'mcviseron'>
32
+
33
+ const labelStyle: CSSProperties = {
34
+ display: 'inline-flex',
35
+ alignItems: 'center',
36
+ gap: 6,
37
+ padding: '0 6px',
38
+ height: 28,
39
+ borderRadius: 8,
40
+ fontSize: 12,
41
+ lineHeight: 1.3,
42
+ color: 'var(--dsw-alias-label-secondary)',
43
+ whiteSpace: 'nowrap',
44
+ }
45
+
46
+ const triggerStyle: CSSProperties = {
47
+ display: 'inline-flex',
48
+ alignItems: 'center',
49
+ justifyContent: 'space-between',
50
+ gap: 6,
51
+ height: 28,
52
+ minWidth: 92,
53
+ maxWidth: 150,
54
+ borderRadius: 10,
55
+ border: '1px solid var(--dsw-alias-border-l3)',
56
+ background: 'var(--dsw-alias-bg-layer-2)',
57
+ color: 'var(--dsw-alias-label-primary)',
58
+ fontSize: 12,
59
+ lineHeight: 1.3,
60
+ padding: '0 8px',
61
+ cursor: 'pointer',
62
+ }
63
+
64
+ const menuStyle: CSSProperties = {
65
+ position: 'fixed',
66
+ zIndex: 10000,
67
+ padding: 6,
68
+ display: 'flex',
69
+ flexDirection: 'column',
70
+ gap: 2,
71
+ borderRadius: 14,
72
+ border: '1px solid var(--dsw-alias-border-l3)',
73
+ background: 'var(--dsw-alias-bg-layer-2)',
74
+ boxShadow: '0 18px 44px rgba(0, 0, 0, 0.32)',
75
+ }
76
+
77
+ const menuOptionStyle: CSSProperties = {
78
+ display: 'flex',
79
+ alignItems: 'center',
80
+ justifyContent: 'space-between',
81
+ gap: 10,
82
+ width: '100%',
83
+ border: 0,
84
+ borderRadius: 10,
85
+ background: 'transparent',
86
+ color: 'var(--dsw-alias-label-primary)',
87
+ fontSize: 13,
88
+ lineHeight: '20px',
89
+ padding: '7px 10px',
90
+ textAlign: 'left',
91
+ cursor: 'pointer',
92
+ }
93
+
94
+ const noticeStyle: CSSProperties = {
95
+ display: 'inline-flex',
96
+ alignItems: 'center',
97
+ gap: 4,
98
+ padding: '3px 8px',
99
+ borderRadius: 999,
100
+ border: '1px solid var(--dsw-alias-state-warn-primary)',
101
+ background: 'var(--dsw-alias-state-warn-tertiary)',
102
+ color: 'var(--dsw-alias-state-warn-primary)',
103
+ fontSize: 12,
104
+ fontWeight: 700,
105
+ lineHeight: '18px',
106
+ whiteSpace: 'nowrap',
107
+ }
108
+
109
+ const shutdownNoticeStyle: CSSProperties = {
110
+ ...noticeStyle,
111
+ borderColor: 'var(--dsw-alias-state-error-primary)',
112
+ background: 'var(--dsw-alias-state-error-tertiary)',
113
+ color: 'var(--dsw-alias-state-error-primary)',
114
+ }
115
+
116
+ /**
117
+ * Composer control for the one-shot session-end action.
118
+ *
119
+ * The dropdown is off by default. The server state is polled because the agent
120
+ * can arm the action through its set_session_end_action tool while a turn is
121
+ * running; the AI-requested state gets a colored, non-modal reminder.
122
+ */
123
+ export function SessionEndControl(props: SessionEndControlProps) {
124
+ const { t } = props
125
+ const sessionId = (props as { sessionId?: string }).sessionId
126
+ const [state, setState] = useState<State>(INITIAL)
127
+ const [busy, setBusy] = useState(false)
128
+ const [open, setOpen] = useState(false)
129
+ const [menu, setMenu] = useState({ left: 0, bottom: 0, minWidth: 0 })
130
+ const triggerRef = useRef<HTMLButtonElement>(null)
131
+ const menuRef = useRef<HTMLDivElement>(null)
132
+
133
+ useEffect(() => {
134
+ if (sessionId === undefined || sessionId === '') {
135
+ setState(INITIAL)
136
+ return
137
+ }
138
+ let cancelled = false
139
+ const load = async (): Promise<void> => {
140
+ try {
141
+ const response = await fetch(SESSION_END_API.state, {
142
+ method: 'POST',
143
+ headers: { 'content-type': 'application/json' },
144
+ body: JSON.stringify({ sessionId }),
145
+ })
146
+ const body = await response.json() as Partial<State> & { ok?: boolean }
147
+ if (cancelled || body.ok !== true) return
148
+ setState(prev => ({
149
+ ...prev,
150
+ ...body,
151
+ available: body.available ?? prev.available,
152
+ }))
153
+ } catch {
154
+ /* a transient poll failure leaves the last known state in place */
155
+ }
156
+ }
157
+ void load()
158
+ const timer = setInterval(() => { void load() }, 1500)
159
+ return () => {
160
+ cancelled = true
161
+ clearInterval(timer)
162
+ }
163
+ }, [sessionId])
164
+
165
+ useEffect(() => {
166
+ if (!open) return
167
+ const close = (): void => { setOpen(false) }
168
+ const onPointer = (event: MouseEvent): void => {
169
+ const target = event.target as Node
170
+ if (triggerRef.current?.contains(target) || menuRef.current?.contains(target)) return
171
+ setOpen(false)
172
+ }
173
+ const onKey = (event: KeyboardEvent): void => {
174
+ if (event.key === 'Escape') setOpen(false)
175
+ }
176
+ document.addEventListener('mousedown', onPointer)
177
+ document.addEventListener('keydown', onKey)
178
+ window.addEventListener('resize', close)
179
+ window.addEventListener('scroll', close, true)
180
+ return () => {
181
+ document.removeEventListener('mousedown', onPointer)
182
+ document.removeEventListener('keydown', onKey)
183
+ window.removeEventListener('resize', close)
184
+ window.removeEventListener('scroll', close, true)
185
+ }
186
+ }, [open])
187
+
188
+ if (sessionId === undefined || sessionId === '') return null
189
+
190
+
191
+ const toggleMenu = (): void => {
192
+ if (open) {
193
+ setOpen(false)
194
+ return
195
+ }
196
+ const rect = triggerRef.current?.getBoundingClientRect()
197
+ if (rect === undefined) return
198
+ const minWidth = Math.max(rect.width, 176)
199
+ const left = Math.min(
200
+ Math.max(8, rect.left),
201
+ Math.max(8, window.innerWidth - minWidth - 8),
202
+ )
203
+ setMenu({ left, bottom: window.innerHeight - rect.top + 6, minWidth })
204
+ setOpen(true)
205
+ }
206
+
207
+ const change = (mode: Mode): void => {
208
+ setOpen(false)
209
+ if (mode === 'shutdown' && typeof window !== 'undefined' && typeof window.confirm === 'function') {
210
+ if (!window.confirm(t('sessionEnd.shutdownConfirm'))) return
211
+ }
212
+ setBusy(true)
213
+ setState(prev => ({
214
+ ...prev,
215
+ mode,
216
+ requestedBy: mode === 'off' ? 'none' : 'user',
217
+ waiting: false,
218
+ }))
219
+ void fetch(SESSION_END_API.set, {
220
+ method: 'POST',
221
+ headers: { 'content-type': 'application/json' },
222
+ body: JSON.stringify({ sessionId, mode }),
223
+ })
224
+ .then(async response => await response.json() as Partial<State> & { ok?: boolean })
225
+ .then(body => {
226
+ if (body.ok === true) {
227
+ setState(prev => ({
228
+ ...prev,
229
+ ...body,
230
+ available: body.available ?? prev.available,
231
+ }))
232
+ }
233
+ })
234
+ .catch(() => { /* the next poll reconciles */ })
235
+ .finally(() => { setBusy(false) })
236
+ }
237
+
238
+ if (state.enabled === false) return null
239
+
240
+ const aiRequested = state.mode !== 'off' && state.requestedBy === 'ai'
241
+ const shutdown = state.mode === 'shutdown'
242
+ const notice = shutdown
243
+ ? t('sessionEnd.userShutdown')
244
+ : aiRequested
245
+ ? state.mode === 'close'
246
+ ? t('sessionEnd.aiClose')
247
+ : state.waiting ? t('sessionEnd.aiWaiting') : t('sessionEnd.aiRestart')
248
+ : ''
249
+
250
+ return (
251
+ <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
252
+ {notice !== '' && (
253
+ <span
254
+ style={shutdown ? shutdownNoticeStyle : noticeStyle}
255
+ title={state.waiting ? t('sessionEnd.aiWaiting') : notice}
256
+ >
257
+ {notice}
258
+ </span>
259
+ )}
260
+ <style>{`
261
+ .mcviseron-session-end-trigger { transition: background 120ms ease, border-color 120ms ease; }
262
+ .mcviseron-session-end-trigger:hover:not(:disabled) { background: var(--dsw-alias-interactive-bg-hover, var(--dsw-alias-bg-layer-3)); }
263
+ .mcviseron-session-end-option { transition: background 120ms ease; }
264
+ .mcviseron-session-end-option:hover:not(:disabled) { background: var(--dsw-alias-interactive-bg-hover, var(--dsw-alias-bg-layer-3)); }
265
+ `}</style>
266
+ <span style={labelStyle} title={t('sessionEnd.hint')}>
267
+ <span>{t('sessionEnd.label')}</span>
268
+ <button
269
+ ref={triggerRef}
270
+ type="button"
271
+ className="mcviseron-session-end-trigger"
272
+ aria-label={t('sessionEnd.label')}
273
+ aria-haspopup="listbox"
274
+ aria-expanded={open}
275
+ title={t('sessionEnd.hint')}
276
+ style={{
277
+ ...triggerStyle,
278
+ borderColor: aiRequested ? 'var(--dsw-alias-state-warn-primary)' : 'var(--dsw-alias-border-l3)',
279
+ }}
280
+ disabled={busy}
281
+ onClick={toggleMenu}
282
+ >
283
+ <span>{t(
284
+ state.mode === 'off'
285
+ ? 'sessionEnd.off'
286
+ : state.mode === 'restart'
287
+ ? 'sessionEnd.restart'
288
+ : state.mode === 'close'
289
+ ? 'sessionEnd.close'
290
+ : 'sessionEnd.shutdown',
291
+ )}</span>
292
+ <span aria-hidden style={{ fontSize: 10, opacity: 0.75 }}>{open ? '▴' : '▾'}</span>
293
+ </button>
294
+ {open && (
295
+ <div
296
+ ref={menuRef}
297
+ role="listbox"
298
+ aria-label={t('sessionEnd.label')}
299
+ style={{ ...menuStyle, left: menu.left, bottom: menu.bottom, minWidth: menu.minWidth }}
300
+ >
301
+ {([
302
+ ['off', 'sessionEnd.off', false],
303
+ ['restart', 'sessionEnd.restart', !state.available.restart],
304
+ ['close', 'sessionEnd.close', !state.available.close],
305
+ ['shutdown', 'sessionEnd.shutdown', !state.available.shutdown],
306
+ ] as const).map(([value, label, disabled]) => (
307
+ <button
308
+ key={value}
309
+ type="button"
310
+ role="option"
311
+ aria-selected={state.mode === value}
312
+ disabled={disabled}
313
+ className="mcviseron-session-end-option"
314
+ style={{
315
+ ...menuOptionStyle,
316
+ color: state.mode === value ? 'var(--dsw-alias-brand-primary)' : menuOptionStyle.color,
317
+ fontWeight: state.mode === value ? 600 : 400,
318
+ opacity: disabled ? 0.45 : 1,
319
+ cursor: disabled ? 'default' : 'pointer',
320
+ }}
321
+ onClick={() => { if (!disabled) change(value) }}
322
+ >
323
+ <span>{t(label)}</span>
324
+ {state.mode === value ? <span aria-hidden>✓</span> : null}
325
+ </button>
326
+ ))}
327
+ </div>
328
+ )}
329
+ </span>
330
+ </span>
331
+ )
332
+ }