@steerable/agent-shell-web 0.12.8 → 0.13.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@steerable/agent-shell-web",
3
- "version": "0.12.8",
3
+ "version": "0.13.1",
4
4
  "type": "module",
5
5
  "description": "Steerable framework — product-neutral renderer SPA source for @steerable/agent-shell (React + Vite). Consumed by product web entry points via the `@/` alias (anchored at this package's src/) and the createProductViteConfig factory. Published as a source package (src/), plus the compiled vite.base config factory (vite.base.js + .d.ts) for Node-side config loading.",
6
6
  "license": "Apache-2.0",
@@ -45,8 +45,8 @@
45
45
  "react-router-dom": "^6.30.0",
46
46
  "rehype-raw": "^7.0.0",
47
47
  "remark-gfm": "^4.0.1",
48
- "@steerable/agent-protocol": "0.12.8",
49
- "@steerable/agent-ui": "0.12.8"
48
+ "@steerable/agent-protocol": "0.13.1",
49
+ "@steerable/agent-ui": "0.13.1"
50
50
  },
51
51
  "devDependencies": {
52
52
  "@tailwindcss/vite": "^4.3.0",
@@ -59,7 +59,7 @@
59
59
  "typescript": "^5.8.3",
60
60
  "vite": "^5.4.21",
61
61
  "vitest": "^3.2.4",
62
- "@steerable/pack-sdk": "0.12.8"
62
+ "@steerable/pack-sdk": "0.13.1"
63
63
  },
64
64
  "scripts": {
65
65
  "gen": "echo agent-shell-web",
@@ -430,6 +430,8 @@ interface AgentSidebarProps {
430
430
  onToggleRightPanel?: (kind: string) => void;
431
431
  /** 收起侧边栏(AgentLayout 换成窄 rail,展开按钮在 rail 上)。 */
432
432
  onCollapse: () => void;
433
+ /** Custom ApplicationManifest navigation visibility rules (bypassed under ?safe=1). */
434
+ hiddenNavItems?: readonly ('skills' | 'mcp' | 'agents' | 'terminal')[];
433
435
  }
434
436
 
435
437
  export function AgentSidebar({
@@ -437,6 +439,7 @@ export function AgentSidebar({
437
439
  rightPanel: _rightPanel,
438
440
  onToggleRightPanel: _onToggleRightPanel,
439
441
  onCollapse,
442
+ hiddenNavItems = [],
440
443
  }: AgentSidebarProps) {
441
444
  const navigate = useNavigate();
442
445
  const location = useLocation();
@@ -449,11 +452,13 @@ export function AgentSidebar({
449
452
  () => new URLSearchParams(location.search).get("section"),
450
453
  [location.search],
451
454
  );
455
+ const hiddenSet = useMemo(() => new Set(hiddenNavItems), [hiddenNavItems]);
452
456
  const pluginsAvailable =
453
- settingsChrome("agents") ||
454
- settingsChrome("skills") ||
455
- settingsChrome("mcp") ||
456
- settingsChrome("web-search");
457
+ (!hiddenSet.has("agents") && settingsChrome("agents")) ||
458
+ (!hiddenSet.has("skills") && settingsChrome("skills")) ||
459
+ (!hiddenSet.has("mcp") && settingsChrome("mcp")) ||
460
+ (!(hiddenSet.has("agents") && hiddenSet.has("skills") && hiddenSet.has("mcp")) &&
461
+ settingsChrome("web-search"));
457
462
  const onPluginsSettings =
458
463
  pluginsAvailable &&
459
464
  onSettingsPage &&
@@ -0,0 +1,64 @@
1
+ import { useState } from 'react';
2
+ import { useNavigate } from 'react-router-dom';
3
+ import { LuShieldAlert } from 'react-icons/lu';
4
+ import { t } from '@/i18n';
5
+ import { resetToDefaultApplication, stripSafeQueryParam } from '@/lib/safe-mode';
6
+
7
+ export interface SafeRecoveryBannerProps {
8
+ onResetComplete?: () => void;
9
+ }
10
+
11
+ export function SafeRecoveryBanner({ onResetComplete }: SafeRecoveryBannerProps) {
12
+ const navigate = useNavigate();
13
+ const [resetting, setResetting] = useState(false);
14
+
15
+ const handleReset = async () => {
16
+ setResetting(true);
17
+ try {
18
+ await resetToDefaultApplication();
19
+ onResetComplete?.();
20
+ if (typeof window !== 'undefined') {
21
+ const cleaned = stripSafeQueryParam(window.location.href);
22
+ window.history.replaceState(null, '', cleaned);
23
+ }
24
+ navigate('/agent');
25
+ } finally {
26
+ setResetting(false);
27
+ }
28
+ };
29
+
30
+ return (
31
+ <div
32
+ role="region"
33
+ aria-label={t('Safe recovery mode')}
34
+ data-testid="safe-recovery-banner"
35
+ className="flex items-center justify-between gap-3 border-b border-amber-500/30 bg-amber-500/10 px-3.5 py-2 text-xs text-agent-foreground"
36
+ >
37
+ <div className="flex min-w-0 items-center gap-2">
38
+ <LuShieldAlert className="h-4 w-4 flex-shrink-0 text-amber-600 dark:text-amber-400" aria-hidden="true" />
39
+ <span className="truncate font-medium">
40
+ {t('Safe recovery mode · custom application shell bypassed')}
41
+ </span>
42
+ </div>
43
+ <div className="flex flex-shrink-0 items-center gap-2">
44
+ <button
45
+ type="button"
46
+ onClick={() => navigate('/settings')}
47
+ data-testid="safe-recovery-settings"
48
+ className="rounded-md px-2 py-1 text-xs font-medium text-agent-muted-foreground transition-colors hover:bg-agent-foreground/10 hover:text-agent-foreground"
49
+ >
50
+ {t('Settings')}
51
+ </button>
52
+ <button
53
+ type="button"
54
+ disabled={resetting}
55
+ onClick={() => void handleReset()}
56
+ data-testid="safe-recovery-reset"
57
+ className="rounded-md bg-agent-foreground px-2.5 py-1 text-xs font-medium text-agent-canvas transition-opacity hover:opacity-90 disabled:opacity-50"
58
+ >
59
+ {t('Reset to default application')}
60
+ </button>
61
+ </div>
62
+ </div>
63
+ );
64
+ }
@@ -1,4 +1,5 @@
1
- import { LuShieldAlert, LuTriangleAlert } from 'react-icons/lu';
1
+ import { useEffect, useRef } from 'react';
2
+ import { LuFlag, LuShieldAlert, LuTriangleAlert } from 'react-icons/lu';
2
3
  import {
3
4
  type ApprovalDecisionKind,
4
5
  type ApprovalPromptRequest,
@@ -6,17 +7,11 @@ import {
6
7
  import { t } from '@/i18n';
7
8
 
8
9
  /**
9
- * ApprovalPromptMenu — W4-1 审批代数的输入区 UI。
10
+ * ApprovalPromptMenu — W4-1 & Phase 9 `outward` approval UI.
10
11
  *
11
- * 由 ApprovalPromptProvider 提供当前请求,在普通输入框的位置让用户对
12
- * 工具调用做 7 变体决策(允许/拒绝 × 一次性/会话/持久 + 中止)。
13
- *
14
- * 持久化语义(与框架 ApprovalExecutor 对齐):
15
- * - 一次性:只作用于本次调用,不缓存。
16
- * - 会话:按 category(默认=工具名)缓存在本 chat 的会话级 cache。
17
- * - 持久:写入 ~/.steerable/approvals.json,跨会话生效。
18
- *
19
- * 请求队列及刷新恢复由 Provider 管理。
12
+ * Supports the 7-variant approval algebra for standard/egress/sandbox prompts,
13
+ * and enforces single-invocation confirmation for `checkpoint === 'outward'`
14
+ * (hiding session/always options and placing initial keyboard focus on Reject).
20
15
  */
21
16
 
22
17
  const MODE_LABEL: Record<string, string> = {
@@ -27,8 +22,6 @@ const MODE_LABEL: Record<string, string> = {
27
22
  };
28
23
 
29
24
  function summarizeArguments(args: Record<string, unknown>): string {
30
- // 'url' 必须在前列:批准一次 web_fetch 就是批准一次出网请求,
31
- // 用户必须看清目标地址(W5-2)。
32
25
  for (const key of ['url', 'command', 'cmd', 'path', 'file', 'target', 'query', 'content']) {
33
26
  const v = args[key];
34
27
  if (typeof v === 'string' && v.length > 0) {
@@ -111,17 +104,30 @@ export function ApprovalPromptMenu({
111
104
  pendingCount: number;
112
105
  onDecide: (kind: ApprovalDecisionKind) => void;
113
106
  }) {
107
+ const isOutward = current.checkpoint === 'outward';
108
+ const outwardRejectRef = useRef<HTMLButtonElement | null>(null);
109
+
110
+ useEffect(() => {
111
+ if (!isOutward) return;
112
+ outwardRejectRef.current?.focus();
113
+ const onWindowKeyDown = (e: KeyboardEvent) => {
114
+ if (e.key === 'Escape') {
115
+ e.preventDefault();
116
+ onDecide('deny_once');
117
+ }
118
+ };
119
+ window.addEventListener('keydown', onWindowKeyDown);
120
+ return () => window.removeEventListener('keydown', onWindowKeyDown);
121
+ }, [isOutward, current.requestId, onDecide]);
122
+
114
123
  const destructive = current.mode === 'destructive';
115
- // 网络出口拓宽(W-egress-ask):sidecar 的 web 工具被 egress 代理 403
116
- // 后发起。白名单是代理进程级的(会话寿命),所以「始终」变体对网络
117
- // 出口没有意义——只给一次性/会话两档,且默认焦点在拒绝(安全默认:
118
- // 用户能认出 api.github.com,认不出 cdn.jsdelivr.net.evil.com)。
119
124
  const isEgress = current.category === 'network_egress';
120
125
  const isSandboxEscalation = current.category === 'sandbox_escalation';
121
126
  const isBrowser = current.category === 'browser';
122
127
  const sandboxOff = current.sandboxEnforced === false;
123
128
  const outsideWorkspace =
124
129
  current.outsideWorkspace === true &&
130
+ !isOutward &&
125
131
  !isEgress &&
126
132
  !isSandboxEscalation &&
127
133
  !isBrowser &&
@@ -136,132 +142,188 @@ export function ApprovalPromptMenu({
136
142
  <div
137
143
  className="overflow-hidden rounded-agent-lg border border-agent-border bg-agent-canvas text-xs text-agent-foreground shadow-xl"
138
144
  data-testid="approval-composer"
145
+ onKeyDown={(e) => {
146
+ if (isOutward && e.key === 'Escape') {
147
+ e.preventDefault();
148
+ onDecide('deny_once');
149
+ }
150
+ }}
139
151
  >
140
- <div className="flex items-center gap-2 border-b border-agent-border px-3 py-2">
141
- {destructive ? (
142
- <LuTriangleAlert className="h-4 w-4 shrink-0 text-agent-destructive" />
143
- ) : (
144
- <LuShieldAlert className="h-4 w-4 shrink-0 text-amber-500" />
145
- )}
146
- <div className="min-w-0 flex-1">
147
- <div className="text-xs font-medium text-agent-foreground">
148
- {isEgress ? (
149
- <>
150
- {t('Agent requests internet access')}
151
- <span className="mx-1 font-mono">
152
- {egressHost}
153
- {egressPort !== null ? `:${egressPort}` : ''}
152
+ <div
153
+ className={`flex items-center gap-2 border-b px-3 py-2 ${
154
+ isOutward
155
+ ? 'border-rose-500/30 bg-rose-500/10'
156
+ : 'border-agent-border'
157
+ }`}
158
+ >
159
+ {isOutward ? (
160
+ <LuFlag className="h-4 w-4 shrink-0 text-agent-destructive" aria-hidden="true" />
161
+ ) : destructive ? (
162
+ <LuTriangleAlert className="h-4 w-4 shrink-0 text-agent-destructive" />
163
+ ) : (
164
+ <LuShieldAlert className="h-4 w-4 shrink-0 text-amber-500" />
165
+ )}
166
+ <div className="min-w-0 flex-1">
167
+ <div className="text-xs font-medium text-agent-foreground">
168
+ {isOutward ? (
169
+ <span data-testid="approval-outward-badge">
170
+ {t('Outward submission · manual confirmation required every time')}
171
+ <span className="mx-1 font-mono">{current.toolName}</span>
172
+ </span>
173
+ ) : isEgress ? (
174
+ <>
175
+ {t('Agent requests internet access')}
176
+ <span className="mx-1 font-mono">
177
+ {egressHost}
178
+ {egressPort !== null ? `:${egressPort}` : ''}
179
+ </span>
180
+ {current.categoryLabel ? (
181
+ <span className="text-agent-muted-foreground">
182
+ {t('({category})', { category: categoryName(current.categoryLabel) })}
183
+ </span>
184
+ ) : null}
185
+ </>
186
+ ) : isSandboxEscalation ? (
187
+ <>
188
+ {t('Agent requests to run a command outside the workspace')}
189
+ {current.categoryLabel ? (
190
+ <span className="ml-1 text-agent-muted-foreground">
191
+ {t('({category})', { category: categoryName(current.categoryLabel) })}
154
192
  </span>
155
- {current.categoryLabel ? (
156
- <span className="text-agent-muted-foreground">
157
- {t('({category})', { category: categoryName(current.categoryLabel) })}
158
- </span>
159
- ) : null}
160
- </>
161
- ) : isSandboxEscalation ? (
162
- <>
163
- {t('Agent requests to run a command outside the workspace')}
164
- {current.categoryLabel ? (
165
- <span className="ml-1 text-agent-muted-foreground">
166
- {t('({category})', { category: categoryName(current.categoryLabel) })}
167
- </span>
168
- ) : null}
169
- </>
170
- ) : isBrowser && current.toolName === 'browser_navigate' ? (
171
- <>
172
- {t('Agent requests to open a page')}
173
- <span className="mx-1 font-mono">{current.toolName}</span>
174
- {current.categoryLabel ? (
175
- <span className="text-agent-muted-foreground">
176
- {t('({category})', { category: categoryName(current.categoryLabel) })}
177
- </span>
178
- ) : null}
179
- </>
180
- ) : (
181
- <>
182
- {t('Agent requests to run')}
183
- <span className="mx-1 font-mono">{current.toolName}</span>
193
+ ) : null}
194
+ </>
195
+ ) : isBrowser && current.toolName === 'browser_navigate' ? (
196
+ <>
197
+ {t('Agent requests to open a page')}
198
+ <span className="mx-1 font-mono">{current.toolName}</span>
199
+ {current.categoryLabel ? (
184
200
  <span className="text-agent-muted-foreground">
185
- {current.categoryLabel
186
- ? t('({category})', { category: categoryName(current.categoryLabel) })
187
- : t('({mode} action)', {
188
- mode: MODE_LABEL[current.mode] ? t(MODE_LABEL[current.mode]) : current.mode,
189
- })}
201
+ {t('({category})', { category: categoryName(current.categoryLabel) })}
190
202
  </span>
191
- </>
192
- )}
193
- </div>
194
- {pendingCount > 0 && (
195
- <div className="mt-0.5 text-[11px] text-agent-muted-foreground">
196
- {t('{count} more awaiting approval', { count: pendingCount })}
197
- </div>
203
+ ) : null}
204
+ </>
205
+ ) : (
206
+ <>
207
+ {t('Agent requests to run')}
208
+ <span className="mx-1 font-mono">{current.toolName}</span>
209
+ <span className="text-agent-muted-foreground">
210
+ {current.categoryLabel
211
+ ? t('({category})', { category: categoryName(current.categoryLabel) })
212
+ : t('({mode} action)', {
213
+ mode: MODE_LABEL[current.mode] ? t(MODE_LABEL[current.mode]) : current.mode,
214
+ })}
215
+ </span>
216
+ </>
198
217
  )}
199
218
  </div>
219
+ {pendingCount > 0 && (
220
+ <div className="mt-0.5 text-[11px] text-agent-muted-foreground">
221
+ {t('{count} more awaiting approval', { count: pendingCount })}
222
+ </div>
223
+ )}
200
224
  </div>
225
+ </div>
201
226
 
202
- <div className="max-h-48 overflow-auto px-3 py-2">
203
- <pre className="whitespace-pre-wrap break-all rounded-agent-md bg-agent-muted/50 px-3 py-2 font-mono text-xs text-agent-foreground">
204
- {summarizeArguments(current.arguments)}
205
- </pre>
206
- {isEgress ? (
207
- <p className="mt-2 text-[11px] leading-relaxed text-agent-muted-foreground">
208
- {t(
209
- 'This domain is not on the egress allowlist. Check the full spelling before allowing it (lookalike domains often use similar spellings, such as cdn.jsdelivr.net.evil.com). Allowing it applies only to this chat. To allow it permanently, add the domain to the egress allowlist in Settings.',
210
- )}
211
- </p>
212
- ) : isSandboxEscalation ? (
213
- <p className="mt-2 text-[11px] leading-relaxed text-agent-muted-foreground">
214
- {t(
215
- 'The workspace sandbox blocked this command. Allowing it retries only this command, without limiting where it can write.',
216
- )}
217
- </p>
218
- ) : isBrowser ? (
219
- <p className="mt-2 text-[11px] leading-relaxed text-agent-muted-foreground">
220
- {t(
221
- 'Opening pages, clicking, filling, and pressing keys act on that site and can send information off this computer. Scrolling, reading, and screenshots do not need approval.',
222
- )}
223
- </p>
224
- ) : outsideWorkspace ? (
225
- <p className="mt-2 text-[11px] leading-relaxed text-agent-muted-foreground">
226
- {current.outsideWorkspaceKind === 'workspace'
227
- ? cwd
228
- ? t(
229
- 'The command runs in the sandbox. Working directory {cwd} is outside this chat workspace, so writes there are blocked.',
230
- { cwd },
231
- )
232
- : t(
233
- 'The command runs in the sandbox. Its working directory is outside this chat workspace, so writes there are blocked.',
234
- )
235
- : cwd
236
- ? t(
237
- 'The command runs in the sandbox. Working directory {cwd} is outside the project, so writes there are blocked. Add that directory as a project source folder when a write is required.',
238
- { cwd },
239
- )
240
- : t(
241
- 'The command runs in the sandbox. Its working directory is outside the project, so writes there are blocked. Add that directory as a project source folder when a write is required.',
242
- )}
243
- </p>
244
- ) : (
245
- <>
246
- {current.category !== current.toolName && (
247
- <p className="mt-2 text-[11px] text-agent-muted-foreground">
248
- {t(
249
- 'Saved category: {category} (a chat or always decision applies to every call in this category)',
250
- { category: current.category },
251
- )}
252
- </p>
253
- )}
254
- {!sandboxOff && (
255
- <p className="mt-2 text-[11px] leading-relaxed text-agent-muted-foreground">
256
- {t(
257
- 'Runs in the workspace sandbox. Writes outside it are blocked. To write outside, switch the sandbox to "Full access" and try again.',
227
+ <div className="max-h-48 overflow-auto px-3 py-2">
228
+ <pre className="whitespace-pre-wrap break-all rounded-agent-md bg-agent-muted/50 px-3 py-2 font-mono text-xs text-agent-foreground">
229
+ {summarizeArguments(current.arguments)}
230
+ </pre>
231
+ {isOutward ? (
232
+ <p className="mt-2 text-[11px] leading-relaxed text-agent-muted-foreground">
233
+ {t(
234
+ 'This action submits data to an external system or modifies authoritative records. Session and permanent auto-allow grants are disabled.',
235
+ )}
236
+ </p>
237
+ ) : isEgress ? (
238
+ <p className="mt-2 text-[11px] leading-relaxed text-agent-muted-foreground">
239
+ {t(
240
+ 'This domain is not on the egress allowlist. Check the full spelling before allowing it (lookalike domains often use similar spellings, such as cdn.jsdelivr.net.evil.com). Allowing it applies only to this chat. To allow it permanently, add the domain to the egress allowlist in Settings.',
241
+ )}
242
+ </p>
243
+ ) : isSandboxEscalation ? (
244
+ <p className="mt-2 text-[11px] leading-relaxed text-agent-muted-foreground">
245
+ {t(
246
+ 'The workspace sandbox blocked this command. Allowing it retries only this command, without limiting where it can write.',
247
+ )}
248
+ </p>
249
+ ) : isBrowser ? (
250
+ <p className="mt-2 text-[11px] leading-relaxed text-agent-muted-foreground">
251
+ {t(
252
+ 'Opening pages, clicking, filling, and pressing keys act on that site and can send information off this computer. Scrolling, reading, and screenshots do not need approval.',
253
+ )}
254
+ </p>
255
+ ) : outsideWorkspace ? (
256
+ <p className="mt-2 text-[11px] leading-relaxed text-agent-muted-foreground">
257
+ {current.outsideWorkspaceKind === 'workspace'
258
+ ? cwd
259
+ ? t(
260
+ 'The command runs in the sandbox. Working directory {cwd} is outside this chat workspace, so writes there are blocked.',
261
+ { cwd },
262
+ )
263
+ : t(
264
+ 'The command runs in the sandbox. Its working directory is outside this chat workspace, so writes there are blocked.',
265
+ )
266
+ : cwd
267
+ ? t(
268
+ 'The command runs in the sandbox. Working directory {cwd} is outside the project, so writes there are blocked. Add that directory as a project source folder when a write is required.',
269
+ { cwd },
270
+ )
271
+ : t(
272
+ 'The command runs in the sandbox. Its working directory is outside the project, so writes there are blocked. Add that directory as a project source folder when a write is required.',
258
273
  )}
259
- </p>
260
- )}
261
- </>
262
- )}
263
- </div>
274
+ </p>
275
+ ) : (
276
+ <>
277
+ {current.category !== current.toolName && (
278
+ <p className="mt-2 text-[11px] text-agent-muted-foreground">
279
+ {t(
280
+ 'Saved category: {category} (a chat or always decision applies to every call in this category)',
281
+ { category: current.category },
282
+ )}
283
+ </p>
284
+ )}
285
+ {!sandboxOff && (
286
+ <p className="mt-2 text-[11px] leading-relaxed text-agent-muted-foreground">
287
+ {t(
288
+ 'Runs in the workspace sandbox. Writes outside it are blocked. To write outside, switch the sandbox to "Full access" and try again.',
289
+ )}
290
+ </p>
291
+ )}
292
+ </>
293
+ )}
294
+ </div>
264
295
 
296
+ {isOutward ? (
297
+ <div className="flex flex-wrap items-center justify-between gap-2 border-t border-agent-border px-3 py-2">
298
+ <div className="flex flex-wrap items-center gap-2">
299
+ <button
300
+ ref={outwardRejectRef}
301
+ type="button"
302
+ data-testid="approval-deny_once"
303
+ onClick={() => onDecide('deny_once')}
304
+ className="rounded-agent-md border border-agent-border px-3 py-1.5 text-xs font-medium text-agent-foreground transition hover:bg-agent-muted"
305
+ >
306
+ {t('Reject this submission')}
307
+ </button>
308
+ <button
309
+ type="button"
310
+ data-testid="approval-abort"
311
+ onClick={() => onDecide('abort')}
312
+ className="rounded-agent-md bg-agent-destructive px-3 py-1.5 text-xs font-medium text-white transition hover:opacity-90"
313
+ >
314
+ {t('Abort this turn')}
315
+ </button>
316
+ </div>
317
+ <button
318
+ type="button"
319
+ data-testid="approval-allow_once"
320
+ onClick={() => onDecide('allow_once')}
321
+ className="rounded-agent-md bg-agent-foreground px-3 py-1.5 text-xs font-medium text-agent-canvas transition hover:opacity-90"
322
+ >
323
+ {t('Approve this submission')}
324
+ </button>
325
+ </div>
326
+ ) : (
265
327
  <div className="space-y-2 border-t border-agent-border px-3 py-2">
266
328
  <DecisionRow
267
329
  buttons={
@@ -295,6 +357,7 @@ export function ApprovalPromptMenu({
295
357
  : t('"This chat" applies only to this chat. "Always" is saved on this computer and applies to every chat.')}
296
358
  </p>
297
359
  </div>
360
+ )}
298
361
  </div>
299
362
  );
300
363
  }
@@ -0,0 +1,88 @@
1
+ import { useState } from 'react';
2
+ import { t } from '@/i18n';
3
+ import { getHostBridge, hasHostBridge } from '@/lib/host-bridge';
4
+
5
+ export interface MemorySaveNoticeBarProps {
6
+ refinementId: string;
7
+ scope?: 'user' | 'workspace' | 'tenant';
8
+ chatId?: string;
9
+ workspaceId?: string;
10
+ onEdit?: () => void;
11
+ onWithdrawn?: (refinementId: string) => void;
12
+ }
13
+
14
+ export function MemorySaveNoticeBar({
15
+ refinementId,
16
+ scope = 'workspace',
17
+ chatId,
18
+ workspaceId,
19
+ onEdit,
20
+ onWithdrawn,
21
+ }: MemorySaveNoticeBarProps) {
22
+ const [withdrawn, setWithdrawn] = useState(false);
23
+
24
+ const handleWithdraw = async () => {
25
+ const path = `/api/v2/memory/refinements/${encodeURIComponent(refinementId)}/withdraw`;
26
+ const body = {
27
+ ...(chatId ? { chatId } : {}),
28
+ ...(workspaceId ? { workspaceId } : {}),
29
+ };
30
+ if (hasHostBridge()) {
31
+ await getHostBridge()?.localBackend.request({ method: 'POST', path, body });
32
+ } else {
33
+ await fetch(path, {
34
+ method: 'POST',
35
+ headers: { 'Content-Type': 'application/json' },
36
+ body: JSON.stringify(body),
37
+ });
38
+ }
39
+ setWithdrawn(true);
40
+ onWithdrawn?.(refinementId);
41
+ };
42
+
43
+ if (withdrawn) {
44
+ return (
45
+ <div
46
+ data-testid="memory-notice-withdrawn"
47
+ className="mt-1.5 flex items-center gap-2 text-[11px] text-agent-muted-foreground"
48
+ >
49
+ <span>{t('Withdrawn from memory and blocked from re-learning.')}</span>
50
+ </div>
51
+ );
52
+ }
53
+
54
+ const label =
55
+ scope === 'user'
56
+ ? t('Remembered personal preference')
57
+ : t('Remembered project preference');
58
+
59
+ return (
60
+ <div
61
+ data-testid="memory-save-notice-bar"
62
+ className="mt-1.5 flex flex-wrap items-center gap-2 text-[11px] text-agent-muted-foreground"
63
+ >
64
+ <span>{label}</span>
65
+ <span>·</span>
66
+ {onEdit ? (
67
+ <button
68
+ type="button"
69
+ data-testid="memory-notice-edit"
70
+ onClick={onEdit}
71
+ className="underline hover:text-agent-foreground"
72
+ >
73
+ {t('Edit')}
74
+ </button>
75
+ ) : null}
76
+ <button
77
+ type="button"
78
+ data-testid="memory-notice-withdraw"
79
+ onClick={() => void handleWithdraw()}
80
+ className="underline hover:text-rose-600"
81
+ >
82
+ {t('Withdraw')}
83
+ </button>
84
+ </div>
85
+ );
86
+ }
87
+
88
+ export default MemorySaveNoticeBar;
@@ -0,0 +1,370 @@
1
+ import { useCallback, useEffect, useState } from 'react';
2
+ import { t } from '@/i18n';
3
+ import { getHostBridge, hasHostBridge } from '@/lib/host-bridge';
4
+
5
+ export type MemoryScopeTab = 'user' | 'workspace' | 'tenant';
6
+ export type MemoryPermissionMode = 'off' | 'ask' | 'auto';
7
+
8
+ export interface RefinementItemDto {
9
+ id: string;
10
+ normalizedHash: string;
11
+ scope: MemoryScopeTab;
12
+ content: string;
13
+ humanEdited: boolean;
14
+ status: 'active' | 'ordinary' | 'withdrawn';
15
+ createdAt: string;
16
+ expiresAt: string | null;
17
+ }
18
+
19
+ interface MemoryApiResponse {
20
+ permissionMode: MemoryPermissionMode;
21
+ scope: MemoryScopeTab;
22
+ scopeId: string;
23
+ contentMarkdown: string;
24
+ contentSha256: string;
25
+ bytesUsed: number;
26
+ maxBytes: number;
27
+ linesUsed: number;
28
+ maxLines: number;
29
+ refinements: RefinementItemDto[];
30
+ revokedHashes: string[];
31
+ }
32
+
33
+ async function requestMemoryApi(
34
+ method: 'GET' | 'PUT' | 'POST' | 'DELETE',
35
+ path: string,
36
+ body?: Record<string, unknown>,
37
+ ): Promise<{ status: number; data: Record<string, unknown> }> {
38
+ if (hasHostBridge()) {
39
+ const bridge = getHostBridge();
40
+ if (!bridge?.localBackend) return { status: 503, data: {} };
41
+ try {
42
+ const res = await bridge.localBackend.request<Record<string, unknown>>({
43
+ method,
44
+ path,
45
+ body,
46
+ });
47
+ if (
48
+ res &&
49
+ typeof res === 'object' &&
50
+ typeof (res as { status?: unknown }).status === 'number' &&
51
+ 'data' in res
52
+ ) {
53
+ return {
54
+ status: Number((res as { status: number }).status),
55
+ data: ((res as { data?: unknown }).data ?? {}) as Record<string, unknown>,
56
+ };
57
+ }
58
+ return { status: 200, data: (res ?? {}) as Record<string, unknown> };
59
+ } catch (err) {
60
+ const status =
61
+ typeof (err as { status?: unknown })?.status === 'number'
62
+ ? Number((err as { status: number }).status)
63
+ : 500;
64
+ return {
65
+ status,
66
+ data: { message: err instanceof Error ? err.message : String(err) },
67
+ };
68
+ }
69
+ }
70
+ if (typeof fetch !== 'function' || !path.startsWith('http') && typeof window !== 'undefined' && window.location?.origin === 'null') {
71
+ return { status: 503, data: {} };
72
+ }
73
+ try {
74
+ const resp = await fetch(path, {
75
+ method,
76
+ headers: body ? { 'Content-Type': 'application/json' } : undefined,
77
+ body: body ? JSON.stringify(body) : undefined,
78
+ });
79
+ const json = (await resp.json().catch(() => ({}))) as Record<string, unknown>;
80
+ return { status: resp.status, data: json };
81
+ } catch {
82
+ return { status: 503, data: {} };
83
+ }
84
+ }
85
+
86
+ export interface MemorySettingsPanelProps {
87
+ workspaceId?: string;
88
+ showTenantTab?: boolean;
89
+ isAdmin?: boolean;
90
+ }
91
+
92
+ export function MemorySettingsPanel({
93
+ workspaceId = 'default',
94
+ showTenantTab = false,
95
+ isAdmin = true,
96
+ }: MemorySettingsPanelProps) {
97
+ const [scope, setScope] = useState<MemoryScopeTab>('user');
98
+ const [permissionMode, setPermissionMode] = useState<MemoryPermissionMode>('ask');
99
+ const [markdown, setMarkdown] = useState('');
100
+ const [baseHash, setBaseHash] = useState('');
101
+ const [bytesUsed, setBytesUsed] = useState(0);
102
+ const [maxBytes, setMaxBytes] = useState(16384);
103
+ const [refinements, setRefinements] = useState<RefinementItemDto[]>([]);
104
+ const [revokedHashes, setRevokedHashes] = useState<string[]>([]);
105
+ const [conflictBanner, setConflictBanner] = useState(false);
106
+ const [saving, setSaving] = useState(false);
107
+
108
+ const loadScope = useCallback(
109
+ async (targetScope: MemoryScopeTab) => {
110
+ const scopeParam =
111
+ targetScope === 'workspace' ? `&scopeId=${encodeURIComponent(workspaceId)}` : '';
112
+ const res = await requestMemoryApi(
113
+ 'GET',
114
+ `/api/v2/memory?scope=${targetScope}${scopeParam}`,
115
+ );
116
+ if (res.status === 200) {
117
+ const d = res.data as unknown as MemoryApiResponse;
118
+ setPermissionMode(d.permissionMode ?? 'ask');
119
+ setMarkdown(d.contentMarkdown ?? '');
120
+ setBaseHash(d.contentSha256 ?? '');
121
+ setBytesUsed(d.bytesUsed ?? 0);
122
+ setMaxBytes(d.maxBytes || 16384);
123
+ setRefinements(Array.isArray(d.refinements) ? d.refinements : []);
124
+ setRevokedHashes(Array.isArray(d.revokedHashes) ? d.revokedHashes : []);
125
+ setConflictBanner(false);
126
+ }
127
+ },
128
+ [workspaceId],
129
+ );
130
+
131
+ useEffect(() => {
132
+ void loadScope(scope);
133
+ }, [scope, loadScope]);
134
+
135
+ const handleModeChange = async (nextMode: MemoryPermissionMode) => {
136
+ setPermissionMode(nextMode);
137
+ await requestMemoryApi('PUT', '/api/v2/memory', { permissionMode: nextMode });
138
+ };
139
+
140
+ const readOnly = scope === 'tenant' && !isAdmin;
141
+
142
+ const handleSave = async () => {
143
+ if (readOnly) return;
144
+ setSaving(true);
145
+ try {
146
+ const res = await requestMemoryApi('PUT', '/api/v2/memory', {
147
+ scope,
148
+ ...(scope === 'workspace' ? { scopeId: workspaceId } : {}),
149
+ contentMarkdown: markdown,
150
+ baseHash,
151
+ });
152
+ if (res.status === 409) {
153
+ setConflictBanner(true);
154
+ return;
155
+ }
156
+ if (res.status === 200) {
157
+ await loadScope(scope);
158
+ }
159
+ } finally {
160
+ setSaving(false);
161
+ }
162
+ };
163
+
164
+ const handleRefinementAction = async (
165
+ id: string,
166
+ action: 'renew' | 'convert' | 'withdraw',
167
+ ) => {
168
+ await requestMemoryApi('POST', `/api/v2/memory/refinements/${encodeURIComponent(id)}/${action}`, {
169
+ workspaceId,
170
+ });
171
+ await loadScope(scope);
172
+ };
173
+
174
+ const activeRefinements = refinements.filter((r) => r.status === 'active');
175
+ const ratio = Math.min(100, Math.round((bytesUsed / Math.max(1, maxBytes)) * 100));
176
+
177
+ return (
178
+ <div
179
+ data-testid="memory-settings-panel"
180
+ className="space-y-4 rounded-xl border border-agent-border bg-agent-card p-4 text-xs"
181
+ >
182
+ {/* Top bar: permission mode + quota meter */}
183
+ <div className="flex flex-wrap items-center justify-between gap-3">
184
+ <div className="flex items-center gap-1.5" role="radiogroup" aria-label={t('Memory mode')}>
185
+ {(
186
+ [
187
+ ['off', t('Off')],
188
+ ['ask', t('Ask before saving')],
189
+ ['auto', t('Remember automatically')],
190
+ ] as const
191
+ ).map(([val, label]) => (
192
+ <button
193
+ key={val}
194
+ type="button"
195
+ data-testid={`memory-mode-${val}`}
196
+ onClick={() => void handleModeChange(val)}
197
+ className={`rounded-md px-2.5 py-1 text-xs transition ${
198
+ permissionMode === val
199
+ ? 'bg-agent-foreground font-semibold text-agent-background'
200
+ : 'border border-agent-border text-agent-muted-foreground hover:text-agent-foreground'
201
+ }`}
202
+ >
203
+ {label}
204
+ </button>
205
+ ))}
206
+ </div>
207
+ <div className="flex items-center gap-2 text-[11px] text-agent-muted-foreground">
208
+ <span data-testid="memory-quota-label">
209
+ {(bytesUsed / 1024).toFixed(1)} / {(maxBytes / 1024).toFixed(1)} KB
210
+ </span>
211
+ <div className="h-1.5 w-24 overflow-hidden rounded-full bg-agent-border">
212
+ <div className="h-full bg-agent-foreground" style={{ width: `${ratio}%` }} />
213
+ </div>
214
+ </div>
215
+ </div>
216
+
217
+ {/* Scope tabs */}
218
+ <div className="flex items-center gap-2 border-b border-agent-border pb-2">
219
+ <button
220
+ type="button"
221
+ data-testid="memory-tab-user"
222
+ onClick={() => setScope('user')}
223
+ className={`rounded px-2.5 py-1 ${
224
+ scope === 'user' ? 'bg-agent-foreground/10 font-semibold' : 'text-agent-muted-foreground'
225
+ }`}
226
+ >
227
+ {t('Personal memory')}
228
+ </button>
229
+ <button
230
+ type="button"
231
+ data-testid="memory-tab-workspace"
232
+ onClick={() => setScope('workspace')}
233
+ className={`rounded px-2.5 py-1 ${
234
+ scope === 'workspace'
235
+ ? 'bg-agent-foreground/10 font-semibold'
236
+ : 'text-agent-muted-foreground'
237
+ }`}
238
+ >
239
+ {t('Project memory')}
240
+ </button>
241
+ {showTenantTab ? (
242
+ <button
243
+ type="button"
244
+ data-testid="memory-tab-tenant"
245
+ onClick={() => setScope('tenant')}
246
+ className={`rounded px-2.5 py-1 ${
247
+ scope === 'tenant'
248
+ ? 'bg-agent-foreground/10 font-semibold'
249
+ : 'text-agent-muted-foreground'
250
+ }`}
251
+ >
252
+ {t('Department shared rules')}
253
+ </button>
254
+ ) : null}
255
+ </div>
256
+
257
+ {/* Optimistic lock conflict banner */}
258
+ {conflictBanner ? (
259
+ <div
260
+ role="alert"
261
+ data-testid="memory-conflict-banner"
262
+ className="flex items-center justify-between gap-2 rounded-lg border border-amber-500/40 bg-amber-500/10 px-3 py-2 text-amber-900 dark:text-amber-200"
263
+ >
264
+ <span>{t('Memory changed in another session. Reload before saving.')}</span>
265
+ <button
266
+ type="button"
267
+ data-testid="memory-conflict-reload"
268
+ onClick={() => void loadScope(scope)}
269
+ className="rounded bg-amber-600 px-2 py-1 text-white"
270
+ >
271
+ {t('Reload')}
272
+ </button>
273
+ </div>
274
+ ) : null}
275
+
276
+ {/* MEMORY.md editor */}
277
+ <div className="space-y-2">
278
+ <textarea
279
+ rows={6}
280
+ readOnly={readOnly}
281
+ value={markdown}
282
+ onChange={(e) => setMarkdown(e.target.value)}
283
+ aria-label={t('Memory markdown editor')}
284
+ data-testid="memory-markdown-editor"
285
+ className="w-full rounded-lg border border-agent-border bg-agent-background p-2.5 font-mono text-xs"
286
+ />
287
+ {!readOnly ? (
288
+ <div className="flex justify-end">
289
+ <button
290
+ type="button"
291
+ disabled={saving}
292
+ onClick={() => void handleSave()}
293
+ data-testid="memory-save-btn"
294
+ className="rounded-md bg-agent-foreground px-3 py-1.5 text-xs font-medium text-agent-background disabled:opacity-50"
295
+ >
296
+ {t('Save memory')}
297
+ </button>
298
+ </div>
299
+ ) : (
300
+ <p className="text-[11px] text-agent-muted-foreground">
301
+ {t('Read-only: only administrators can edit department shared rules.')}
302
+ </p>
303
+ )}
304
+ </div>
305
+
306
+ {/* Active RSI refinement review queue */}
307
+ {activeRefinements.length > 0 ? (
308
+ <div className="space-y-2 border-t border-agent-border pt-3">
309
+ <div className="font-semibold text-agent-foreground">
310
+ {t('Refinement notes pending review (30-day expiry)')}
311
+ </div>
312
+ {activeRefinements.map((item) => (
313
+ <div
314
+ key={item.id}
315
+ data-testid={`memory-refinement-${item.id}`}
316
+ className="flex flex-wrap items-center justify-between gap-2 rounded-lg border border-agent-border p-2.5"
317
+ >
318
+ <div className="space-y-0.5">
319
+ <div className="text-agent-foreground">{item.content}</div>
320
+ <div className="font-mono text-[11px] text-agent-muted-foreground">
321
+ {item.id}
322
+ {item.expiresAt ? ` · ${t('Expires')} ${item.expiresAt.slice(0, 10)}` : ''}
323
+ </div>
324
+ </div>
325
+ {!readOnly ? (
326
+ <div className="flex items-center gap-1.5">
327
+ <button
328
+ type="button"
329
+ data-testid={`memory-renew-${item.id}`}
330
+ onClick={() => void handleRefinementAction(item.id, 'renew')}
331
+ className="rounded border border-agent-border px-2 py-1 hover:bg-agent-foreground/5"
332
+ >
333
+ {t('Renew 30d')}
334
+ </button>
335
+ <button
336
+ type="button"
337
+ data-testid={`memory-convert-${item.id}`}
338
+ onClick={() => void handleRefinementAction(item.id, 'convert')}
339
+ className="rounded border border-agent-border px-2 py-1 hover:bg-agent-foreground/5"
340
+ >
341
+ {t('Make ordinary')}
342
+ </button>
343
+ <button
344
+ type="button"
345
+ data-testid={`memory-withdraw-${item.id}`}
346
+ onClick={() => void handleRefinementAction(item.id, 'withdraw')}
347
+ className="rounded border border-rose-500/40 px-2 py-1 text-rose-600 hover:bg-rose-500/10"
348
+ >
349
+ {t('Withdraw')}
350
+ </button>
351
+ </div>
352
+ ) : null}
353
+ </div>
354
+ ))}
355
+ </div>
356
+ ) : null}
357
+
358
+ {/* Revoked hashes count */}
359
+ {revokedHashes.length > 0 ? (
360
+ <div className="text-[11px] text-agent-muted-foreground" data-testid="memory-revoked-summary">
361
+ {t('{count} withdrawn items blocked from re-learning.', {
362
+ count: String(revokedHashes.length),
363
+ })}
364
+ </div>
365
+ ) : null}
366
+ </div>
367
+ );
368
+ }
369
+
370
+ export default MemorySettingsPanel;
@@ -8,6 +8,13 @@ import { TaskProcessPanel, type InspectedTask } from '@/components/chat/TaskProc
8
8
  import { AskUserPromptProvider } from '@/components/chat/AskUserPromptProvider';
9
9
  import { ApprovalPromptProvider } from '@/components/chat/ApprovalPromptProvider';
10
10
  import { InsightsConsentBanner } from '@/components/settings/InsightsSettingsPanel';
11
+ import { SafeRecoveryBanner } from '@/components/SafeRecoveryBanner';
12
+ import {
13
+ fetchActiveApplication,
14
+ isSafeRecoveryMode,
15
+ type ActiveApplicationState,
16
+ type HiddenNavItem,
17
+ } from '@/lib/safe-mode';
11
18
  import { trackBehavior } from '@/lib/insights';
12
19
  import { getHostBridge, hasHostBridge } from '@/lib/host-bridge';
13
20
  import { deleteChatIfEmpty, pruneEmptyChats } from '@/lib/local-api';
@@ -694,6 +701,33 @@ function AgentLayoutContent() {
694
701
  trackBehavior('app_open', { path: window.location.hash || '#/' });
695
702
  }, []);
696
703
 
704
+ const [safeModeActive, setSafeModeActive] = useState<boolean>(() => isSafeRecoveryMode());
705
+ const [activeApp, setActiveApp] = useState<ActiveApplicationState | null>(null);
706
+
707
+ useEffect(() => {
708
+ const syncSafe = () => setSafeModeActive(isSafeRecoveryMode());
709
+ window.addEventListener('hashchange', syncSafe);
710
+ window.addEventListener('popstate', syncSafe);
711
+ return () => {
712
+ window.removeEventListener('hashchange', syncSafe);
713
+ window.removeEventListener('popstate', syncSafe);
714
+ };
715
+ }, []);
716
+
717
+ useEffect(() => {
718
+ let cancelled = false;
719
+ void fetchActiveApplication(safeModeActive).then((app) => {
720
+ if (!cancelled) setActiveApp(app);
721
+ });
722
+ return () => {
723
+ cancelled = true;
724
+ };
725
+ }, [safeModeActive]);
726
+
727
+ const hiddenNavItems: readonly HiddenNavItem[] = safeModeActive
728
+ ? []
729
+ : (activeApp?.hiddenNavItems ?? []);
730
+
697
731
  return (
698
732
  <div className="relative flex h-full w-full bg-agent-muted/30">
699
733
  {sidebarCollapsed ? (
@@ -719,6 +753,7 @@ function AgentLayoutContent() {
719
753
  rightPanel={rightPanel}
720
754
  onToggleRightPanel={toggleRightPanel}
721
755
  onCollapse={toggleSidebarCollapsed}
756
+ hiddenNavItems={hiddenNavItems}
722
757
  />
723
758
  </div>
724
759
  {/* Drag handle — 1px wide, 4px hit area via padding. */}
@@ -736,6 +771,14 @@ function AgentLayoutContent() {
736
771
  <div className="h-full min-w-0 flex-1 p-1.5">
737
772
  <div className="flex h-full w-full">
738
773
  <div className="flex h-full min-w-0 flex-1 flex-col overflow-hidden rounded-agent-lg bg-agent-canvas shadow-sm">
774
+ {safeModeActive && (
775
+ <SafeRecoveryBanner
776
+ onResetComplete={() => {
777
+ setSafeModeActive(false);
778
+ void fetchActiveApplication(false).then(setActiveApp);
779
+ }}
780
+ />
781
+ )}
739
782
  <div className="min-h-0 flex-1 overflow-hidden">
740
783
  <Outlet
741
784
  context={{
@@ -742,6 +742,79 @@ async function request<T>(input: LocalBackendRequestInput): Promise<T> {
742
742
  } as T;
743
743
  }
744
744
 
745
+ if (method === 'GET' && cleanPath === '/api/v2/auth/bootstrap') {
746
+ return {
747
+ applicationId: 'default',
748
+ safeMode: false,
749
+ brand: { displayName: 'Steerable Workbench' },
750
+ authMethods: [{ kind: 'local', id: 'local', label: 'Local session' }],
751
+ } as T;
752
+ }
753
+
754
+ if (method === 'GET' && cleanPath === '/api/v2/applications') {
755
+ return {
756
+ activeApplicationId: 'default',
757
+ safeMode: false,
758
+ applications: [
759
+ {
760
+ id: 'default',
761
+ name: 'Default Workbench',
762
+ description: 'Standard full-featured agent workbench',
763
+ },
764
+ ],
765
+ } as T;
766
+ }
767
+
768
+ if (method === 'GET' && cleanPath === '/api/v2/memory') {
769
+ const scope = parseQuery(path).get('scope') ?? 'user';
770
+ return {
771
+ scope,
772
+ scopeId: scope === 'user' ? 'demo-user' : 'default',
773
+ permissionMode: 'ask',
774
+ markdown: '- Prefer concise tables with source citations.\n',
775
+ baseHash: 'demo00000001',
776
+ bytesUsed: 46,
777
+ maxBytes: 16_384,
778
+ linesUsed: 1,
779
+ maxLines: 200,
780
+ canWrite: true,
781
+ entries: [
782
+ {
783
+ id: 'mem-demo-1',
784
+ kind: 'ordinary',
785
+ content: 'Prefer concise tables with source citations.',
786
+ contentHash: 'demo00000001',
787
+ createdAt: new Date().toISOString(),
788
+ updatedAt: new Date().toISOString(),
789
+ humanEdited: true,
790
+ },
791
+ ],
792
+ } as T;
793
+ }
794
+
795
+ if (method === 'GET' && /^\/api\/v2\/chats\/[^/]+\/fact-chain$/.test(cleanPath)) {
796
+ const chatId = decodeURIComponent(cleanPath.split('/')[4] ?? 'demo');
797
+ return {
798
+ chatId,
799
+ evidenceStatus: 'complete',
800
+ requestNode: {
801
+ messageId: 'msg-demo-1',
802
+ promptSummary: 'Summarize weekly invoices and export a verified report.',
803
+ policyDigest: '9f86d081884c7d65',
804
+ },
805
+ toolNodes: [
806
+ {
807
+ id: 'tc-demo-1',
808
+ toolName: 'read_file',
809
+ argsSummary: '{"path":"invoices/2026-11.csv"}',
810
+ status: 'executed',
811
+ durationMs: 18,
812
+ },
813
+ ],
814
+ deliverableNodes: [],
815
+ } as T;
816
+ }
817
+
745
818
  if (method === 'GET' && cleanPath === '/api/v2/llm/presets') {
746
819
  return {
747
820
  presets: [
@@ -72,6 +72,8 @@ export interface ApprovalPromptRequest {
72
72
  * 缺省保持旧 sidecar 的说明。
73
73
  */
74
74
  sandboxEnforced?: boolean;
75
+ /** `'outward'` forces per-invocation human confirmation with no remembered grants. */
76
+ checkpoint?: 'standard' | 'outward';
75
77
  }
76
78
 
77
79
  /**
@@ -0,0 +1,83 @@
1
+ import { getHostBridge, hasHostBridge } from './host-bridge';
2
+
3
+ export type HiddenNavItem = 'skills' | 'mcp' | 'agents' | 'terminal';
4
+
5
+ export interface ActiveApplicationState {
6
+ readonly id: string;
7
+ readonly title: Readonly<Record<string, string>>;
8
+ readonly defaultAgentProfileId: string;
9
+ readonly allowedPackIds: readonly string[];
10
+ readonly defaultWorkbenchTabs: readonly string[];
11
+ readonly hiddenNavItems: readonly HiddenNavItem[];
12
+ readonly safeMode: boolean;
13
+ readonly customApplicationBypassed: boolean;
14
+ }
15
+
16
+ /**
17
+ * Detects `/?safe=1` (or `#/...?safe=1`) safe recovery mode so operators can
18
+ * always bypass a broken or overly restrictive ApplicationManifest.
19
+ */
20
+ export function isSafeRecoveryMode(
21
+ loc: Pick<Location, 'search' | 'hash'> | undefined =
22
+ typeof window !== 'undefined' ? window.location : undefined,
23
+ ): boolean {
24
+ if (!loc) return false;
25
+ if (new URLSearchParams(loc.search).get('safe') === '1') return true;
26
+ const hashQueryIdx = loc.hash.indexOf('?');
27
+ if (hashQueryIdx >= 0) {
28
+ const hashParams = new URLSearchParams(loc.hash.slice(hashQueryIdx + 1));
29
+ if (hashParams.get('safe') === '1') return true;
30
+ }
31
+ return false;
32
+ }
33
+
34
+ /** Strips `safe=1` from both `location.search` and `location.hash` after reset. */
35
+ export function stripSafeQueryParam(href: string): string {
36
+ try {
37
+ const url = new URL(href, 'http://localhost');
38
+ url.searchParams.delete('safe');
39
+ if (url.hash.includes('?')) {
40
+ const [hashPath, rawQuery] = url.hash.split('?', 2);
41
+ const hp = new URLSearchParams(rawQuery);
42
+ hp.delete('safe');
43
+ const qs = hp.toString();
44
+ url.hash = qs ? `${hashPath}?${qs}` : hashPath;
45
+ }
46
+ return `${url.pathname}${url.search}${url.hash}`;
47
+ } catch {
48
+ return '#/';
49
+ }
50
+ }
51
+
52
+ export async function fetchActiveApplication(
53
+ safeMode: boolean,
54
+ ): Promise<ActiveApplicationState | null> {
55
+ if (!hasHostBridge()) return null;
56
+ const b = getHostBridge();
57
+ if (!b) return null;
58
+ try {
59
+ const data = await b.localBackend.request<{ application?: ActiveApplicationState }>({
60
+ method: 'GET',
61
+ path: `/api/v2/applications/active${safeMode ? '?safe=1' : ''}`,
62
+ });
63
+ return data?.application ?? null;
64
+ } catch {
65
+ return null;
66
+ }
67
+ }
68
+
69
+ export async function resetToDefaultApplication(): Promise<boolean> {
70
+ if (!hasHostBridge()) return false;
71
+ const b = getHostBridge();
72
+ if (!b) return false;
73
+ try {
74
+ const data = await b.localBackend.request<{ application?: ActiveApplicationState }>({
75
+ method: 'POST',
76
+ path: '/api/v2/applications/reset',
77
+ body: {},
78
+ });
79
+ return Boolean(data?.application);
80
+ } catch {
81
+ return false;
82
+ }
83
+ }
@@ -2,6 +2,7 @@ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } fr
2
2
  import {
3
3
  LuActivity,
4
4
  LuBlocks,
5
+ LuBookOpen,
5
6
  LuBot,
6
7
  LuChartBar,
7
8
  LuCodeXml,
@@ -21,6 +22,7 @@ import { getLocale, t } from '@/i18n';
21
22
  import { useAppRelease } from '@/components/SidebarRelease';
22
23
  import { AgentsSettingsPanel } from '@/components/settings/AgentsSettingsPanel';
23
24
  import { AppearanceSettingsPanel } from '@/components/settings/AppearanceSettingsPanel';
25
+ import { MemorySettingsPanel } from '@/components/settings/MemorySettingsPanel';
24
26
  import { OrchestrationSettingsPanel } from '@/components/settings/OrchestrationSettingsPanel';
25
27
  import { AppUpdateSettingsPanel } from '@/components/settings/AppUpdateSettingsPanel';
26
28
  import { PortableSettingsPanel } from '@/components/settings/PortableSettingsPanel';
@@ -209,6 +211,7 @@ export function SettingsPage() {
209
211
  if (settingsChrome('security')) {
210
212
  list.push({ id: 'security', label: t('Security'), Icon: LuShieldCheck });
211
213
  }
214
+ list.push({ id: 'memory', label: t('Memory'), Icon: LuBookOpen });
212
215
  if (settingsChrome('insights')) {
213
216
  list.push({ id: 'insights', label: t('Help improve the product'), Icon: LuChartBar });
214
217
  }
@@ -471,6 +474,14 @@ export function SettingsPage() {
471
474
  </section>
472
475
  )}
473
476
 
477
+ <section className="space-y-2" data-testid="settings-section-memory">
478
+ <h2 className="flex items-center gap-1.5 text-xs font-semibold text-agent-foreground">
479
+ <LuBookOpen className="h-3.5 w-3.5 text-agent-muted-foreground" />
480
+ {t('Memory')}
481
+ </h2>
482
+ <MemorySettingsPanel />
483
+ </section>
484
+
474
485
  {settingsChrome('insights') && (
475
486
  <section className="space-y-2" data-testid="settings-section-insights">
476
487
  <h2 className="flex items-center gap-1.5 text-xs font-semibold text-agent-foreground">