@steerable/agent-shell-web 0.14.3 → 0.14.4

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.
@@ -10,7 +10,14 @@ import {
10
10
  import ReactMarkdown, { type Components } from 'react-markdown';
11
11
  import remarkGfm from 'remark-gfm';
12
12
  import rehypeRaw from 'rehype-raw';
13
- import { LuBlocks, LuMessageSquare, LuPlug } from 'react-icons/lu';
13
+ import {
14
+ LuBlocks,
15
+ LuCircle,
16
+ LuCircleCheck,
17
+ LuMessageSquare,
18
+ LuPlug,
19
+ } from 'react-icons/lu';
20
+ import { splitMessageWithProposedPlans } from '@steerable/agent-protocol';
14
21
  import { t } from '@/i18n';
15
22
  import type { LocalChat, LocalChatAgent } from '@/lib/local-api';
16
23
  import {
@@ -446,17 +453,108 @@ export function Markdown({
446
453
  renderTextWithMentions(node, agents, chats, skills, mcpTools),
447
454
  );
448
455
 
456
+ const cleaned = stripNextStepsTags(children);
457
+ const mayContainPlan =
458
+ cleaned.includes('<proposed_plan>') ||
459
+ cleaned.includes('<PROPOSED_PLAN>') ||
460
+ /(?:^|\n)\s*(?:`{3,}|~{3,})plan\b/i.test(cleaned);
461
+
462
+ if (!mayContainPlan) {
463
+ return (
464
+ <ReactMarkdown
465
+ remarkPlugins={[[remarkGfm, { singleTilde: false }]]}
466
+ rehypePlugins={[rehypeRaw]}
467
+ components={finalComponents}
468
+ >
469
+ {cleaned}
470
+ </ReactMarkdown>
471
+ );
472
+ }
473
+
474
+ const segments = splitMessageWithProposedPlans(cleaned);
475
+ const hasPlanSegment = segments.some((seg) => seg.kind === 'plan');
476
+ if (!hasPlanSegment) {
477
+ return (
478
+ <ReactMarkdown
479
+ remarkPlugins={[[remarkGfm, { singleTilde: false }]]}
480
+ rehypePlugins={[rehypeRaw]}
481
+ components={finalComponents}
482
+ >
483
+ {cleaned}
484
+ </ReactMarkdown>
485
+ );
486
+ }
487
+
488
+ const planBodyComponents: Components = {
489
+ ...finalComponents,
490
+ li: (props: ComponentPropsWithoutRef<'li'> & { className?: string }) => {
491
+ const isTaskItem =
492
+ typeof props.className === 'string' &&
493
+ props.className.includes('task-list-item');
494
+ return (
495
+ <li
496
+ {...props}
497
+ className={
498
+ isTaskItem
499
+ ? 'flex list-none items-start gap-2 leading-relaxed -ml-4'
500
+ : 'leading-relaxed marker:text-amber-500/70'
501
+ }
502
+ />
503
+ );
504
+ },
505
+ input: (props: ComponentPropsWithoutRef<'input'>) => {
506
+ if (props.type === 'checkbox') {
507
+ return props.checked ? (
508
+ <LuCircleCheck
509
+ aria-hidden="true"
510
+ className="mt-[3px] h-3.5 w-3.5 shrink-0 text-amber-600 dark:text-amber-400"
511
+ />
512
+ ) : (
513
+ <LuCircle
514
+ aria-hidden="true"
515
+ className="mt-[3px] h-3.5 w-3.5 shrink-0 text-amber-500/65"
516
+ />
517
+ );
518
+ }
519
+ return <input {...props} />;
520
+ },
521
+ };
522
+
523
+ let lastPlanIdx = -1;
524
+ for (let i = 0; i < segments.length; i++) {
525
+ if (segments[i]?.kind === 'plan') lastPlanIdx = i;
526
+ }
527
+
449
528
  return (
450
- <ReactMarkdown
451
- // `singleTilde: false` — GFM 删除线只认 `~~text~~`。remark-gfm 默认还把
452
- // 单个 `~`("约~50%"、"5~10 个"、"~/path")当删除线开闭符,导致普通
453
- // 文本被莫名划掉。GitHub 本站也只渲染双波浪线。
454
- remarkPlugins={[[remarkGfm, { singleTilde: false }]]}
455
- rehypePlugins={[rehypeRaw]}
456
- components={finalComponents}
457
- >
458
- {stripNextStepsTags(children)}
459
- </ReactMarkdown>
529
+ <>
530
+ {segments.map((seg, idx) =>
531
+ seg.kind === 'markdown' ? (
532
+ <ReactMarkdown
533
+ key={`md-${idx}`}
534
+ remarkPlugins={[[remarkGfm, { singleTilde: false }]]}
535
+ rehypePlugins={[rehypeRaw]}
536
+ components={finalComponents}
537
+ >
538
+ {seg.content}
539
+ </ReactMarkdown>
540
+ ) : (
541
+ <PlanTodoList
542
+ key={`plan-${idx}`}
543
+ plan={seg.plan}
544
+ isLastPlanInMessage={idx === lastPlanIdx}
545
+ renderRichMarkdown={(md) => (
546
+ <ReactMarkdown
547
+ remarkPlugins={[[remarkGfm, { singleTilde: false }]]}
548
+ rehypePlugins={[rehypeRaw]}
549
+ components={planBodyComponents}
550
+ >
551
+ {md}
552
+ </ReactMarkdown>
553
+ )}
554
+ />
555
+ ),
556
+ )}
557
+ </>
460
558
  );
461
559
  }
462
560
 
@@ -1,81 +1,107 @@
1
- import { LuCircle, LuCircleCheck, LuListChecks } from 'react-icons/lu';
1
+ import { useState, type ReactNode } from 'react';
2
+ import {
3
+ LuArrowRight,
4
+ LuCheck,
5
+ LuCircle,
6
+ LuCircleCheck,
7
+ LuCopy,
8
+ LuListChecks,
9
+ LuSquarePlus,
10
+ } from 'react-icons/lu';
11
+ import {
12
+ parseProposedPlanBody,
13
+ type ParsedProposedPlan,
14
+ } from '@steerable/agent-protocol';
2
15
  import { t } from '@/i18n';
16
+ import {
17
+ useCurrentMessageId,
18
+ usePlanActionContext,
19
+ } from '@/lib/chat-mode-store';
3
20
 
4
21
  /**
5
- * PlanTodoList — renders the ```plan fenced block that the plan-mode skill
6
- * instructs the model to emit, as a visual todolist card instead of a raw
7
- * code block.
22
+ * PlanTodoList — renders `<proposed_plan>` blocks and legacy ```` ```plan ````
23
+ * fenced blocks as an actionable plan artifact card.
8
24
  *
9
- * Expected fence content (see src/local-backend/skills/70-plan-mode):
10
- *
11
- * # 一句话计划标题
12
- * - [ ] 第一步……
13
- * - [x] 已完成的步骤(执行回顾时可能出现)
14
- *
15
- * The parser is intentionally forgiving: numbered lists (`1. …`), plain
16
- * dashes (`- …`) and bare `[ ] …` lines all count as steps, so a slightly
17
- * off-spec local model still gets a proper todolist instead of a wall of
18
- * monospace text. Unclosed fences during streaming parse the same way, so
19
- * steps appear progressively as tokens arrive.
25
+ * Supports both simple checklist plans and rich Markdown specifications
26
+ * (summaries, subheadings, nested code blocks, tables), plus an inline
27
+ * Codex-style 3-way implementation footer on the latest actionable plan.
20
28
  */
21
29
 
22
- interface PlanItem {
30
+ export interface PlanItem {
23
31
  text: string;
24
32
  done: boolean;
25
33
  }
26
34
 
27
- interface ParsedPlan {
35
+ export interface ParsedPlan {
28
36
  title: string | null;
29
37
  items: PlanItem[];
30
38
  notes: string[];
31
39
  }
32
40
 
33
- const CHECKBOX_RE = /^(?:[-*]\s*)?\[([ xX])\]\s*(.*)$/;
34
- const BULLET_RE = /^[-*]\s+(.*)$/;
35
- const NUMBERED_RE = /^\d+[.、)]\s*(.*)$/;
36
-
37
41
  export function parsePlanContent(raw: string): ParsedPlan {
38
- const plan: ParsedPlan = { title: null, items: [], notes: [] };
39
- for (const line of raw.split('\n')) {
40
- const trimmed = line.trim();
41
- if (!trimmed) continue;
42
+ const parsed = parseProposedPlanBody(raw);
43
+ return {
44
+ title: parsed.title,
45
+ items: parsed.steps,
46
+ notes: parsed.notes,
47
+ };
48
+ }
42
49
 
43
- if (trimmed.startsWith('#')) {
44
- const title = trimmed.replace(/^#+\s*/, '');
45
- if (title && plan.title === null) plan.title = title;
46
- continue;
47
- }
50
+ export interface PlanTodoListProps {
51
+ /** Raw inner text when rendered from a standalone ```` ```plan ```` code block. */
52
+ content?: string;
53
+ /** Pre-parsed plan model when split at the message level. */
54
+ plan?: ParsedProposedPlan;
55
+ /** Optional rich Markdown renderer injected by `Markdown.tsx` to avoid circular imports. */
56
+ renderRichMarkdown?: (markdown: string) => ReactNode;
57
+ /** True when this card is the last plan block in its parent message (default: true). */
58
+ isLastPlanInMessage?: boolean;
59
+ }
48
60
 
49
- const checkbox = trimmed.match(CHECKBOX_RE);
50
- if (checkbox) {
51
- const text = checkbox[2].trim();
52
- if (text) plan.items.push({ text, done: checkbox[1] !== ' ' });
53
- continue;
54
- }
61
+ export function PlanTodoList({
62
+ content = '',
63
+ plan: providedPlan,
64
+ renderRichMarkdown,
65
+ isLastPlanInMessage = true,
66
+ }: PlanTodoListProps) {
67
+ const plan: ParsedProposedPlan = providedPlan ?? {
68
+ syntax: 'fence',
69
+ complete: true,
70
+ ...parseProposedPlanBody(content),
71
+ };
72
+ const { title, steps: items, notes, hasRichMarkdown, bodyMarkdown, markdown } = plan;
55
73
 
56
- const bullet = trimmed.match(BULLET_RE) ?? trimmed.match(NUMBERED_RE);
57
- if (bullet) {
58
- const text = bullet[1].trim();
59
- if (text) plan.items.push({ text, done: false });
60
- continue;
61
- }
74
+ const [copied, setCopied] = useState(false);
75
+ const currentMessageId = useCurrentMessageId();
76
+ const planActionCtx = usePlanActionContext();
62
77
 
63
- plan.notes.push(trimmed);
64
- }
65
- return plan;
66
- }
78
+ const showActionFooter = Boolean(
79
+ isLastPlanInMessage &&
80
+ planActionCtx?.actionable &&
81
+ currentMessageId &&
82
+ planActionCtx.actionable.messageId === currentMessageId,
83
+ );
84
+ const contextUsedPercent = planActionCtx?.actionable?.contextUsedPercent ?? null;
67
85
 
68
- export function PlanTodoList({ content }: { content: string }) {
69
- const { title, items, notes } = parsePlanContent(content);
86
+ const handleCopy = () => {
87
+ const copyText = markdown || content;
88
+ if (!copyText || typeof navigator === 'undefined' || !navigator.clipboard?.writeText) {
89
+ return;
90
+ }
91
+ void navigator.clipboard.writeText(copyText).then(() => {
92
+ setCopied(true);
93
+ setTimeout(() => setCopied(false), 1800);
94
+ });
95
+ };
70
96
 
71
97
  return (
72
98
  <div
73
- className="my-2 overflow-hidden rounded-agent-lg border border-amber-400/50 bg-amber-400/5 not-italic dark:border-amber-500/30"
99
+ className="my-2.5 overflow-hidden rounded-agent-lg border border-amber-400/50 bg-amber-400/5 not-italic dark:border-amber-500/30"
74
100
  data-testid="plan-todo-list"
75
101
  >
76
102
  <div className="flex items-center gap-2 border-b border-amber-400/30 bg-amber-400/10 px-3 py-2 dark:border-amber-500/20">
77
103
  <LuListChecks className="h-4 w-4 shrink-0 text-amber-600 dark:text-amber-400" />
78
- <span className="flex-1 truncate text-[13px] font-semibold text-amber-800 dark:text-amber-200">
104
+ <span className="flex-1 truncate text-[13px] font-semibold text-amber-900 dark:text-amber-100">
79
105
  {title || t('Execution plan')}
80
106
  </span>
81
107
  {items.length > 0 && (
@@ -83,36 +109,116 @@ export function PlanTodoList({ content }: { content: string }) {
83
109
  {items.filter((i) => i.done).length}/{items.length}
84
110
  </span>
85
111
  )}
112
+ {markdown && (
113
+ <button
114
+ type="button"
115
+ onClick={handleCopy}
116
+ title={copied ? t('Copied') : t('Copy plan')}
117
+ aria-label={copied ? t('Copied') : t('Copy plan')}
118
+ data-testid="plan-copy"
119
+ className="inline-flex h-5 items-center gap-1 rounded px-1.5 text-[11px] text-amber-800/80 transition-colors hover:bg-amber-400/20 hover:text-amber-900 dark:text-amber-200/80 dark:hover:text-amber-100"
120
+ >
121
+ {copied ? (
122
+ <>
123
+ <LuCheck className="h-3 w-3 shrink-0" />
124
+ <span>{t('Copied')}</span>
125
+ </>
126
+ ) : (
127
+ <>
128
+ <LuCopy className="h-3 w-3 shrink-0" />
129
+ <span className="hidden sm:inline">{t('Copy plan')}</span>
130
+ </>
131
+ )}
132
+ </button>
133
+ )}
86
134
  </div>
87
- {items.length > 0 && (
88
- <ol className="m-0 list-none space-y-1 px-3 py-2">
89
- {items.map((item, idx) => (
90
- <li key={idx} className="flex items-start gap-2 text-[13px] leading-relaxed">
91
- {item.done ? (
92
- <LuCircleCheck className="mt-[3px] h-3.5 w-3.5 shrink-0 text-amber-600 dark:text-amber-400" />
93
- ) : (
94
- <LuCircle className="mt-[3px] h-3.5 w-3.5 shrink-0 text-amber-500/60" />
95
- )}
96
- <span
97
- className={
98
- item.done
99
- ? 'text-agent-muted-foreground line-through'
100
- : 'text-agent-foreground'
101
- }
102
- >
103
- {item.text}
104
- </span>
105
- </li>
106
- ))}
107
- </ol>
135
+
136
+ {hasRichMarkdown && renderRichMarkdown && bodyMarkdown ? (
137
+ <div className="px-3 py-2.5 text-[12.5px] leading-relaxed text-agent-foreground [&_pre]:bg-agent-canvas/90">
138
+ {renderRichMarkdown(bodyMarkdown)}
139
+ </div>
140
+ ) : (
141
+ <>
142
+ {items.length > 0 && (
143
+ <ol className="m-0 list-none space-y-1 px-3 py-2">
144
+ {items.map((item, idx) => (
145
+ <li key={idx} className="flex items-start gap-2 text-[13px] leading-relaxed">
146
+ {item.done ? (
147
+ <LuCircleCheck className="mt-[3px] h-3.5 w-3.5 shrink-0 text-amber-600 dark:text-amber-400" />
148
+ ) : (
149
+ <LuCircle className="mt-[3px] h-3.5 w-3.5 shrink-0 text-amber-500/60" />
150
+ )}
151
+ <span
152
+ className={
153
+ item.done
154
+ ? 'text-agent-muted-foreground line-through'
155
+ : 'text-agent-foreground'
156
+ }
157
+ >
158
+ {item.text}
159
+ </span>
160
+ </li>
161
+ ))}
162
+ </ol>
163
+ )}
164
+ {notes.length > 0 && (
165
+ <div className="border-t border-amber-400/20 px-3 py-1.5 text-[12px] text-agent-muted-foreground">
166
+ {notes.map((note, idx) => (
167
+ <p key={idx} className="my-0.5">
168
+ {note}
169
+ </p>
170
+ ))}
171
+ </div>
172
+ )}
173
+ </>
108
174
  )}
109
- {notes.length > 0 && (
110
- <div className="border-t border-amber-400/20 px-3 py-1.5 text-[12px] text-agent-muted-foreground">
111
- {notes.map((note, idx) => (
112
- <p key={idx} className="my-0.5">
113
- {note}
114
- </p>
115
- ))}
175
+
176
+ {showActionFooter && planActionCtx && currentMessageId && (
177
+ <div
178
+ className="flex flex-wrap items-center justify-between gap-2 border-t border-amber-400/30 bg-amber-400/10 px-3 py-2 text-xs dark:border-amber-500/20"
179
+ data-testid="plan-action-bar"
180
+ >
181
+ <div className="flex min-w-0 items-center gap-2 text-amber-800 dark:text-amber-200">
182
+ <span className="font-medium">
183
+ {t('Plan ready. How would you like to proceed?')}
184
+ </span>
185
+ {contextUsedPercent !== null && contextUsedPercent >= 25 && (
186
+ <span className="rounded-full bg-amber-400/20 px-1.5 py-0.5 text-[10px] text-amber-700 dark:text-amber-300">
187
+ {t('{percent}% context used', { percent: contextUsedPercent })}
188
+ </span>
189
+ )}
190
+ </div>
191
+ <div className="flex flex-wrap items-center gap-1.5">
192
+ <button
193
+ type="button"
194
+ onClick={() => planActionCtx.onDismiss(currentMessageId)}
195
+ className="rounded-full px-2.5 py-1 text-agent-muted-foreground transition-colors hover:bg-agent-foreground/5 hover:text-agent-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-amber-500/50"
196
+ data-testid="plan-dismiss"
197
+ >
198
+ {t('Keep refining')}
199
+ </button>
200
+ {planActionCtx.onExecuteInFreshChat && markdown && (
201
+ <button
202
+ type="button"
203
+ onClick={() => planActionCtx.onExecuteInFreshChat?.(markdown)}
204
+ title={t('Start a fresh chat in Agent mode with only this approved plan')}
205
+ className="inline-flex items-center gap-1 rounded-full border border-amber-500/40 bg-agent-canvas/80 px-2.5 py-1 font-medium text-amber-800 transition-colors hover:bg-amber-400/20 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-amber-500/50 dark:border-amber-400/35 dark:text-amber-200"
206
+ data-testid="plan-execute-fresh"
207
+ >
208
+ <LuSquarePlus className="h-3.5 w-3.5 shrink-0" />
209
+ <span>{t('Execute in new chat')}</span>
210
+ </button>
211
+ )}
212
+ <button
213
+ type="button"
214
+ onClick={planActionCtx.onExecuteInPlace}
215
+ className="inline-flex items-center gap-1 rounded-full bg-agent-foreground px-3 py-1 font-medium text-agent-canvas transition hover:opacity-90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-amber-500/50"
216
+ data-testid="plan-execute"
217
+ >
218
+ <span>{t('Execute plan')}</span>
219
+ <LuArrowRight className="h-3.5 w-3.5 shrink-0" />
220
+ </button>
221
+ </div>
116
222
  </div>
117
223
  )}
118
224
  </div>
@@ -0,0 +1,241 @@
1
+ import { createContext, useContext } from 'react';
2
+ import {
3
+ extractLatestProposedPlan,
4
+ type ParsedProposedPlan,
5
+ } from '@steerable/agent-protocol';
6
+ import { clampWebChatMode, getWebChatModes, type ChatModeId } from './host-tools';
7
+
8
+ const CHAT_MODE_SESSION_STORAGE_KEY = 'steerable:chat-mode-by-id:v1';
9
+ const DISMISSED_PLANS_STORAGE_KEY = 'steerable:dismissed-plan-msgs:v1';
10
+ const MAX_STORED_ENTRIES = 100;
11
+
12
+ function readSessionMap(): Record<string, ChatModeId> {
13
+ if (typeof sessionStorage === 'undefined') return {};
14
+ try {
15
+ const raw = sessionStorage.getItem(CHAT_MODE_SESSION_STORAGE_KEY);
16
+ if (!raw) return {};
17
+ const parsed = JSON.parse(raw) as unknown;
18
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return {};
19
+ const out: Record<string, ChatModeId> = {};
20
+ for (const [k, v] of Object.entries(parsed as Record<string, unknown>)) {
21
+ if (v === 'plan' || v === 'agent') {
22
+ out[k] = v;
23
+ }
24
+ }
25
+ return out;
26
+ } catch {
27
+ return {};
28
+ }
29
+ }
30
+
31
+ function writeSessionMap(map: Record<string, ChatModeId>): void {
32
+ if (typeof sessionStorage === 'undefined') return;
33
+ try {
34
+ const entries = Object.entries(map);
35
+ const trimmed =
36
+ entries.length > MAX_STORED_ENTRIES
37
+ ? Object.fromEntries(entries.slice(entries.length - MAX_STORED_ENTRIES))
38
+ : map;
39
+ sessionStorage.setItem(CHAT_MODE_SESSION_STORAGE_KEY, JSON.stringify(trimmed));
40
+ } catch {
41
+ // Ignore storage quota errors in private browsing contexts.
42
+ }
43
+ }
44
+
45
+ function extractMessageMode(messageMetadata: unknown): ChatModeId | null {
46
+ if (!messageMetadata) return null;
47
+ try {
48
+ const parsed =
49
+ typeof messageMetadata === 'string'
50
+ ? (JSON.parse(messageMetadata) as Record<string, unknown>)
51
+ : (messageMetadata as Record<string, unknown>);
52
+ if (parsed?.mode === 'plan') return 'plan';
53
+ if (parsed?.mode === 'agent') return 'agent';
54
+ } catch {
55
+ // Ignore malformed historical metadata.
56
+ }
57
+ return null;
58
+ }
59
+
60
+ /**
61
+ * Resolve the initial chat mode for a specific `chatId` without cross-chat leakage.
62
+ * New chats always default to `'agent'`; existing chats restore their session-scoped
63
+ * selection or infer from the latest persisted user message metadata.
64
+ */
65
+ export function readChatModeForSession(
66
+ chatId: string,
67
+ messages?: ReadonlyArray<{ role: string; messageMetadata?: unknown }>,
68
+ ): ChatModeId {
69
+ if (chatId) {
70
+ const map = readSessionMap();
71
+ const saved = map[chatId];
72
+ if (saved) return clampWebChatMode(saved);
73
+ }
74
+ if (messages && messages.length > 0) {
75
+ for (let i = messages.length - 1; i >= 0; i--) {
76
+ const msg = messages[i]!;
77
+ if (msg.role !== 'user') continue;
78
+ const msgMode = extractMessageMode(msg.messageMetadata);
79
+ return clampWebChatMode(msgMode ?? 'agent');
80
+ }
81
+ }
82
+ return clampWebChatMode('agent');
83
+ }
84
+
85
+ export function writeChatModeForSession(chatId: string, mode: ChatModeId): void {
86
+ if (!chatId) return;
87
+ const map = readSessionMap();
88
+ map[chatId] = clampWebChatMode(mode);
89
+ writeSessionMap(map);
90
+ }
91
+
92
+ export function clearChatModeStoreForTests(): void {
93
+ if (typeof sessionStorage === 'undefined') return;
94
+ sessionStorage.removeItem(CHAT_MODE_SESSION_STORAGE_KEY);
95
+ sessionStorage.removeItem(DISMISSED_PLANS_STORAGE_KEY);
96
+ }
97
+
98
+ function readDismissedSet(): Set<string> {
99
+ if (typeof sessionStorage === 'undefined') return new Set();
100
+ try {
101
+ const raw = sessionStorage.getItem(DISMISSED_PLANS_STORAGE_KEY);
102
+ if (!raw) return new Set();
103
+ const parsed = JSON.parse(raw) as unknown;
104
+ if (!Array.isArray(parsed)) return new Set();
105
+ return new Set(parsed.filter((item): item is string => typeof item === 'string'));
106
+ } catch {
107
+ return new Set();
108
+ }
109
+ }
110
+
111
+ export function isPlanMessageDismissed(chatId: string, messageId: string): boolean {
112
+ if (!chatId || !messageId) return false;
113
+ return readDismissedSet().has(`${chatId}:${messageId}`);
114
+ }
115
+
116
+ export function dismissPlanMessage(chatId: string, messageId: string): void {
117
+ if (!chatId || !messageId || typeof sessionStorage === 'undefined') return;
118
+ try {
119
+ const current = Array.from(readDismissedSet());
120
+ const key = `${chatId}:${messageId}`;
121
+ if (!current.includes(key)) current.push(key);
122
+ const trimmed =
123
+ current.length > MAX_STORED_ENTRIES
124
+ ? current.slice(current.length - MAX_STORED_ENTRIES)
125
+ : current;
126
+ sessionStorage.setItem(DISMISSED_PLANS_STORAGE_KEY, JSON.stringify(trimmed));
127
+ } catch {
128
+ // Ignore storage quota errors.
129
+ }
130
+ }
131
+
132
+ export interface ParsedModeSlashCommand {
133
+ targetMode: ChatModeId;
134
+ remainder: string;
135
+ }
136
+
137
+ /**
138
+ * Parse built-in `/plan` and `/agent` composer commands:
139
+ * - `/plan` -> switch to Plan mode without sending
140
+ * - `/plan off` -> switch to Agent mode without sending
141
+ * - `/plan <goal>` -> switch to Plan mode and submit `<goal>` in Plan mode
142
+ * - `/agent` -> switch to Agent mode without sending
143
+ * - `/agent <task>` -> switch to Agent mode and submit `<task>` in Agent mode
144
+ */
145
+ export function parseModeSlashCommand(rawText: string): ParsedModeSlashCommand | null {
146
+ if (!getWebChatModes().includes('plan')) return null;
147
+ const trimmed = rawText.trim();
148
+ const planMatch = trimmed.match(/^\/plan(?:\s+([\s\S]*))?$/i);
149
+ if (planMatch) {
150
+ const rest = (planMatch[1] ?? '').trim();
151
+ if (rest.toLowerCase() === 'off') {
152
+ return { targetMode: 'agent', remainder: '' };
153
+ }
154
+ return { targetMode: 'plan', remainder: rest };
155
+ }
156
+ const agentMatch = trimmed.match(/^\/agent(?:\s+([\s\S]*))?$/i);
157
+ if (agentMatch) {
158
+ const rest = (agentMatch[1] ?? '').trim();
159
+ return { targetMode: 'agent', remainder: rest };
160
+ }
161
+ return null;
162
+ }
163
+
164
+ export interface ActionablePlanState {
165
+ messageId: string;
166
+ plan: ParsedProposedPlan;
167
+ contextUsedPercent: number | null;
168
+ }
169
+
170
+ export function resolveActionablePlan(input: {
171
+ chatId: string;
172
+ messages: ReadonlyArray<{
173
+ id: string;
174
+ role: string;
175
+ content: string;
176
+ messageMetadata?: unknown;
177
+ }>;
178
+ isStreaming: boolean;
179
+ interrupted?: boolean;
180
+ dismissedIds?: ReadonlySet<string>;
181
+ contextUsedPercent?: number | null;
182
+ }): ActionablePlanState | null {
183
+ const { chatId, messages, isStreaming, interrupted = false, dismissedIds, contextUsedPercent = null } =
184
+ input;
185
+ if (isStreaming || interrupted || messages.length === 0) return null;
186
+ if (!getWebChatModes().includes('plan')) return null;
187
+
188
+ const lastMessage = messages[messages.length - 1]!;
189
+ if (lastMessage.role !== 'assistant' || !lastMessage.content) return null;
190
+
191
+ if (dismissedIds?.has(lastMessage.id) || isPlanMessageDismissed(chatId, lastMessage.id)) {
192
+ return null;
193
+ }
194
+
195
+ // Skip turns that recorded a terminal failure or user cancellation in metadata.
196
+ if (lastMessage.messageMetadata) {
197
+ try {
198
+ const meta =
199
+ typeof lastMessage.messageMetadata === 'string'
200
+ ? (JSON.parse(lastMessage.messageMetadata) as Record<string, unknown>)
201
+ : (lastMessage.messageMetadata as Record<string, unknown>);
202
+ if (
203
+ meta?.turnFailure ||
204
+ meta?.stopped === true ||
205
+ meta?.status === 'failed' ||
206
+ meta?.status === 'cancelled'
207
+ ) {
208
+ return null;
209
+ }
210
+ } catch {
211
+ // Ignore malformed metadata.
212
+ }
213
+ }
214
+
215
+ const plan = extractLatestProposedPlan(lastMessage.content);
216
+ if (!plan || !plan.complete) return null;
217
+
218
+ return {
219
+ messageId: lastMessage.id,
220
+ plan,
221
+ contextUsedPercent,
222
+ };
223
+ }
224
+
225
+ export interface PlanActionContextValue {
226
+ actionable: ActionablePlanState | null;
227
+ onExecuteInPlace: () => void;
228
+ onExecuteInFreshChat?: (planMarkdown: string) => void;
229
+ onDismiss: (messageId: string) => void;
230
+ }
231
+
232
+ export const PlanActionContext = createContext<PlanActionContextValue | null>(null);
233
+ export const CurrentMessageIdContext = createContext<string | null>(null);
234
+
235
+ export function usePlanActionContext(): PlanActionContextValue | null {
236
+ return useContext(PlanActionContext);
237
+ }
238
+
239
+ export function useCurrentMessageId(): string | null {
240
+ return useContext(CurrentMessageIdContext);
241
+ }