@steerable/agent-shell-web 0.14.2 → 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.
@@ -51,7 +51,6 @@ import {
51
51
  import { useChatTasks } from "@/components/chat/useChatTasks";
52
52
  import { useGoalAndLoops } from "@/components/chat/useGoalAndLoops";
53
53
  import { GoalLoopStatusBar } from "@/components/chat/GoalLoopStatusBar";
54
- import { LuListChecks, LuArrowRight } from "react-icons/lu";
55
54
  import { LocalLlmSettingsModal } from "@/components/LocalLlmSettingsModal";
56
55
  import {
57
56
  ChatProjectBadge,
@@ -60,10 +59,19 @@ import {
60
59
  import { ProjectTrustBanner } from "@/components/chat/ProjectTrustBanner";
61
60
  import {
62
61
  compactChat,
62
+ getChatContextStatus,
63
63
  getChatLiveStream,
64
64
  type ChatLiveStream,
65
65
  type LocalChatMessage,
66
66
  } from "@/lib/local-api";
67
+ import {
68
+ dismissPlanMessage,
69
+ parseModeSlashCommand,
70
+ PlanActionContext,
71
+ readChatModeForSession,
72
+ resolveActionablePlan,
73
+ writeChatModeForSession,
74
+ } from "@/lib/chat-mode-store";
67
75
  import { useProjects } from "@/hooks/useProjects";
68
76
  import type { AgentOutletContext } from "@/layouts/AgentLayout";
69
77
  import {
@@ -107,13 +115,6 @@ function chronological(messages: ChatMessage[] | undefined): ChatMessage[] {
107
115
 
108
116
  type ChatMessageWithMetadata = ChatMessage & LocalChatMessage;
109
117
 
110
- const CHAT_MODE_STORAGE_KEY = "agent-chat-mode";
111
-
112
- function readStoredMode(): ChatMode {
113
- if (typeof localStorage === "undefined") return clampWebChatMode("agent");
114
- return clampWebChatMode(localStorage.getItem(CHAT_MODE_STORAGE_KEY));
115
- }
116
-
117
118
  interface ComposerTurnSettings {
118
119
  execPolicy: ExecPolicy;
119
120
  mode: ChatMode;
@@ -124,6 +125,8 @@ interface ComposerTurnSettings {
124
125
  /**
125
126
  * 排队和插队失败后的新回合不经过输入框的正常提交,这里在真正开流时
126
127
  * 补上当前输入框的命令沙箱、模式、模型和编排开关。
128
+ * 若输入本轮显式携带了 `metadata.mode`(例如 `/plan <任务>` 或新对话落地页继承),
129
+ * 优先尊重输入本轮的显式模式,否则回退到当前输入框的 `settings.mode`。
127
130
  */
128
131
  function applyComposerTurnSettings<T extends { metadata?: Record<string, unknown> }>(
129
132
  input: T,
@@ -131,7 +134,12 @@ function applyComposerTurnSettings<T extends { metadata?: Record<string, unknown
131
134
  ): T {
132
135
  const metadata: Record<string, unknown> = { ...(input.metadata ?? {}) };
133
136
  metadata.execPolicy = settings.execPolicy;
134
- if (settings.mode === "plan") metadata.mode = "plan";
137
+ const explicitMode = input.metadata?.mode;
138
+ const effectiveMode =
139
+ explicitMode === "plan" || explicitMode === "agent"
140
+ ? explicitMode
141
+ : settings.mode;
142
+ if (effectiveMode === "plan") metadata.mode = "plan";
135
143
  else delete metadata.mode;
136
144
  if (settings.modelOverride) metadata.model = settings.modelOverride;
137
145
  if (settings.effortOverride) metadata.reasoningEffort = settings.effortOverride;
@@ -443,6 +451,7 @@ function AgentChatLoader({
443
451
 
444
452
  return (
445
453
  <AgentChatView
454
+ key={chatId}
446
455
  chatId={chatId}
447
456
  initialMessages={initialMessages}
448
457
  initialExecutedActions={initialExecutedActions}
@@ -506,10 +515,14 @@ function AgentChatView({
506
515
  const chatProject = chat?.projectId
507
516
  ? (projects.find((p) => p.id === chat.projectId) ?? null)
508
517
  : null;
518
+ const initialSessionMode = useMemo(
519
+ () => readChatModeForSession(chatId, initialMessages),
520
+ [chatId, initialMessages],
521
+ );
509
522
  // 插队 / 排队在开流或注入时读这里,而不是排队那一刻的闭包。
510
523
  const composerSettingsRef = useRef<ComposerTurnSettings>({
511
524
  execPolicy: readStoredExecPolicy(),
512
- mode: readStoredMode(),
525
+ mode: initialSessionMode,
513
526
  modelOverride: null,
514
527
  effortOverride: null,
515
528
  });
@@ -661,13 +674,12 @@ function AgentChatView({
661
674
  // the DB-id keyed copy for history after refresh.
662
675
  const pendingActionsRef = useRef<ExecutedAction[]>([]);
663
676
 
664
- // ── Plan 模式(类 Cursor "先出计划")────────────────────────────────────
665
- // mode 持久化到 localStorage,跨对话/刷新保留用户偏好。planReady 控制"开始
666
- // 执行计划"操作条:当一轮 plan 模式回复结束后置为 true。
667
- const [mode, setMode] = useState<ChatMode>(readStoredMode);
677
+ // ── Plan 模式(对标 Codex:会话级状态隔离 + 结构化 <proposed_plan> 识别)──
678
+ // mode 按 chatId 隔离存储在 sessionStorage(不跨会话串台,刷新后按会话消息恢复)。
679
+ const [mode, setMode] = useState<ChatMode>(initialSessionMode);
668
680
  const [execPolicy, setExecPolicy] = useState<ExecPolicy>(readStoredExecPolicy);
669
- const [planReady, setPlanReady] = useState(false);
670
- const planTurnRef = useRef(false);
681
+ const [dismissedPlanVersion, setDismissedPlanVersion] = useState(0);
682
+ const [planContextPercent, setPlanContextPercent] = useState<number | null>(null);
671
683
  const wasStreamingRef = useRef(false);
672
684
  const [suggestedReplies, setSuggestedReplies] =
673
685
  useState<SuggestedRepliesState | null>(initialSuggestedReplies);
@@ -675,13 +687,18 @@ function AgentChatView({
675
687
  initialSuggestedReplies?.messageId ?? null,
676
688
  );
677
689
 
678
- const handleModeChange = useCallback((next: ChatMode) => {
679
- const clamped = clampWebChatMode(next);
680
- setMode(clamped);
681
- if (typeof localStorage !== "undefined") {
682
- localStorage.setItem(CHAT_MODE_STORAGE_KEY, clamped);
683
- }
684
- }, []);
690
+ const handleModeChange = useCallback(
691
+ (next: ChatMode) => {
692
+ const clamped = clampWebChatMode(next);
693
+ composerSettingsRef.current = {
694
+ ...composerSettingsRef.current,
695
+ mode: clamped,
696
+ };
697
+ setMode(clamped);
698
+ writeChatModeForSession(chatId, clamped);
699
+ },
700
+ [chatId],
701
+ );
685
702
 
686
703
  const handleExecPolicyChange = useCallback((next: ExecPolicy) => {
687
704
  setExecPolicy(next);
@@ -990,15 +1007,10 @@ function AgentChatView({
990
1007
  // turn_active 标记已随回复落库清除,重新加载不会再报)。
991
1008
  const [interrupted, setInterrupted] = useState(initialInterrupted);
992
1009
 
993
- // 监听 streaming 结束沿:若刚结束的这一轮是 plan 模式,展示"开始执行计划"操作条。
994
- // 同时冻结本轮墙钟,写进 durationByMessageId(占位 id + 落库 id),折叠条
995
- // 才能在刷新前显示「工作了 …」。
1010
+ // 监听 streaming 结束沿:冻结本轮墙钟,写进 durationByMessageId(占位 id + 落库 id),
1011
+ // 折叠条才能在刷新前显示「工作了 …」。
996
1012
  useEffect(() => {
997
1013
  if (wasStreamingRef.current && !isStreaming) {
998
- if (planTurnRef.current) {
999
- setPlanReady(true);
1000
- planTurnRef.current = false;
1001
- }
1002
1014
  const started = turnStartedAtRef.current;
1003
1015
  if (started != null) {
1004
1016
  const elapsed = Math.max(0, Date.now() - started);
@@ -1100,9 +1112,6 @@ function AgentChatView({
1100
1112
  pendingDurationMessageIdRef.current = null;
1101
1113
  currentLlmSpeedRef.current = null;
1102
1114
  setCurrentLlmSpeed(undefined);
1103
- // 新一轮开始:记录本轮是否为 plan 模式,并隐藏上一份计划的操作条。
1104
- planTurnRef.current = input.metadata?.mode === "plan";
1105
- setPlanReady(false);
1106
1115
  // 手动发起新一轮即取代中断态——用户已经继续往前走了。
1107
1116
  setInterrupted(false);
1108
1117
  setSuggestedReplies(null);
@@ -1308,8 +1317,6 @@ function AgentChatView({
1308
1317
  pendingDurationMessageIdRef.current = null;
1309
1318
  currentLlmSpeedRef.current = null;
1310
1319
  setCurrentLlmSpeed(undefined);
1311
- planTurnRef.current = mode === "plan";
1312
- setPlanReady(false);
1313
1320
  const metadata = {
1314
1321
  ...(mode === "plan" ? { mode: "plan" as const } : {}),
1315
1322
  ...(execPolicy === "full" ? { execPolicy: "full" as const } : {}),
@@ -1464,19 +1471,76 @@ function AgentChatView({
1464
1471
  : null;
1465
1472
  if (pendingModel) setModelOverride(pendingModel);
1466
1473
  if (pendingEffort) setEffortOverride(pendingEffort);
1474
+ if (pending.metadata?.mode === "plan") {
1475
+ handleModeChange("plan");
1476
+ }
1467
1477
  void handleSubmit({
1468
1478
  content: pending.content,
1469
1479
  metadata: pending.metadata,
1470
1480
  });
1471
- }, [chatId, handleSubmit]);
1481
+ }, [chatId, handleSubmit, handleModeChange]);
1472
1482
 
1473
- // "开始执行计划":切回 agent 模式并自动发送执行指令,恢复全量工具。
1483
+ // 当前会话执行计划:切回 Agent 模式并在原会话下发确认执行指令(完整复用探索上下文)。
1474
1484
  const handleExecutePlan = useCallback(() => {
1475
1485
  handleModeChange("agent");
1476
- setPlanReady(false);
1477
1486
  void handleSubmit({ content: t("Start executing the plan above.") });
1478
1487
  }, [handleModeChange, handleSubmit]);
1479
1488
 
1489
+ // 新对话执行计划(对标 Codex Clear context & implement):
1490
+ // 继承当前项目与所选 Agent 创建全新会话,设为 Agent 模式,仅携带审批通过的计划正文开始执行。
1491
+ const handleExecutePlanInFreshChat = useCallback(
1492
+ async (planMarkdown: string) => {
1493
+ try {
1494
+ const newId = await ctx.createChat({
1495
+ ...(chat?.projectId && showProjectsChrome
1496
+ ? { projectId: chat.projectId }
1497
+ : {}),
1498
+ ...(ctx.selectedAgentId ? { agentId: ctx.selectedAgentId } : {}),
1499
+ });
1500
+ if (!newId) {
1501
+ setNewChatError(t("Failed to create the chat. Please try again."));
1502
+ return;
1503
+ }
1504
+ writeChatModeForSession(newId, "agent");
1505
+ const metadata = {
1506
+ ...(execPolicy === "full" ? { execPolicy: "full" as const } : {}),
1507
+ ...(ctx.selectedAgentId ? { agentId: ctx.selectedAgentId } : {}),
1508
+ ...(modelOverride ? { model: modelOverride } : {}),
1509
+ ...(effortOverride ? { reasoningEffort: effortOverride } : {}),
1510
+ };
1511
+ setPendingFirstMessage({
1512
+ chatId: newId,
1513
+ content: `${t("Implement the following approved plan:")}\n\n${planMarkdown}`,
1514
+ metadata: Object.keys(metadata).length > 0 ? metadata : undefined,
1515
+ });
1516
+ navigate(`/agent/${newId}`);
1517
+ } catch (err) {
1518
+ setNewChatError(err instanceof Error ? err.message : String(err));
1519
+ }
1520
+ },
1521
+ [
1522
+ ctx,
1523
+ chat?.projectId,
1524
+ showProjectsChrome,
1525
+ execPolicy,
1526
+ modelOverride,
1527
+ effortOverride,
1528
+ navigate,
1529
+ ],
1530
+ );
1531
+
1532
+ // 继续打磨计划:收起当前计划消息的操作栏(保持在 Plan 模式),聚焦输入框继续补充约束。
1533
+ const handleDismissPlan = useCallback(
1534
+ (messageId: string) => {
1535
+ dismissPlanMessage(chatId, messageId);
1536
+ setDismissedPlanVersion((v) => v + 1);
1537
+ requestAnimationFrame(() => {
1538
+ (document.querySelector('[data-testid="chat-input"]') as HTMLElement | null)?.focus();
1539
+ });
1540
+ },
1541
+ [chatId],
1542
+ );
1543
+
1480
1544
  // 分享当前对话:截取整个聊天面板区域(含 header + 消息 + 输入框),
1481
1545
  // 由主进程 capturePage 后写入系统剪贴板,用户可直接粘贴到任何地方。
1482
1546
  const handleShare = useCallback(async (): Promise<boolean> => {
@@ -1603,7 +1667,71 @@ function AgentChatView({
1603
1667
  );
1604
1668
  };
1605
1669
 
1670
+ const actionablePlan = useMemo(() => {
1671
+ void dismissedPlanVersion;
1672
+ return resolveActionablePlan({
1673
+ chatId,
1674
+ messages: effectiveMessages,
1675
+ isStreaming: effectiveIsStreaming,
1676
+ interrupted,
1677
+ contextUsedPercent: planContextPercent,
1678
+ });
1679
+ }, [
1680
+ chatId,
1681
+ effectiveMessages,
1682
+ effectiveIsStreaming,
1683
+ interrupted,
1684
+ planContextPercent,
1685
+ dismissedPlanVersion,
1686
+ ]);
1687
+
1688
+ useEffect(() => {
1689
+ if (!actionablePlan || !hasHostBridge()) {
1690
+ setPlanContextPercent(null);
1691
+ return;
1692
+ }
1693
+ let cancelled = false;
1694
+ void (async () => {
1695
+ try {
1696
+ const status = await getChatContextStatus(chatId);
1697
+ if (cancelled || !status) return;
1698
+ const maxTokens = status.maxContextTokens || 131_072;
1699
+ const pct = Math.max(
1700
+ 0,
1701
+ Math.min(100, Math.round((status.estimatedTokens / maxTokens) * 100)),
1702
+ );
1703
+ setPlanContextPercent(pct);
1704
+ } catch {
1705
+ if (!cancelled) setPlanContextPercent(null);
1706
+ }
1707
+ })();
1708
+ return () => {
1709
+ cancelled = true;
1710
+ };
1711
+ }, [actionablePlan?.messageId, chatId]);
1712
+
1713
+ const planActionContextValue = useMemo(
1714
+ () =>
1715
+ actionablePlan
1716
+ ? {
1717
+ actionable: actionablePlan,
1718
+ onExecuteInPlace: handleExecutePlan,
1719
+ onExecuteInFreshChat: (planMd: string) => {
1720
+ void handleExecutePlanInFreshChat(planMd);
1721
+ },
1722
+ onDismiss: handleDismissPlan,
1723
+ }
1724
+ : null,
1725
+ [
1726
+ actionablePlan,
1727
+ handleExecutePlan,
1728
+ handleExecutePlanInFreshChat,
1729
+ handleDismissPlan,
1730
+ ],
1731
+ );
1732
+
1606
1733
  return (
1734
+ <PlanActionContext.Provider value={planActionContextValue}>
1607
1735
  <div className="flex h-full w-full flex-col">
1608
1736
  {hydrationError && (
1609
1737
  <div className="border-b border-agent-border bg-agent-muted/60 px-2.5 py-1 text-xs text-agent-destructive">
@@ -1692,7 +1820,7 @@ function AgentChatView({
1692
1820
  : undefined
1693
1821
  }
1694
1822
  inputToolbarExtras={
1695
- <div className="inline-flex items-center gap-1.5">
1823
+ <div className="inline-flex min-w-0 items-center gap-1">
1696
1824
  <ModelPicker
1697
1825
  model={modelOverride}
1698
1826
  reasoningEffort={effortOverride}
@@ -1709,7 +1837,6 @@ function AgentChatView({
1709
1837
  chatId={chatId}
1710
1838
  messageCount={effectiveMessages.length}
1711
1839
  isStreaming={effectiveIsStreaming}
1712
- livePromptTokens={currentTurnUsage?.promptTokens}
1713
1840
  liveCachedPromptTokens={currentTurnUsage?.cachedPromptTokens}
1714
1841
  onCompacted={() => onBranchTick()}
1715
1842
  />
@@ -1768,35 +1895,6 @@ function AgentChatView({
1768
1895
  onTrustChanged={fetchProjects}
1769
1896
  />
1770
1897
  ) : null}
1771
- {planReady && !isStreaming ? (
1772
- <div className="mx-2.5 mb-1 flex items-center justify-between gap-2 rounded-agent-md border border-amber-400/50 bg-amber-400/10 px-2.5 py-1.5 text-xs">
1773
- <div className="flex items-center gap-2 text-amber-700 dark:text-amber-300">
1774
- <LuListChecks className="h-4 w-4 shrink-0" />
1775
- <span>
1776
- {t("The plan is ready. Once it looks right, switch to Agent mode to execute it.")}
1777
- </span>
1778
- </div>
1779
- <div className="flex items-center gap-2">
1780
- <button
1781
- type="button"
1782
- onClick={() => setPlanReady(false)}
1783
- className="rounded-full px-2 py-1 text-agent-muted-foreground transition-colors hover:text-agent-foreground"
1784
- data-testid="plan-dismiss"
1785
- >
1786
- {t("Dismiss")}
1787
- </button>
1788
- <button
1789
- type="button"
1790
- onClick={handleExecutePlan}
1791
- 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"
1792
- data-testid="plan-execute"
1793
- >
1794
- {t("Execute plan")}
1795
- <LuArrowRight className="h-3.5 w-3.5" />
1796
- </button>
1797
- </div>
1798
- </div>
1799
- ) : null}
1800
1898
  </>
1801
1899
  }
1802
1900
  />
@@ -1809,6 +1907,7 @@ function AgentChatView({
1809
1907
  {/* W4-1 审批弹窗挂在 AgentLayout(回合不因页面切换而暂停,
1810
1908
  模态必须跨路由可渲染)。 */}
1811
1909
  </div>
1910
+ </PlanActionContext.Provider>
1812
1911
  );
1813
1912
  }
1814
1913
 
@@ -1833,7 +1932,7 @@ function EmptyChatGate() {
1833
1932
  const [mentionReferences, setMentionReferences] = useState<
1834
1933
  MentionReference[]
1835
1934
  >([]);
1836
- const [mode, setMode] = useState<ChatMode>(readStoredMode);
1935
+ const [mode, setMode] = useState<ChatMode>(() => clampWebChatMode("agent"));
1837
1936
  const [execPolicy, setExecPolicy] = useState<ExecPolicy>(readStoredExecPolicy);
1838
1937
  const [modelOverride, setModelOverride] = useState<string | null>(null);
1839
1938
  const [effortOverride, setEffortOverride] = useState<string | null>(null);
@@ -1864,11 +1963,7 @@ function EmptyChatGate() {
1864
1963
  null;
1865
1964
 
1866
1965
  const handleModeChange = useCallback((next: ChatMode) => {
1867
- const clamped = clampWebChatMode(next);
1868
- setMode(clamped);
1869
- if (typeof localStorage !== "undefined") {
1870
- localStorage.setItem(CHAT_MODE_STORAGE_KEY, clamped);
1871
- }
1966
+ setMode(clampWebChatMode(next));
1872
1967
  }, []);
1873
1968
 
1874
1969
  const handleExecPolicyChange = useCallback((next: ExecPolicy) => {
@@ -1886,8 +1981,18 @@ function EmptyChatGate() {
1886
1981
  const submitPrompt = useCallback(
1887
1982
  async (rawText: string, overrideMode?: ChatMode) => {
1888
1983
  if (isCreating) return;
1889
- const trimmed = rawText.trim();
1890
- const effectiveMode = overrideMode ?? mode;
1984
+ let trimmed = rawText.trim();
1985
+ let effectiveMode = overrideMode ?? mode;
1986
+ const slashCmd = !overrideMode && trimmed ? parseModeSlashCommand(trimmed) : null;
1987
+ if (slashCmd) {
1988
+ effectiveMode = clampWebChatMode(slashCmd.targetMode);
1989
+ setMode(effectiveMode);
1990
+ if (!slashCmd.remainder && files.length === 0) {
1991
+ setInputValue("");
1992
+ return;
1993
+ }
1994
+ trimmed = slashCmd.remainder;
1995
+ }
1891
1996
  if (!trimmed && files.length === 0) return;
1892
1997
  trackBehavior('composer_send', {
1893
1998
  empty: false,
@@ -1944,6 +2049,7 @@ function EmptyChatGate() {
1944
2049
  ...(imageAttachments.length > 0 ? { images: imageAttachments } : {}),
1945
2050
  };
1946
2051
 
2052
+ writeChatModeForSession(id, effectiveMode);
1947
2053
  setPendingFirstMessage({
1948
2054
  chatId: id,
1949
2055
  content,
@@ -12,6 +12,10 @@
12
12
  */
13
13
  @import "tailwindcss";
14
14
 
15
+ /* Mirror `darkMode: 'class'` from `@steerable/agent-ui/tailwind-preset` so OS dark mode
16
+ * (`prefers-color-scheme: dark`) never triggers `dark:*` utilities on the light canvas. */
17
+ @custom-variant dark (&:where(.dark, .dark *));
18
+
15
19
  @source "../**/*.{ts,tsx}";
16
20
  @source "../../node_modules/@steerable/agent-ui/dist/**/*.js";
17
21
 
@@ -72,14 +76,13 @@ body {
72
76
  .markdown-content > :last-child { margin-bottom: 0; }
73
77
 
74
78
  /*
75
- * ToolExecutionCard header: CJK status labels (已完成 / 失败 / …) wrap at
76
- * every character when the flex row is squeezed. Keep the trailing status
77
- * cluster at content width; let the truncated summary take the leftover.
79
+ * ToolExecutionCard header: CJK status labels wrap at every character when
80
+ * the flex row is squeezed. Keep the trailing status cluster at content width;
81
+ * let the truncated summary take the leftover.
78
82
  *
79
83
  * WKWebView (Tauri) lays out flex items of a <button> in the border box, so
80
- * padding-right on that button does not inset 「已完成」. Clear that padding
81
- * and inset the status with margin. The card also puts the same inset on an
82
- * inner span; these direct-child rules only match the older button markup.
84
+ * horizontal padding lives on the inner span inside ToolExecutionCard; clear
85
+ * UA inline padding on header buttons directly.
83
86
  */
84
87
  .steerable-tool-execution span.truncate {
85
88
  min-width: 0;
@@ -91,30 +94,12 @@ body {
91
94
  white-space: nowrap;
92
95
  }
93
96
 
94
- .steerable-tool-execution > div > button.flex-1 {
95
- padding-left: 0;
96
- padding-right: 0;
97
- padding-inline: 0;
98
- }
99
-
100
- .steerable-tool-execution > div > button.flex-1 > span.ml-auto {
101
- margin-inline-end: 0.625rem;
102
- }
103
-
104
- .steerable-tool-execution > div > button.flex-1.pl-2\.5 > :first-child {
105
- margin-inline-start: 0.625rem;
106
- }
107
-
108
- .steerable-tool-execution > div > button.shrink-0 {
97
+ .steerable-tool-execution > div > button {
109
98
  padding-left: 0;
110
99
  padding-right: 0;
111
100
  padding-inline: 0;
112
101
  }
113
102
 
114
- .steerable-tool-execution > div > button.shrink-0 > svg {
115
- margin-inline: 0.625rem;
116
- }
117
-
118
103
  /*
119
104
  * ChatInput overlay: the contenteditable must keep a real text fill.
120
105
  * macOS Pinyin inspects fill during the first letter's keydown — before