@allbluecn/web-app 0.28.0 → 0.28.1

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.
Files changed (56) hide show
  1. package/package.json +4 -3
  2. package/src/components/harness/__tests__/dock-registry.test.ts +43 -0
  3. package/src/components/harness/conversation-panel/messages/harness-chain/__tests__/use-harness-chat-adapter.test.ts +20 -0
  4. package/src/components/harness/conversation-panel/messages/harness-chain/use-agent-terminals.ts +116 -0
  5. package/src/components/harness/conversation-panel/messages/harness-chain/use-harness-chat-adapter.ts +17 -5
  6. package/src/components/harness/conversation-panel/messages/harness-chain/use-harness-session.ts +4 -1
  7. package/src/components/harness/conversation-panel/messages/tools/__tests__/tool-run.test.ts +26 -1
  8. package/src/components/harness/conversation-panel/messages/tools/tool-run.ts +11 -0
  9. package/src/components/harness/extension-panel/dock/__tests__/tab-strip.test.tsx +45 -0
  10. package/src/components/harness/extension-panel/dock/dock-registry.ts +34 -0
  11. package/src/components/harness/extension-panel/dock/dock-surface.tsx +33 -0
  12. package/src/components/harness/extension-panel/dock/guide-page.tsx +4 -1
  13. package/src/components/harness/extension-panel/dock/tab-strip.tsx +9 -1
  14. package/src/components/harness/extension-panel/panels/terminal/__tests__/kind.test.tsx +219 -2
  15. package/src/components/harness/extension-panel/panels/terminal/__tests__/terminal-instance.test.tsx +322 -19
  16. package/src/components/harness/extension-panel/panels/terminal/__tests__/use-agent-terminal-roster.test.tsx +393 -0
  17. package/src/components/harness/extension-panel/panels/terminal/__tests__/ws-transport.test.ts +25 -0
  18. package/src/components/harness/extension-panel/panels/terminal/kind.tsx +55 -1
  19. package/src/components/harness/extension-panel/panels/terminal/shell-pref.ts +7 -4
  20. package/src/components/harness/extension-panel/panels/terminal/sse-transport.ts +26 -6
  21. package/src/components/harness/extension-panel/panels/terminal/tab-control-state.tsx +114 -0
  22. package/src/components/harness/extension-panel/panels/terminal/terminal-instance.tsx +190 -96
  23. package/src/components/harness/extension-panel/panels/terminal/terminal-theme.ts +113 -0
  24. package/src/components/harness/extension-panel/panels/terminal/transport.ts +28 -6
  25. package/src/components/harness/extension-panel/panels/terminal/use-agent-terminal-roster.ts +107 -0
  26. package/src/components/harness/extension-panel/panels/terminal/ws-transport.ts +7 -5
  27. package/src/components/harness/extension-panel/panels/terminal/xterm-terminal.tsx +5 -67
  28. package/src/lib/changelog/sdk-versions.ts +2 -2
  29. package/src/lib/queries/harness-terminal.ts +77 -0
  30. package/src/paraglide/messages/_index.js +48 -0
  31. package/src/paraglide/messages/en.js +15 -0
  32. package/src/paraglide/messages/zh.js +15 -0
  33. package/src/routes/api/harness/$.ts +19 -2
  34. package/src/routes/api/harness/terminal/$.ts +37 -6
  35. package/src/routes/api/harness/terminal/__tests__/route.test.ts +120 -0
  36. package/src/server/harness/__tests__/agent-terminal.server.test.ts +448 -0
  37. package/src/server/harness/__tests__/builtin-tools-invariant.test.ts +22 -12
  38. package/src/server/harness/__tests__/first-contact-fakes.test.ts +103 -3
  39. package/src/server/harness/__tests__/terminal-manager.server.test.ts +761 -2
  40. package/src/server/harness/agent-terminal.server.ts +631 -0
  41. package/src/server/harness/first-contact-fakes.ts +115 -4
  42. package/src/server/harness/host.server.ts +28 -1
  43. package/src/server/harness/persistence/__tests__/session-index-store.server.test.ts +83 -0
  44. package/src/server/harness/persistence/prisma-persistence.server.ts +12 -3
  45. package/src/server/harness/persistence/session-index-store.server.ts +26 -0
  46. package/src/server/harness/plugins/__tests__/assemble-disable.test.ts +25 -17
  47. package/src/server/harness/plugins/__tests__/tool-risk-audit.test.ts +16 -6
  48. package/src/server/harness/plugins/assemble-app.ts +12 -0
  49. package/src/server/harness/plugins/base-patch.ts +9 -2
  50. package/src/server/harness/plugins/builtin/__tests__/agent-terminal.plugin.test.ts +702 -0
  51. package/src/server/harness/plugins/builtin/agent-terminal.plugin.ts +518 -0
  52. package/src/server/harness/terminal-frame-builder.server.ts +5 -3
  53. package/src/server/harness/terminal-manager.server.ts +772 -35
  54. package/src/server/harness/terminal-ws-handler.server.ts +8 -2
  55. package/src/server/harness/tool-risk.ts +20 -4
  56. package/src/components/harness/extension-panel/panels/terminal/__tests__/xterm-webgl.test.ts +0 -68
@@ -0,0 +1,114 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // AllBlue - 理想之海
3
+ // Copyright (C) 2026 AllBlue Contributors
4
+ //
5
+ // This program is free software: you can redistribute it and/or modify
6
+ // it under the terms of the GNU Affero General Public License as published by
7
+ // the Free Software Foundation, either version 3 of the License, or
8
+ // (at your option) any later version.
9
+ //
10
+ // This program is distributed in the hope that it will be useful,
11
+ // but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ // GNU Affero General Public License for more details.
14
+ //
15
+ // You should have received a copy of the GNU Affero General Public License
16
+ // along with this program. If not, see <https://www.gnu.org/licenses/>.
17
+
18
+ // T14 agent 终端 tab 标题徽章:控制权轻量状态 + 自订阅标题组件。
19
+ //
20
+ // 设计取舍(不建 Context、不建全局 store):createTerminalKind 闭包持有 store
21
+ // (Map<tabId, snapshot> + version + listeners);TerminalInstance 的 state 帧经
22
+ // onControlStateChange 写入,TerminalTabTitle 用 useSyncExternalStore 订阅 version
23
+ // 自行重渲染——state 帧到达只重渲染标题节点本身,tab-strip 保持通用(dockRegistry
24
+ // 的 renderTabTitle 钩子返回的 ReactNode 塞进标题槽即可,零订阅零终端特有逻辑)。
25
+ //
26
+ // store 生命周期 = kind 实例生命周期(引用计数注册,双挂载期间两实例各自持有;旧实例
27
+ // cleanup 注销后其 store 无消费者,无泄漏面)。tab 关闭经 onTabClose 清 entry。
28
+
29
+ import { useSyncExternalStore } from "react"
30
+ import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"
31
+ import { m } from "@/paraglide/messages.js"
32
+ import type { DockTab } from "@/components/harness/extension-panel/dock/dock-layout"
33
+ import type { TerminalControlSnapshot } from "./transport"
34
+
35
+ /** 控制权轻量注册表(tabId → 最近 state 帧 {origin, control};version 驱动订阅重渲染)。 */
36
+ export interface TerminalControlStore {
37
+ /** 读某 tab 的最近快照(无 state 帧到达过 → undefined)。 */
38
+ get(tabId: string): TerminalControlSnapshot | undefined
39
+ /** 写入快照(同值幂等:不递增 version 不通知)。 */
40
+ set(tabId: string, snapshot: TerminalControlSnapshot): void
41
+ /** 清除 entry(tab 关闭时 onTabClose 调用,防复用/泄漏)。 */
42
+ clear(tabId: string): void
43
+ /** useSyncExternalStore 订阅(读 getVersion 作快照)。 */
44
+ subscribe(listener: () => void): () => void
45
+ /** 单调版本号(同值 set 不递增)。 */
46
+ getVersion(): number
47
+ }
48
+
49
+ export function createTerminalControlStore(): TerminalControlStore {
50
+ const states = new Map<string, TerminalControlSnapshot>()
51
+ const listeners = new Set<() => void>()
52
+ let version = 0
53
+
54
+ const notify = () => listeners.forEach((l) => l())
55
+
56
+ return {
57
+ get: (tabId) => states.get(tabId),
58
+ set(tabId, snapshot) {
59
+ const prev = states.get(tabId)
60
+ if (prev && prev.origin === snapshot.origin && prev.control === snapshot.control) return
61
+ states.set(tabId, snapshot)
62
+ version += 1
63
+ notify()
64
+ },
65
+ clear(tabId) {
66
+ if (!states.delete(tabId)) return
67
+ version += 1
68
+ notify()
69
+ },
70
+ subscribe(listener) {
71
+ listeners.add(listener)
72
+ return () => {
73
+ listeners.delete(listener)
74
+ }
75
+ },
76
+ getVersion: () => version,
77
+ }
78
+ }
79
+
80
+ /**
81
+ * terminal tab 标题(renderTabTitle 钩子的返回节点):title 文本 + Agent 徽章(可选)。
82
+ * 徽章语义(T14 逐字):origin==='agent' ∧ control==='agent' → 显示;接管翻转
83
+ * (control='user')后消失;用户终端(origin='user')恒无。badge 即 tooltip 触发器
84
+ * (span 非 button——嵌在 chip Button 内,避免嵌套交互元素)。
85
+ */
86
+ export function TerminalTabTitle({ tab, store }: { tab: DockTab; store: TerminalControlStore }) {
87
+ // 订阅 version(原始值快照);快照本体经 get 在渲染期读取。
88
+ useSyncExternalStore(store.subscribe, store.getVersion)
89
+ const snapshot = store.get(tab.id)
90
+ const agentControlled = snapshot?.origin === "agent" && snapshot?.control === "agent"
91
+ return (
92
+ <>
93
+ {tab.title}
94
+ {agentControlled ? (
95
+ <Tooltip>
96
+ <TooltipTrigger
97
+ render={
98
+ <span
99
+ data-testid="dock-tab-agent-badge"
100
+ // 与 chip 图标同口径:不污染 chip accessible name(测试/键盘按 title 查
101
+ // chip);文案经 tooltip 悬停可见。
102
+ aria-hidden="true"
103
+ className="ml-0.5 inline-flex shrink-0 items-center rounded-[4px] bg-primary/10 px-1 text-[10px] leading-4 font-medium text-primary"
104
+ >
105
+ {m.harness_panel_terminal_agentBadge()}
106
+ </span>
107
+ }
108
+ />
109
+ <TooltipContent>{m.harness_panel_terminal_agentBadgeTooltip()}</TooltipContent>
110
+ </Tooltip>
111
+ ) : null}
112
+ </>
113
+ )
114
+ }
@@ -20,8 +20,9 @@
20
20
  // `reset()+write(screen)` 重建 → 增量 output `write(data)`;exit 帧 → exited 态。
21
21
  // 输入永不重放:重连一律走 snapshot 重建(服务端语义)。
22
22
  // - 输入:xterm onData → 16ms 批处理窗口合并 + 客户端单调 seq → transport.send
23
- // (POST input `{writes:[{seq,data}]}`);与 resize 共用一条 seq 序列,经 transport
24
- // 内 Promise 链串行发送保序(防 write/resize 请求乱序触发服务端 invalid_sequence 409)。
23
+ // (POST input `{writes:[{seq,data,typed?}]}`;typed 为 T12 手势识别标记——手势事件后
24
+ // 250ms 窗口内且非焦点报告才算用户键入,混合批任一笔 typed 整批置位);与 resize 共用
25
+ // 一条 seq 序列,经 transport 内 Promise 链串行发送保序(防乱序触发服务端 409)。
25
26
  // - resize:FitAddon 尺寸变化(xterm-terminal 仅可见+非零时产出)→ 防抖 200ms →
26
27
  // transport.send(POST input `{resize:{seq,cols,rows}}`)。keepMounted 隐藏态在
27
28
  // xterm-terminal 已跳过 fit,本层再以 connected 门控兜底。
@@ -38,12 +39,13 @@ import { lazy, Suspense, useCallback, useEffect, useRef, useState } from "react"
38
39
  import { RotateCcw, SquareTerminal } from "lucide-react"
39
40
  import { cn } from "cn"
40
41
  import { Button } from "@/components/ui/button"
41
- import { useThemeMode } from "@/providers/theme-mode-provider"
42
+ import { toast } from "@/components/ui/toast"
43
+ import { computeXtermTheme, subscribeThemeClass } from "./terminal-theme"
42
44
  import { readTerminalShellPref } from "./shell-pref"
43
45
  import { m } from "@/paraglide/messages.js"
44
46
  import type { XtermHandle } from "./xterm-terminal"
45
47
  import { createTerminalTransport } from "./transport"
46
- import type { DownFrame, TerminalTransport } from "./transport"
48
+ import type { DownFrame, TerminalControlSnapshot, TerminalTransport } from "./transport"
47
49
  import { isDesktopClient } from "@/lib/desktop-env"
48
50
  import { isHarnessClientEnabled } from "@/lib/harness-gate"
49
51
 
@@ -56,71 +58,54 @@ type TerminalPhase = "connecting" | "connected" | "disconnected" | "exited"
56
58
  /** binding localStorage 键前缀(设计 §4.2)。 */
57
59
  const BINDING_PREFIX = "allblue.harness.terminal-binding.v1"
58
60
 
61
+ // ── typed 输入手势识别(T12,agent 终端接管翻转的真实用户键入信号)─────────────
62
+ /** 手势窗口(ms):手势事件后该窗口内的 xterm onData 视为用户真实键入 → write 带 typed。 */
63
+ const TYPED_INPUT_WINDOW_MS = 250
64
+ /** 手势事件类型(终端容器 capture 阶段监听记时间戳;不挂 document——同页多终端实例时间戳互不污染)。 */
65
+ const INPUT_GESTURES = ["keydown", "beforeinput", "paste", "compositionend", "drop", "mousedown", "touchstart"]
66
+ /** DECSET 1004 焦点报告(xterm 聚焦变化自动上报序列)非用户键入,恒不算 typed。 */
67
+ const FOCUS_REPORTS = ["\x1b[I", "\x1b[O"]
68
+
59
69
  function bindingKey(threadId: string, tabId: string): string {
60
70
  return `${BINDING_PREFIX}.${threadId}.${tabId}`
61
71
  }
62
- function readBinding(threadId: string, tabId: string): string | null {
72
+ /** binding 存 {terminalId, serverEpoch}(方案 C)。serverEpoch 供重连比对区分「服务端重启」
73
+ * (epoch 变)与「终端退出/idle 回收」(epoch 不变)两类失效——二者对客户端本是同一 404
74
+ * 签名。兼容旧纯 id 值:读到非 JSON/无 epoch 视为 epoch 未知,走既有 404 兜底。 */
75
+ interface TerminalBinding {
76
+ terminalId: string
77
+ serverEpoch?: string
78
+ }
79
+ function readBinding(threadId: string, tabId: string): TerminalBinding | null {
63
80
  try {
64
- return window.localStorage.getItem(bindingKey(threadId, tabId))
81
+ const raw = window.localStorage.getItem(bindingKey(threadId, tabId))
82
+ if (!raw) return null
83
+ const parsed = JSON.parse(raw) as TerminalBinding
84
+ return typeof parsed?.terminalId === "string" ? parsed : null
65
85
  } catch {
66
- return null
86
+ // 旧格式(纯 id 字符串)→ JSON.parse 失败,按 null 处理(epoch 未知,走 404 兜底)
87
+ try {
88
+ const legacy = window.localStorage.getItem(bindingKey(threadId, tabId))
89
+ return legacy ? { terminalId: legacy } : null
90
+ } catch {
91
+ return null
92
+ }
67
93
  }
68
94
  }
69
- function writeBinding(threadId: string, tabId: string, terminalId: string): void {
95
+ function writeBinding(threadId: string, tabId: string, terminalId: string, serverEpoch?: string): void {
70
96
  try {
71
- window.localStorage.setItem(bindingKey(threadId, tabId), terminalId)
97
+ const payload: TerminalBinding = { terminalId, ...(serverEpoch ? { serverEpoch } : {}) }
98
+ window.localStorage.setItem(bindingKey(threadId, tabId), JSON.stringify(payload))
72
99
  } catch {
73
100
  /* localStorage 不可用(隐私模式)→ 忽略,仅本次会话内有效 */
74
101
  }
75
102
  }
76
-
77
- // xterm 主题色板(canvas 渲染需具体色值,无法用 CSS var()——此为 xterm API 约束,
78
- // 非界面样式硬编码色;语义色板对齐 shadcn 中性灰阶,双主题各自成套)。
79
- const XTERM_THEME_LIGHT: Record<string, string> = {
80
- background: "#ffffff",
81
- foreground: "#1c1917",
82
- cursor: "#1c1917",
83
- cursorAccent: "#ffffff",
84
- selectionBackground: "#00000033",
85
- black: "#1c1917",
86
- red: "#b91c1c",
87
- green: "#15803d",
88
- yellow: "#a16207",
89
- blue: "#1d4ed8",
90
- magenta: "#a21caf",
91
- cyan: "#0e7490",
92
- white: "#d6d3d1",
93
- brightBlack: "#78716c",
94
- brightRed: "#dc2626",
95
- brightGreen: "#16a34a",
96
- brightYellow: "#ca8a04",
97
- brightBlue: "#2563eb",
98
- brightMagenta: "#c026d3",
99
- brightCyan: "#0891b2",
100
- brightWhite: "#f5f5f4",
101
- }
102
- const XTERM_THEME_DARK: Record<string, string> = {
103
- background: "#1c1917",
104
- foreground: "#e7e5e4",
105
- cursor: "#e7e5e4",
106
- cursorAccent: "#1c1917",
107
- selectionBackground: "#ffffff40",
108
- black: "#292524",
109
- red: "#f87171",
110
- green: "#4ade80",
111
- yellow: "#facc15",
112
- blue: "#60a5fa",
113
- magenta: "#f472b6",
114
- cyan: "#22d3ee",
115
- white: "#a8a29e",
116
- brightBlack: "#78716c",
117
- brightRed: "#fca5a5",
118
- brightGreen: "#86efac",
119
- brightYellow: "#fde047",
120
- brightBlue: "#93c5fd",
121
- brightMagenta: "#f9a8d4",
122
- brightCyan: "#67e8f9",
123
- brightWhite: "#f5f5f4",
103
+ function clearBinding(threadId: string, tabId: string): void {
104
+ try {
105
+ window.localStorage.removeItem(bindingKey(threadId, tabId))
106
+ } catch {
107
+ /* localStorage 不可用 → 忽略 */
108
+ }
124
109
  }
125
110
 
126
111
  export interface TerminalInstanceProps {
@@ -128,12 +113,40 @@ export interface TerminalInstanceProps {
128
113
  threadId: string
129
114
  /** DockTab id(binding localStorage 键的一段)。 */
130
115
  tabId: string
116
+ /**
117
+ * 初始 terminalId(T14,instanceId 优先 attach):kind 传 tab.instanceId——reconcile
118
+ * 开的 agent 终端 tab 直接 attach 该终端,跳过 binding 读取与 create。无效 id 服务端
119
+ * 报错走现有 disconnected/reconnect 面,不回落 create(agent 终端已死显示退出态,由
120
+ * reconcile 关 tab)。用户 tab 无 instanceId(T13 不变量:带 instanceId ⟺ agent 终端
121
+ * tab),undefined → 原 binding → create 链不变。
122
+ */
123
+ initialTerminalId?: string
124
+ /**
125
+ * state 帧控制权上抛(T14):kind 注入,写入 tab-control-state store 驱动 tab 标题
126
+ * Agent 徽章。仅 origin/control 均非缺失时调用。
127
+ */
128
+ onControlStateChange?: (snapshot: TerminalControlSnapshot) => void
129
+ /**
130
+ * 重开通知(T14-I1):reopen 时同步调用一次。kind 注入 dockRegistry.clearTabInstanceId
131
+ * 清 tab 元数据 instanceId——组件内只能清自身 attach 覆盖,DockTab.instanceId 的清除
132
+ * 归 kind(残留会让 T13 reconcile 强制关掉刚重开的新终端)。用户 tab 场景为安全 no-op。
133
+ */
134
+ onReopen?: () => void
131
135
  className?: string
132
136
  }
133
137
 
134
- export function TerminalInstance({ threadId, tabId, className }: TerminalInstanceProps) {
135
- const { resolved } = useThemeMode()
136
- const xtermTheme = resolved === "dark" ? XTERM_THEME_DARK : XTERM_THEME_LIGHT
138
+ export function TerminalInstance({
139
+ threadId,
140
+ tabId,
141
+ initialTerminalId,
142
+ onControlStateChange,
143
+ onReopen,
144
+ className,
145
+ }: TerminalInstanceProps) {
146
+ // 主题(DSH 模式):背景不透明取 --background 计算值;主题源 = documentElement class
147
+ // 订阅(同帧跟随 View Transition 的 flushSync class 翻转),不用 resolved(晚 400ms)。
148
+ const [xtermTheme, setXtermTheme] = useState<Record<string, string>>(() => computeXtermTheme())
149
+ useEffect(() => subscribeThemeClass(() => setXtermTheme(computeXtermTheme())), [])
137
150
 
138
151
  const xtermRef = useRef<XtermHandle | null>(null)
139
152
  const hostRef = useRef<HTMLDivElement>(null)
@@ -152,21 +165,54 @@ export function TerminalInstance({ threadId, tabId, className }: TerminalInstanc
152
165
  const connectedRef = useRef(false)
153
166
  const didInitBindingRef = useRef(false)
154
167
  const transportRef = useRef<TerminalTransport | null>(null)
155
- const writeBufRef = useRef<string[]>([])
168
+ /** 批处理缓冲(每笔记 typed 手势判定,flush 时合并)。 */
169
+ const writeBufRef = useRef<Array<{ data: string; typed: boolean }>>([])
156
170
  const writeTimerRef = useRef<number | null>(null)
157
171
  const resizeTimerRef = useRef<number | null>(null)
158
172
  const pendingResizeRef = useRef<{ cols: number; rows: number } | null>(null)
173
+ /** 最近一次手势事件时间戳(实例内独立,-Infinity = 尚无手势 → 判定恒 false,保守不误标)。 */
174
+ const gestureAtRef = useRef(-Infinity)
159
175
  // WS 回落状态:会话内首次试 WS 失败后固守 SSE(重连不再重试 WS)
160
176
  const wsFailedRef = useRef(false)
177
+ // T14 控制权跟踪:最近 state 帧 {origin, control}(null = 尚未收到,接管 toast 的
178
+ // prevControl 翻转边判定源——初始挂载不 toast);onControlStateChange 经 ref 保新值
179
+ //(attach effect 闭包捕获首帧值即可,不重挂 effect)。
180
+ const controlRef = useRef<TerminalControlSnapshot | null>(null)
181
+ const onControlStateChangeRef = useRef(onControlStateChange)
182
+ onControlStateChangeRef.current = onControlStateChange
183
+ // instanceId 覆盖经 ref 消费(attach 读),重开(reopen)置空——agent tab 退出后用户
184
+ // 点「重开」走原 create 链(新终端归 user origin,生命周期交回 T13 reconcile)。
185
+ const initialTerminalIdRef = useRef(initialTerminalId)
186
+
187
+ // ── 手势监听(T12):终端容器 capture 阶段记时间戳(keydown/beforeinput/paste/
188
+ // compositionend/drop/mousedown/touchstart 七类)。挂容器不挂 document——同页多终端
189
+ // 实例各自独立时间戳;卸载清理。
190
+ useEffect(() => {
191
+ const host = hostRef.current
192
+ if (!host) return
193
+ const markGesture = () => {
194
+ gestureAtRef.current = performance.now()
195
+ }
196
+ for (const type of INPUT_GESTURES) {
197
+ host.addEventListener(type, markGesture, true)
198
+ }
199
+ return () => {
200
+ for (const type of INPUT_GESTURES) {
201
+ host.removeEventListener(type, markGesture, true)
202
+ }
203
+ }
204
+ }, [])
161
205
 
162
206
  // ── 上行输入(16ms 批处理 → transport.send;seq 由 clientSeqRef 计数器分配)──
163
207
  // transport.send 内部经 Promise 链串行保序(防 write/resize 乱序 409)。
208
+ // 混合批保守取向:批内任一笔 typed → 整批 typed:true(宁可误接管不可漏接管)。
164
209
  const flushWrites = useCallback(() => {
165
210
  writeTimerRef.current = null
166
- const data = writeBufRef.current.join("")
211
+ const buf = writeBufRef.current
167
212
  writeBufRef.current = []
168
- if (!data || !connectedRef.current) return
169
- transportRef.current?.send({ type: "write", sequence: ++clientSeqRef.current, data })
213
+ if (buf.length === 0 || !connectedRef.current) return
214
+ const typed = buf.some((w) => w.typed)
215
+ transportRef.current?.send({ type: "write", sequence: ++clientSeqRef.current, data: buf.map((w) => w.data).join(""), typed })
170
216
  }, [])
171
217
 
172
218
  const flushResize = useCallback(() => {
@@ -177,11 +223,14 @@ export function TerminalInstance({ threadId, tabId, className }: TerminalInstanc
177
223
  transportRef.current?.send({ type: "resize", sequence: ++clientSeqRef.current, cols: pr.cols, rows: pr.rows })
178
224
  }, [])
179
225
 
180
- /** xterm onData → 16ms 批处理窗口合并(仅 connected 可写)。 */
226
+ /** xterm onData → 16ms 批处理窗口合并(仅 connected 可写);逐笔 typed 手势判定。 */
181
227
  const handleData = useCallback(
182
228
  (data: string) => {
183
229
  if (!connectedRef.current) return
184
- writeBufRef.current.push(data)
230
+ // 手势窗口内(≤250ms)且非焦点报告 → 用户真实键入;否则服务端不得翻转接管
231
+ const typed =
232
+ performance.now() - gestureAtRef.current < TYPED_INPUT_WINDOW_MS && !FOCUS_REPORTS.includes(data)
233
+ writeBufRef.current.push({ data, typed })
185
234
  if (writeTimerRef.current == null) {
186
235
  writeTimerRef.current = window.setTimeout(flushWrites, 16)
187
236
  }
@@ -238,9 +287,23 @@ export function TerminalInstance({ threadId, tabId, className }: TerminalInstanc
238
287
  xtermRef.current?.write(frame.data)
239
288
  transport?.scheduleAck()
240
289
  break
241
- case "state":
290
+ case "state": {
242
291
  xtermRef.current?.setDisplaySize(frame.cols, frame.rows)
292
+ // T14 控制权:上抛给 tab 标题徽章 + 接管 toast(翻转边判定)。防御性收窄——
293
+ // 老服务端/异常路径缺 origin/control 时跳过(不下发、不 toast、不污染 prev)。
294
+ if (frame.origin != null && frame.control != null) {
295
+ const prev = controlRef.current
296
+ const snapshot: TerminalControlSnapshot = { origin: frame.origin, control: frame.control }
297
+ controlRef.current = snapshot
298
+ onControlStateChangeRef.current?.(snapshot)
299
+ // 接管翻转边(prev.control agent → user)→ 一次性 toast;初始挂载
300
+ //(prev=null)与重复 user 帧均不触发。
301
+ if (prev?.control === "agent" && frame.control === "user") {
302
+ toast.info(m.harness_panel_terminal_takeoverToast())
303
+ }
304
+ }
243
305
  break
306
+ }
244
307
  case "exit":
245
308
  connectedRef.current = false
246
309
  setExitCode(frame.code)
@@ -287,11 +350,21 @@ export function TerminalInstance({ threadId, tabId, className }: TerminalInstanc
287
350
  setPhase("connecting")
288
351
  setErrorMsg(null)
289
352
 
290
- // 1) 解析 terminalId:binding(仅首次)→ create
291
- if (!terminalIdRef.current && !didInitBindingRef.current) {
353
+ // 1) 解析 terminalId:initialTerminalId(T14 instanceId 优先,agent tab 直连,跳过
354
+ // binding/create)→ binding(仅首次)→ create(下方步骤 2)。binding 路径与
355
+ // create 路径保持原序不动;agent tab 不写 binding(create 路径专属,语义不变)。
356
+ // binding 存的 serverEpoch 记入 boundEpochRef,供 notFound 时比对区分重启/回收。
357
+ let boundEpochRef: string | undefined
358
+ if (initialTerminalIdRef.current) {
359
+ terminalIdRef.current = initialTerminalIdRef.current
360
+ } else if (!terminalIdRef.current && !didInitBindingRef.current) {
292
361
  didInitBindingRef.current = true
293
- terminalIdRef.current = readBinding(threadId, tabId)
362
+ const binding = readBinding(threadId, tabId)
363
+ terminalIdRef.current = binding?.terminalId ?? null
364
+ boundEpochRef = binding?.serverEpoch
294
365
  }
366
+ // 死 id 守卫:notFound 重建每代只走一次,防服务端持续 404 时 create↔connect 死循环
367
+ let recreatedAfterNotFound = false
295
368
 
296
369
  // 决定传输形态:WS 优先(desktop/harness client 且未失败),否则 SSE
297
370
  const shouldTryWs =
@@ -316,33 +389,46 @@ export function TerminalInstance({ threadId, tabId, className }: TerminalInstanc
316
389
  transportRef.current = sse
317
390
  }
318
391
 
319
- // 2) create(若需要新建终端)
320
- if (!terminalIdRef.current) {
321
- const cols = xtermRef.current?.getCols() ?? 80
322
- const rows = xtermRef.current?.getRows() ?? 24
323
- const shell = readTerminalShellPref() ?? undefined
324
- const result = await transport.create({ cols, rows, shell })
325
- if (!result.ok) {
326
- // create 失败(非 WS 连接问题)→ 直接 disconnected,不回落
327
- if (cancelled) return
328
- // terminal_env_unavailable(503,node-pty 加载失败,P6e-1)→ 本地化降级文案
329
- // (重装引导),而非透传服务端 message;其余错误沿用服务端 message。
330
- setErrorMsg(
331
- result.errorCode === "terminal_env_unavailable"
332
- ? m.harness_panel_terminal_envUnavailable()
333
- : (result.error ?? m.harness_panel_terminal_connectFailed()),
334
- )
335
- setPhase("disconnected")
336
- return
392
+ // 2)+3) create(若需新建)→ connect。connect 返回 notFound(服务端已无此终端:
393
+ // dev/host 重启或 idle 回收后 binding 存活死 id)→ 清 id+binding 后 create 重建
394
+ // 再连一次(recreatedAfterNotFound 守卫防服务端持续 404 时的 create↔connect 死循环,
395
+ // 再 404 则走常规 disconnected+重连钮)。
396
+ for (;;) {
397
+ if (!terminalIdRef.current) {
398
+ const cols = xtermRef.current?.getCols() ?? 80
399
+ const rows = xtermRef.current?.getRows() ?? 24
400
+ const shell = readTerminalShellPref() ?? undefined
401
+ const result = await transport.create({ cols, rows, shell })
402
+ if (!result.ok) {
403
+ // create 失败(非 WS 连接问题)→ 直接 disconnected,不回落
404
+ if (cancelled) return
405
+ // terminal_env_unavailable(503,node-pty 加载失败,P6e-1)→ 本地化降级文案
406
+ // (重装引导),而非透传服务端 message;其余错误沿用服务端 message。
407
+ setErrorMsg(
408
+ result.errorCode === "terminal_env_unavailable"
409
+ ? m.harness_panel_terminal_envUnavailable()
410
+ : (result.error ?? m.harness_panel_terminal_connectFailed()),
411
+ )
412
+ setPhase("disconnected")
413
+ return
414
+ }
415
+ terminalIdRef.current = result.terminalId
416
+ setShellName(result.shell)
417
+ writeBinding(threadId, tabId, result.terminalId, result.serverEpoch)
418
+ }
419
+ if (cancelled) return
420
+
421
+ // 3) 连接下行(WS 或 SSE)
422
+ const conn = await transport.connect(terminalIdRef.current)
423
+ if (cancelled) return
424
+ if (conn.notFound && !recreatedAfterNotFound) {
425
+ recreatedAfterNotFound = true
426
+ terminalIdRef.current = null
427
+ clearBinding(threadId, tabId)
428
+ continue
337
429
  }
338
- terminalIdRef.current = result.terminalId
339
- setShellName(result.shell)
340
- writeBinding(threadId, tabId, result.terminalId)
430
+ break
341
431
  }
342
- if (cancelled) return
343
-
344
- // 3) 连接下行(WS 或 SSE)
345
- transport.connect(terminalIdRef.current)
346
432
  }
347
433
 
348
434
  void attach()
@@ -388,6 +474,12 @@ export function TerminalInstance({ threadId, tabId, className }: TerminalInstanc
388
474
  /* ignore */
389
475
  }
390
476
  }
477
+ // T14:同时清 instanceId 覆盖——agent tab 重开走 create(新终端归 user origin),
478
+ // 不再回连已退出的 agent 终端 id。
479
+ initialTerminalIdRef.current = undefined
480
+ // T14-I2:复位控制权边判定基线——新终端首帧(无论 user/agent)prev=null 不判接管边,
481
+ // 防「agent 退出重开后新终端首帧 user → 假『已接管』toast」。
482
+ controlRef.current = null
391
483
  terminalIdRef.current = null
392
484
  clientSeqRef.current = 0
393
485
  setExitCode(null)
@@ -395,7 +487,9 @@ export function TerminalInstance({ threadId, tabId, className }: TerminalInstanc
395
487
  setShellName(null)
396
488
  setPhase("connecting")
397
489
  setGen((g) => g + 1)
398
- }, [threadId, tabId])
490
+ // T14-I1:通知外部清 tab 元数据 instanceId(kind → registry.clearTabInstanceId)。
491
+ onReopen?.()
492
+ }, [threadId, tabId, onReopen])
399
493
 
400
494
  // ── ⌃` 让位:xterm 聚焦时 Ctrl+` 拦在容器 bubble 阶段(xterm textarea 已在 target
401
495
  // 阶段处理为字符输入),document 上的 harness-terminal-new 收不到 → 不新建终端。
@@ -0,0 +1,113 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // AllBlue - 理想之海
3
+ // Copyright (C) 2026 AllBlue Contributors
4
+ //
5
+ // This program is free software: you can redistribute it and/or modify
6
+ // it under the terms of the GNU Affero General Public License as published by
7
+ // the Free Software Foundation, either version 3 of the License, or
8
+ // (at your option) any later version.
9
+ //
10
+ // This program is distributed in the hope that it will be useful,
11
+ // but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ // GNU Affero General Public License for more details.
14
+ //
15
+ // You should have received a copy of the GNU Affero General Public License
16
+ // along with this program. If not, see <https://www.gnu.org/licenses/>.
17
+
18
+ // 终端 xterm 主题(DSH 对标,ui-sidebar-terminal/terminal-theme.ts 模式):
19
+ // 背景不透明、取 documentElement 计算值(--background/--foreground,oklch→hex),
20
+ // 与主窗口严格一致;ANSI 色板按 documentElement 的 dark class 选择。
21
+ //
22
+ // 主题源 = documentElement class 订阅(MutationObserver):主窗口切主题走 View
23
+ // Transition(AnimatedThemeToggler 在 flushSync 内翻转 class),观察器同帧跟随;
24
+ // **不可用 useThemeMode().resolved**——它在 transition.finished 后才翻转(晚 ~400ms),
25
+ // 是此前「切主题不同步/有延迟」的根因。
26
+ //
27
+ // 不透明背景 + 无 webgl:webgl 上下文以 alpha:false 创建,透明背景会被合成成黑色
28
+ // (此前「终端背景一直是黑的」的根因);DSH 亦无 webgl addon,DOM 渲染器主题热更新
29
+ // 即时且廉价,无 webgl dispose+重建 GPU 上下文的延迟。
30
+
31
+ import { parseColor, toHex } from "@/components/design/canvas/document/style/color-utils"
32
+ import { resolveThemeColor } from "@/components/design/canvas/document/style/theme-color"
33
+
34
+ /** ANSI 色板(canvas 渲染需具体色值,无法用 CSS var()——xterm API 约束;语义色对齐 shadcn 中性灰阶)。 */
35
+ const XTERM_THEME_LIGHT: Record<string, string> = {
36
+ foreground: "#1c1917",
37
+ cursor: "#1c1917",
38
+ cursorAccent: "#ffffff",
39
+ selectionBackground: "#00000033",
40
+ black: "#1c1917",
41
+ red: "#b91c1c",
42
+ green: "#15803d",
43
+ yellow: "#a16207",
44
+ blue: "#1d4ed8",
45
+ magenta: "#a21caf",
46
+ cyan: "#0e7490",
47
+ white: "#d6d3d1",
48
+ brightBlack: "#78716c",
49
+ brightRed: "#dc2626",
50
+ brightGreen: "#16a34a",
51
+ brightYellow: "#ca8a04",
52
+ brightBlue: "#2563eb",
53
+ brightMagenta: "#c026d3",
54
+ brightCyan: "#0891b2",
55
+ brightWhite: "#f5f5f4",
56
+ }
57
+ const XTERM_THEME_DARK: Record<string, string> = {
58
+ foreground: "#e7e5e4",
59
+ cursor: "#e7e5e4",
60
+ cursorAccent: "#1c1917",
61
+ selectionBackground: "#ffffff40",
62
+ black: "#292524",
63
+ red: "#f87171",
64
+ green: "#4ade80",
65
+ yellow: "#facc15",
66
+ blue: "#60a5fa",
67
+ magenta: "#f472b6",
68
+ cyan: "#22d3ee",
69
+ white: "#a8a29e",
70
+ brightBlack: "#78716c",
71
+ brightRed: "#fca5a5",
72
+ brightGreen: "#86efac",
73
+ brightYellow: "#fde047",
74
+ brightBlue: "#93c5fd",
75
+ brightMagenta: "#f9a8d4",
76
+ brightCyan: "#67e8f9",
77
+ brightWhite: "#f5f5f4",
78
+ }
79
+
80
+ /** dark class 直读(不依赖 useThemeMode().resolved——它晚 View Transition 一拍)。 */
81
+ function isDarkClass(): boolean {
82
+ return typeof document !== "undefined" && document.documentElement.classList.contains("dark")
83
+ }
84
+
85
+ /** 解析失败兜底:回落各主题的中性背景(近 --background),避免异常时黑屏/白屏错乱。 */
86
+ function fallbackBg(dark: boolean): string {
87
+ return dark ? "#1c1917" : "#ffffff"
88
+ }
89
+
90
+ /** 计算当前主题的 xterm 色板:背景/前景取 --background/--foreground 计算值转 hex(不透明)。 */
91
+ export function computeXtermTheme(): Record<string, string> {
92
+ const dark = isDarkClass()
93
+ const palette = dark ? XTERM_THEME_DARK : XTERM_THEME_LIGHT
94
+ return {
95
+ ...palette,
96
+ background:
97
+ toHex(parseColor(resolveThemeColor("--background")) ?? { r: 0, g: 0, b: 0, a: 1 }) ||
98
+ fallbackBg(dark),
99
+ foreground:
100
+ toHex(parseColor(resolveThemeColor("--foreground")) ?? { r: 0, g: 0, b: 0, a: 1 }) ||
101
+ palette.foreground,
102
+ }
103
+ }
104
+
105
+ /** 订阅 documentElement class 变化(主题切换即时跟随)。返回退订函数。 */
106
+ export function subscribeThemeClass(cb: () => void): () => void {
107
+ if (typeof document === "undefined" || typeof MutationObserver === "undefined") {
108
+ return () => {}
109
+ }
110
+ const observer = new MutationObserver(cb)
111
+ observer.observe(document.documentElement, { attributes: true, attributeFilter: ["class"] })
112
+ return () => observer.disconnect()
113
+ }