@steerable/agent-shell-web 0.14.6 → 0.14.7

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.14.6",
3
+ "version": "0.14.7",
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.14.6",
49
- "@steerable/agent-ui": "0.14.6"
48
+ "@steerable/agent-protocol": "0.14.7",
49
+ "@steerable/agent-ui": "0.14.7"
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.14.6"
62
+ "@steerable/pack-sdk": "0.14.7"
63
63
  },
64
64
  "scripts": {
65
65
  "gen": "echo agent-shell-web",
@@ -95,7 +95,7 @@ import {
95
95
  LuX,
96
96
  } from "react-icons/lu";
97
97
  import { RiPushpin2Fill, RiPushpin2Line } from "react-icons/ri";
98
- import { parseChatTitle } from "@/lib/chat-title";
98
+ import { parseChatTitle, resolveChatDisplayTitle } from "@/lib/chat-title";
99
99
  import { chatRowKeys } from "@/lib/chat-row-keys";
100
100
  import { getDateGroupLabel, getDateGroupPriority } from "@/lib/date-groups";
101
101
  import { getHostBridge, hasHostBridge } from "@/lib/host-bridge";
@@ -938,7 +938,11 @@ export function AgentSidebar({
938
938
  const { displayTitle, isAutomation } = parseChatTitle(chat.title);
939
939
  return {
940
940
  id: chat.id,
941
- title: displayTitle || t("New conversation"),
941
+ title: resolveChatDisplayTitle(
942
+ displayTitle,
943
+ t("New conversation"),
944
+ chat.titleSource,
945
+ ),
942
946
  isAutomation,
943
947
  isPinned: chat.isPinned,
944
948
  sortDate: new Date(
@@ -51,6 +51,7 @@ import {
51
51
  import { hostToolChrome } from '@/lib/host-tools';
52
52
  import { PanelToggleButton } from '@/layouts/PanelToggleButton';
53
53
  import { t } from '@/i18n';
54
+ import { parseChatTitle, resolveChatDisplayTitle } from '@/lib/chat-title';
54
55
  import { forkSourceTime } from './chat/timestamp';
55
56
  import {
56
57
  getTurnFileCategory,
@@ -392,9 +393,23 @@ export function ChatHeader({
392
393
  <div className="flex min-w-0 flex-1 flex-wrap items-center gap-x-2 gap-y-0.5">
393
394
  <span
394
395
  className="break-words text-xs font-medium text-agent-foreground"
395
- title={chat?.title}
396
+ title={
397
+ chat
398
+ ? resolveChatDisplayTitle(
399
+ parseChatTitle(chat.title).displayTitle,
400
+ t('New conversation'),
401
+ chat.titleSource,
402
+ )
403
+ : undefined
404
+ }
396
405
  >
397
- {chat?.title ?? t('No chat selected')}
406
+ {chat
407
+ ? resolveChatDisplayTitle(
408
+ parseChatTitle(chat.title).displayTitle,
409
+ t('New conversation'),
410
+ chat.titleSource,
411
+ )
412
+ : t('No chat selected')}
398
413
  </span>
399
414
  {forkedFrom ? (
400
415
  <span
@@ -12,10 +12,11 @@ import {
12
12
  LuTriangleAlert,
13
13
  } from 'react-icons/lu';
14
14
  import type { ChatMessage } from '@steerable/agent-protocol';
15
- import type { LocalChat, LocalChatAgent } from '@/lib/local-api';
15
+ import type { LocalChat, LocalChatAgent, SavedMemoryNotice } from '@/lib/local-api';
16
16
  import { t } from '@/i18n';
17
17
  import { CurrentMessageIdContext } from '@/lib/chat-mode-store';
18
18
  import { Markdown } from './Markdown';
19
+ import { MemorySaveNoticeBar } from './MemorySaveNoticeBar';
19
20
  import { ExecutedActionsCard, type ExecutedAction } from './ExecutedActionsCard';
20
21
  import type { ChildInfo } from './OrchestrationChildrenCard';
21
22
  import {
@@ -181,6 +182,11 @@ interface AssistantMessageProps {
181
182
  * from inline Markdown so suggestions are not shown twice.
182
183
  */
183
184
  hideInlineNextSteps?: boolean;
185
+ /** Open the Memory settings tab pre-focused on a saved memory's scope/workspace. */
186
+ onOpenMemorySettings?: (target: {
187
+ scope: 'user' | 'workspace' | 'tenant';
188
+ scopeId: string;
189
+ }) => void;
184
190
  }
185
191
 
186
192
  function agentInitial(name: string): string {
@@ -356,6 +362,36 @@ function readPersistedAgentId(message: ChatMessage): string | undefined {
356
362
  }
357
363
  }
358
364
 
365
+ export function readSavedMemories(message: ChatMessage): SavedMemoryNotice[] {
366
+ const raw = (message as { messageMetadata?: unknown }).messageMetadata;
367
+ if (typeof raw !== 'string' || !raw) return [];
368
+ try {
369
+ const parsed = JSON.parse(raw) as { savedMemories?: unknown };
370
+ if (!Array.isArray(parsed.savedMemories)) return [];
371
+ const out: SavedMemoryNotice[] = [];
372
+ for (const item of parsed.savedMemories) {
373
+ if (!item || typeof item !== 'object') continue;
374
+ const rec = item as Record<string, unknown>;
375
+ if (typeof rec.refinementId !== 'string' || !rec.refinementId) continue;
376
+ const scope =
377
+ rec.scope === 'workspace' || rec.scope === 'tenant' ? rec.scope : 'user';
378
+ const scopeId = typeof rec.scopeId === 'string' ? rec.scopeId : 'default';
379
+ out.push({
380
+ refinementId: rec.refinementId,
381
+ scope,
382
+ scopeId,
383
+ ...(typeof rec.summary === 'string' && rec.summary
384
+ ? { summary: rec.summary }
385
+ : {}),
386
+ ...(rec.withdrawn === true ? { withdrawn: true } : {}),
387
+ });
388
+ }
389
+ return out;
390
+ } catch {
391
+ return [];
392
+ }
393
+ }
394
+
359
395
  function TurnErrorBubble({
360
396
  failure,
361
397
  completedSteps,
@@ -499,8 +535,10 @@ export function AssistantMessage({
499
535
  onContinueChild,
500
536
  onStopChild,
501
537
  hideInlineNextSteps = false,
538
+ onOpenMemorySettings,
502
539
  }: AssistantMessageProps) {
503
540
  const content = message.content || '';
541
+ const savedMemories = readSavedMemories(message);
504
542
  const failure = readTurnFailure(message, content);
505
543
  const stopped = !failure && readTurnStatus(message) === 'cancelled';
506
544
  const stoppedDuringRetry = stopped && readStoppedDuringRetry(message);
@@ -756,6 +794,27 @@ export function AssistantMessage({
756
794
  <TurnFilesCard files={turnFiles} executedActions={executedActions} chatId={chatId} />
757
795
  </div>
758
796
  )}
797
+ {!isStreaming && savedMemories.length > 0 && (
798
+ <div className="mt-2 space-y-1" data-testid="assistant-saved-memories">
799
+ {savedMemories.map((mem) => (
800
+ <MemorySaveNoticeBar
801
+ key={mem.refinementId}
802
+ refinementId={mem.refinementId}
803
+ scope={mem.scope}
804
+ summary={mem.summary}
805
+ chatId={chatId ?? undefined}
806
+ messageId={message.id}
807
+ workspaceId={mem.scope === 'workspace' ? mem.scopeId : undefined}
808
+ initialWithdrawn={mem.withdrawn}
809
+ onEdit={
810
+ onOpenMemorySettings
811
+ ? () => onOpenMemorySettings({ scope: mem.scope, scopeId: mem.scopeId })
812
+ : undefined
813
+ }
814
+ />
815
+ ))}
816
+ </div>
817
+ )}
759
818
  <div className="mt-2 flex items-center gap-2 text-[11px] text-agent-muted-foreground/80">
760
819
  <span>
761
820
  {message.createdAt
@@ -1216,16 +1216,28 @@ export const ChatInput = forwardRef<ChatInputHandle, ChatInputProps>(
1216
1216
  const builtinCommandSkills: SkillItem[] = [
1217
1217
  {
1218
1218
  name: 'compact',
1219
- displayName: 'Compact context',
1219
+ displayName: t('Compact context'),
1220
1220
  description: t('Summarize earlier messages to free up context window space'),
1221
1221
  isBuiltin: true,
1222
1222
  },
1223
+ {
1224
+ name: 'memory',
1225
+ displayName: t('Memory settings'),
1226
+ description: t('View or edit personal preferences and project memory'),
1227
+ isBuiltin: true,
1228
+ },
1229
+ {
1230
+ name: 'refine',
1231
+ displayName: t('Remember rule'),
1232
+ description: t('Save a durable preference or project convention directly to memory'),
1233
+ isBuiltin: true,
1234
+ },
1223
1235
  ];
1224
1236
  const allSkills = [
1225
- ...builtinCommandSkills.filter(
1226
- (b) => !skills.some((s) => s.name.toLowerCase() === b.name),
1237
+ ...builtinCommandSkills,
1238
+ ...skills.filter(
1239
+ (s) => !builtinCommandSkills.some((b) => b.name === s.name.toLowerCase()),
1227
1240
  ),
1228
- ...skills,
1229
1241
  ];
1230
1242
  const skillMatches: SlashSuggestion[] = allSkills
1231
1243
  .filter(
@@ -186,6 +186,10 @@ export interface LocalChatPanelProps {
186
186
  onSelectSuggestion?: (text: string) => void;
187
187
  /** 切去设置页或切换会话时在内存中保留未发送草稿文本。 */
188
188
  preserveDraft?: boolean;
189
+ onOpenMemorySettings?: (target: {
190
+ scope: 'user' | 'workspace' | 'tenant';
191
+ scopeId: string;
192
+ }) => void;
189
193
  }
190
194
 
191
195
  export function LocalChatPanel({
@@ -250,6 +254,7 @@ export function LocalChatPanel({
250
254
  suggestedReplies,
251
255
  onSelectSuggestion,
252
256
  preserveDraft = false,
257
+ onOpenMemorySettings,
253
258
  }: LocalChatPanelProps) {
254
259
  const [inputValue, setInputValueState] = useState(() =>
255
260
  preserveDraft ? getChatDraft(chatId) : '',
@@ -586,6 +591,7 @@ export function LocalChatPanel({
586
591
  onShare={onShare}
587
592
  suggestedReplies={suggestedReplies}
588
593
  onSelectSuggestion={onSelectSuggestion}
594
+ onOpenMemorySettings={onOpenMemorySettings}
589
595
  />
590
596
  <div className="mx-auto w-full max-w-3xl">
591
597
  {inputBanner}
@@ -1,12 +1,15 @@
1
- import { useState } from 'react';
1
+ import { useEffect, useState } from 'react';
2
2
  import { t } from '@/i18n';
3
3
  import { getHostBridge, hasHostBridge } from '@/lib/host-bridge';
4
4
 
5
5
  export interface MemorySaveNoticeBarProps {
6
6
  refinementId: string;
7
7
  scope?: 'user' | 'workspace' | 'tenant';
8
+ summary?: string;
8
9
  chatId?: string;
10
+ messageId?: string;
9
11
  workspaceId?: string;
12
+ initialWithdrawn?: boolean;
10
13
  onEdit?: () => void;
11
14
  onWithdrawn?: (refinementId: string) => void;
12
15
  }
@@ -14,17 +17,27 @@ export interface MemorySaveNoticeBarProps {
14
17
  export function MemorySaveNoticeBar({
15
18
  refinementId,
16
19
  scope = 'workspace',
20
+ summary,
17
21
  chatId,
22
+ messageId,
18
23
  workspaceId,
24
+ initialWithdrawn = false,
19
25
  onEdit,
20
26
  onWithdrawn,
21
27
  }: MemorySaveNoticeBarProps) {
22
- const [withdrawn, setWithdrawn] = useState(false);
28
+ const [withdrawn, setWithdrawn] = useState(initialWithdrawn);
29
+
30
+ useEffect(() => {
31
+ if (initialWithdrawn) {
32
+ setWithdrawn(true);
33
+ }
34
+ }, [initialWithdrawn]);
23
35
 
24
36
  const handleWithdraw = async () => {
25
37
  const path = `/api/v2/memory/refinements/${encodeURIComponent(refinementId)}/withdraw`;
26
38
  const body = {
27
39
  ...(chatId ? { chatId } : {}),
40
+ ...(messageId ? { messageId } : {}),
28
41
  ...(workspaceId ? { workspaceId } : {}),
29
42
  };
30
43
  if (hasHostBridge()) {
@@ -61,7 +74,15 @@ export function MemorySaveNoticeBar({
61
74
  data-testid="memory-save-notice-bar"
62
75
  className="mt-1.5 flex flex-wrap items-center gap-2 text-[11px] text-agent-muted-foreground"
63
76
  >
64
- <span>{label}</span>
77
+ <span>{summary ? `${label}:` : label}</span>
78
+ {summary ? (
79
+ <span
80
+ data-testid="memory-notice-summary"
81
+ className="max-w-[32rem] truncate text-agent-foreground/85"
82
+ >
83
+ {summary}
84
+ </span>
85
+ ) : null}
65
86
  <span>·</span>
66
87
  {onEdit ? (
67
88
  <button
@@ -211,6 +211,10 @@ interface MessageListProps {
211
211
  */
212
212
  suggestedReplies?: string[];
213
213
  onSelectSuggestion?: (text: string) => void;
214
+ onOpenMemorySettings?: (target: {
215
+ scope: 'user' | 'workspace' | 'tenant';
216
+ scopeId: string;
217
+ }) => void;
214
218
  }
215
219
 
216
220
  const COMPACTED_SUMMARY_PREFIX = '[context compacted: earlier conversation summarized]';
@@ -284,6 +288,7 @@ export function MessageList({
284
288
  onShare,
285
289
  suggestedReplies,
286
290
  onSelectSuggestion,
291
+ onOpenMemorySettings,
287
292
  }: MessageListProps) {
288
293
  const containerRef = useRef<HTMLDivElement>(null);
289
294
  const [isAtBottom, setIsAtBottom] = useState(true);
@@ -740,6 +745,7 @@ export function MessageList({
740
745
  (message.id === lastAssistantId &&
741
746
  Boolean(suggestedReplies && suggestedReplies.length > 0 && onSelectSuggestion))
742
747
  }
748
+ onOpenMemorySettings={onOpenMemorySettings}
743
749
  />
744
750
  {!isStreaming &&
745
751
  message.id === lastAssistantId &&
@@ -90,17 +90,29 @@ async function requestMemoryApi(
90
90
  }
91
91
 
92
92
  export interface MemorySettingsPanelProps {
93
+ initialScope?: MemoryScopeTab;
93
94
  workspaceId?: string;
95
+ defaultProjectId?: string;
94
96
  showTenantTab?: boolean;
95
97
  isAdmin?: boolean;
96
98
  }
97
99
 
100
+ interface WorkspaceProjectOption {
101
+ id: string;
102
+ name: string;
103
+ folderPath: string;
104
+ }
105
+
98
106
  export function MemorySettingsPanel({
107
+ initialScope,
99
108
  workspaceId = 'default',
109
+ defaultProjectId,
100
110
  showTenantTab = false,
101
111
  isAdmin = true,
102
112
  }: MemorySettingsPanelProps) {
103
- const [scope, setScope] = useState<MemoryScopeTab>('user');
113
+ const [scope, setScope] = useState<MemoryScopeTab>(initialScope ?? 'user');
114
+ const [selectedWorkspaceId, setSelectedWorkspaceId] = useState<string>(workspaceId || 'default');
115
+ const [projects, setProjects] = useState<WorkspaceProjectOption[]>([]);
104
116
  const [permissionMode, setPermissionMode] = useState<MemoryPermissionMode>('ask');
105
117
  const [markdown, setMarkdown] = useState('');
106
118
  const [savedMarkdown, setSavedMarkdown] = useState('');
@@ -113,10 +125,56 @@ export function MemorySettingsPanel({
113
125
  const [saving, setSaving] = useState(false);
114
126
  const [savedOk, setSavedOk] = useState(false);
115
127
 
128
+ useEffect(() => {
129
+ if (initialScope) {
130
+ setScope(initialScope);
131
+ }
132
+ }, [initialScope]);
133
+
134
+ useEffect(() => {
135
+ if (workspaceId) {
136
+ setSelectedWorkspaceId(workspaceId);
137
+ }
138
+ }, [workspaceId]);
139
+
140
+ useEffect(() => {
141
+ let cancelled = false;
142
+ void requestMemoryApi('GET', '/api/v2/projects').then((res) => {
143
+ if (cancelled || res.status !== 200) return;
144
+ const rawProjects = res.data.projects;
145
+ if (!Array.isArray(rawProjects)) return;
146
+ const valid = rawProjects
147
+ .filter(
148
+ (item): item is WorkspaceProjectOption =>
149
+ Boolean(
150
+ item &&
151
+ typeof item === 'object' &&
152
+ typeof (item as { folderPath?: unknown }).folderPath === 'string' &&
153
+ (item as { folderPath: string }).folderPath.trim().length > 0,
154
+ ),
155
+ )
156
+ .map((item) => ({
157
+ id: String(item.id ?? item.folderPath),
158
+ name: String(item.name || item.folderPath),
159
+ folderPath: item.folderPath,
160
+ }));
161
+ setProjects(valid);
162
+ if (workspaceId === 'default' && defaultProjectId) {
163
+ const matched = valid.find((p) => p.id === defaultProjectId);
164
+ if (matched?.folderPath) {
165
+ setSelectedWorkspaceId((cur) => (cur === 'default' ? matched.folderPath : cur));
166
+ }
167
+ }
168
+ });
169
+ return () => {
170
+ cancelled = true;
171
+ };
172
+ }, [defaultProjectId, workspaceId]);
173
+
116
174
  const loadScope = useCallback(
117
- async (targetScope: MemoryScopeTab) => {
175
+ async (targetScope: MemoryScopeTab, targetWorkspaceId = selectedWorkspaceId) => {
118
176
  const scopeParam =
119
- targetScope === 'workspace' ? `&scopeId=${encodeURIComponent(workspaceId)}` : '';
177
+ targetScope === 'workspace' ? `&scopeId=${encodeURIComponent(targetWorkspaceId)}` : '';
120
178
  const res = await requestMemoryApi(
121
179
  'GET',
122
180
  `/api/v2/memory?scope=${targetScope}${scopeParam}`,
@@ -135,12 +193,12 @@ export function MemorySettingsPanel({
135
193
  setConflictBanner(false);
136
194
  }
137
195
  },
138
- [workspaceId],
196
+ [selectedWorkspaceId],
139
197
  );
140
198
 
141
199
  useEffect(() => {
142
- void loadScope(scope);
143
- }, [scope, loadScope]);
200
+ void loadScope(scope, selectedWorkspaceId);
201
+ }, [scope, selectedWorkspaceId, loadScope]);
144
202
 
145
203
  const handleModeChange = async (nextMode: MemoryPermissionMode) => {
146
204
  setPermissionMode(nextMode);
@@ -157,7 +215,7 @@ export function MemorySettingsPanel({
157
215
  try {
158
216
  const res = await requestMemoryApi('PUT', '/api/v2/memory', {
159
217
  scope,
160
- ...(scope === 'workspace' ? { scopeId: workspaceId } : {}),
218
+ ...(scope === 'workspace' ? { scopeId: selectedWorkspaceId } : {}),
161
219
  contentMarkdown: markdown,
162
220
  baseHash,
163
221
  });
@@ -166,7 +224,7 @@ export function MemorySettingsPanel({
166
224
  return;
167
225
  }
168
226
  if (res.status === 200) {
169
- await loadScope(scope);
227
+ await loadScope(scope, selectedWorkspaceId);
170
228
  setSavedOk(true);
171
229
  }
172
230
  } finally {
@@ -179,9 +237,9 @@ export function MemorySettingsPanel({
179
237
  action: 'renew' | 'convert' | 'withdraw',
180
238
  ) => {
181
239
  await requestMemoryApi('POST', `/api/v2/memory/refinements/${encodeURIComponent(id)}/${action}`, {
182
- workspaceId,
240
+ workspaceId: selectedWorkspaceId,
183
241
  });
184
- await loadScope(scope);
242
+ await loadScope(scope, selectedWorkspaceId);
185
243
  };
186
244
 
187
245
  const activeRefinements = refinements.filter((r) => r.status === 'active');
@@ -259,7 +317,31 @@ export function MemorySettingsPanel({
259
317
  })}
260
318
  </div>
261
319
 
262
- <div className="flex items-center gap-2.5 text-[11px] text-agent-muted-foreground">
320
+ <div className="flex flex-wrap items-center gap-2.5 text-[11px] text-agent-muted-foreground">
321
+ {scope === 'workspace' &&
322
+ (projects.length > 0 || selectedWorkspaceId !== 'default') ? (
323
+ <select
324
+ data-testid="memory-workspace-select"
325
+ aria-label={t('Select project workspace')}
326
+ value={selectedWorkspaceId}
327
+ onChange={(e) => {
328
+ setSavedOk(false);
329
+ setSelectedWorkspaceId(e.target.value);
330
+ }}
331
+ className="h-7 max-w-[14rem] truncate rounded-md border border-agent-border bg-agent-canvas px-2 text-xs text-agent-foreground focus:border-agent-foreground/40 focus:outline-none"
332
+ >
333
+ <option value="default">{t('Unlinked workspace (default)')}</option>
334
+ {projects.map((p) => (
335
+ <option key={p.id} value={p.folderPath}>
336
+ {p.name}
337
+ </option>
338
+ ))}
339
+ {selectedWorkspaceId !== 'default' &&
340
+ !projects.some((p) => p.folderPath === selectedWorkspaceId) ? (
341
+ <option value={selectedWorkspaceId}>{selectedWorkspaceId}</option>
342
+ ) : null}
343
+ </select>
344
+ ) : null}
263
345
  <span data-testid="memory-quota-label" className="tabular-nums">
264
346
  {(bytesUsed / 1024).toFixed(1)} / {(maxBytes / 1024).toFixed(1)} KB
265
347
  </span>
@@ -161,6 +161,33 @@ export function parseModeSlashCommand(rawText: string): ParsedModeSlashCommand |
161
161
  return null;
162
162
  }
163
163
 
164
+ export type ParsedMemorySlashCommand =
165
+ | { kind: 'open-settings' }
166
+ | { kind: 'propose'; content: string }
167
+ | { kind: 'missing-content' };
168
+
169
+ /**
170
+ * Parse built-in `/memory` and `/refine` composer commands:
171
+ * - `/memory` -> open long-term memory settings without spending an LLM turn
172
+ * - `/memory <rule>` -> propose `<rule>` directly into long-term memory
173
+ * - `/refine <rule>` -> propose `<rule>` directly into long-term memory
174
+ * - `/refine` (empty) -> report missing content without sending to LLM
175
+ */
176
+ export function parseMemorySlashCommand(rawText: string): ParsedMemorySlashCommand | null {
177
+ const trimmed = rawText.trim();
178
+ const memoryMatch = trimmed.match(/^\/memory(?:\s+([\s\S]*))?$/i);
179
+ if (memoryMatch) {
180
+ const rest = (memoryMatch[1] ?? '').trim();
181
+ return rest ? { kind: 'propose', content: rest } : { kind: 'open-settings' };
182
+ }
183
+ const refineMatch = trimmed.match(/^\/refine(?:\s+([\s\S]*))?$/i);
184
+ if (refineMatch) {
185
+ const rest = (refineMatch[1] ?? '').trim();
186
+ return rest ? { kind: 'propose', content: rest } : { kind: 'missing-content' };
187
+ }
188
+ return null;
189
+ }
190
+
164
191
  export interface ActionablePlanState {
165
192
  messageId: string;
166
193
  plan: ParsedProposedPlan;
@@ -8,12 +8,25 @@
8
8
  // 与后端 automation.py 的标题前缀是同一条持久化约定,不能按界面语言改写。
9
9
  export const AUTOMATION_TITLE_PREFIX = '[自动化] '; // i18n:allow
10
10
  const BARE_BRACKET_PREFIX = '[自动化]'; // i18n:allow
11
+ export const DEFAULT_STORED_CHAT_TITLE = '新对话'; // i18n:allow
11
12
 
12
13
  export interface ParsedChatTitle {
13
14
  displayTitle: string;
14
15
  isAutomation: boolean;
15
16
  }
16
17
 
18
+ export function resolveChatDisplayTitle(
19
+ displayTitle: string,
20
+ fallback: string,
21
+ titleSource?: string | null,
22
+ ): string {
23
+ if (!displayTitle) return fallback;
24
+ if (displayTitle === DEFAULT_STORED_CHAT_TITLE && titleSource !== 'user') {
25
+ return fallback;
26
+ }
27
+ return displayTitle;
28
+ }
29
+
17
30
  export function parseChatTitle(
18
31
  rawTitle: string | null | undefined,
19
32
  ): ParsedChatTitle {
@@ -20,6 +20,7 @@ export interface LocalChat {
20
20
  projectId: string | null;
21
21
  userId: string;
22
22
  title: string;
23
+ titleSource?: 'user' | 'auto' | null;
23
24
  agentId: string | null;
24
25
  createdAt: string;
25
26
  updatedAt: string;
@@ -1023,3 +1024,37 @@ export async function diagnoseLlmConnection(input: {
1023
1024
  body: input,
1024
1025
  });
1025
1026
  }
1027
+
1028
+ /* ---------------- Long-term memory ---------------- */
1029
+
1030
+ export interface SavedMemoryNotice {
1031
+ refinementId: string;
1032
+ scope: 'user' | 'workspace' | 'tenant';
1033
+ scopeId: string;
1034
+ summary?: string;
1035
+ withdrawn?: boolean;
1036
+ }
1037
+
1038
+ export interface ProposeMemoryRefinementResponse {
1039
+ accepted: boolean;
1040
+ reason?: 'user_revoked' | 'human_edited_conflict';
1041
+ meta?: {
1042
+ id: string;
1043
+ scope: 'user' | 'workspace' | 'tenant';
1044
+ content: string;
1045
+ };
1046
+ }
1047
+
1048
+ export async function proposeMemoryRefinement(input: {
1049
+ scope: 'user' | 'workspace' | 'tenant';
1050
+ scopeId?: string;
1051
+ chatId?: string;
1052
+ turnId?: string;
1053
+ content: string;
1054
+ }) {
1055
+ return bridge().localBackend.request<ProposeMemoryRefinementResponse>({
1056
+ method: 'POST',
1057
+ path: '/api/v2/memory/propose',
1058
+ body: input,
1059
+ });
1060
+ }
@@ -62,11 +62,15 @@ import {
62
62
  compactChat,
63
63
  getChatContextStatus,
64
64
  getChatLiveStream,
65
+ proposeMemoryRefinement,
65
66
  type ChatLiveStream,
66
67
  type LocalChatMessage,
68
+ type SavedMemoryNotice,
67
69
  } from "@/lib/local-api";
70
+ import { MemorySaveNoticeBar } from "@/components/chat/MemorySaveNoticeBar";
68
71
  import {
69
72
  dismissPlanMessage,
73
+ parseMemorySlashCommand,
70
74
  parseModeSlashCommand,
71
75
  PlanActionContext,
72
76
  readChatModeForSession,
@@ -114,6 +118,59 @@ function chronological(messages: ChatMessage[] | undefined): ChatMessage[] {
114
118
  return [...messages].reverse();
115
119
  }
116
120
 
121
+ function buildMemorySettingsUrl(target?: {
122
+ scope?: "user" | "workspace" | "tenant";
123
+ scopeId?: string;
124
+ }): string {
125
+ const params = new URLSearchParams({ tab: "memory" });
126
+ if (target?.scope) {
127
+ params.set("scope", target.scope);
128
+ }
129
+ if (
130
+ target?.scope === "workspace" &&
131
+ target.scopeId &&
132
+ target.scopeId !== "default"
133
+ ) {
134
+ params.set("workspaceId", target.scopeId);
135
+ }
136
+ return `/settings?${params.toString()}`;
137
+ }
138
+
139
+ function mergeSavedMemoriesJson(
140
+ rawJson: string | null | undefined,
141
+ incoming: SavedMemoryNotice[],
142
+ ): string {
143
+ let base: Record<string, unknown> = {};
144
+ if (typeof rawJson === "string" && rawJson) {
145
+ try {
146
+ const parsed = JSON.parse(rawJson);
147
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
148
+ base = parsed as Record<string, unknown>;
149
+ }
150
+ } catch {
151
+ base = {};
152
+ }
153
+ }
154
+ const existing = Array.isArray(base.savedMemories)
155
+ ? (base.savedMemories as SavedMemoryNotice[])
156
+ : [];
157
+ const byId = new Map<string, SavedMemoryNotice>();
158
+ for (const item of existing) {
159
+ if (item && typeof item.refinementId === "string" && item.refinementId) {
160
+ byId.set(item.refinementId, item);
161
+ }
162
+ }
163
+ for (const item of incoming) {
164
+ if (item && typeof item.refinementId === "string" && item.refinementId) {
165
+ byId.set(item.refinementId, { ...byId.get(item.refinementId), ...item });
166
+ }
167
+ }
168
+ return JSON.stringify({
169
+ ...base,
170
+ savedMemories: Array.from(byId.values()),
171
+ });
172
+ }
173
+
117
174
  type ChatMessageWithMetadata = ChatMessage & LocalChatMessage;
118
175
 
119
176
  interface ComposerTurnSettings {
@@ -687,6 +744,15 @@ function AgentChatView({
687
744
  const [tailAssistantDbId, setTailAssistantDbId] = useState<string | null>(
688
745
  initialSuggestedReplies?.messageId ?? null,
689
746
  );
747
+ const tailAssistantDbIdRef = useRef<string | null>(tailAssistantDbId);
748
+ tailAssistantDbIdRef.current = tailAssistantDbId;
749
+ const [manualMemoryNotice, setManualMemoryNotice] = useState<SavedMemoryNotice | null>(null);
750
+ const handleOpenMemorySettings = useCallback(
751
+ (target: { scope: "user" | "workspace" | "tenant"; scopeId: string }) => {
752
+ navigate(buildMemorySettingsUrl(target));
753
+ },
754
+ [navigate],
755
+ );
690
756
 
691
757
  const handleModeChange = useCallback(
692
758
  (next: ChatMode) => {
@@ -927,9 +993,62 @@ function AgentChatView({
927
993
  if (response.messages) setMessages(chronological(response.messages));
928
994
  });
929
995
  });
996
+ const offMemorySaved = bridge.onPackEvent("memory:saved", (value) => {
997
+ const payload = value as {
998
+ chatId?: string;
999
+ messageId?: string;
1000
+ savedMemories?: SavedMemoryNotice[];
1001
+ };
1002
+ if (payload.chatId !== chatId || !payload.messageId) return;
1003
+ if (!Array.isArray(payload.savedMemories) || payload.savedMemories.length === 0) return;
1004
+ const incoming = payload.savedMemories;
1005
+ const targetId = payload.messageId;
1006
+ const isTail = targetId === tailAssistantDbIdRef.current;
1007
+ if (isTail) {
1008
+ const mergedTail = mergeSavedMemoriesJson(tailLiveMetadataRef.current, incoming);
1009
+ tailLiveMetadataRef.current = mergedTail;
1010
+ setTailLiveMetadata(mergedTail);
1011
+ }
1012
+ setLiveMetadataByMessageId((prev) => {
1013
+ const next = {
1014
+ ...prev,
1015
+ [targetId]: mergeSavedMemoriesJson(prev[targetId], incoming),
1016
+ };
1017
+ if (isTail) {
1018
+ const last = latestMessagesRef.current[latestMessagesRef.current.length - 1];
1019
+ if (last?.role === "assistant") {
1020
+ next[last.id] = mergeSavedMemoriesJson(
1021
+ next[last.id] ?? tailLiveMetadataRef.current,
1022
+ incoming,
1023
+ );
1024
+ }
1025
+ }
1026
+ return next;
1027
+ });
1028
+ const currentList = latestMessagesRef.current;
1029
+ let changed = false;
1030
+ const nextMessages = currentList.map((m, idx) => {
1031
+ const matchesTail =
1032
+ isTail && idx === currentList.length - 1 && m.role === "assistant";
1033
+ if (m.id !== targetId && !matchesTail) return m;
1034
+ const currentMeta = (m as ChatMessageWithMetadata).messageMetadata;
1035
+ changed = true;
1036
+ return {
1037
+ ...m,
1038
+ messageMetadata: mergeSavedMemoriesJson(
1039
+ typeof currentMeta === "string" ? currentMeta : null,
1040
+ incoming,
1041
+ ),
1042
+ } as ChatMessage;
1043
+ });
1044
+ if (changed) {
1045
+ setMessages(nextMessages);
1046
+ }
1047
+ });
930
1048
  return () => {
931
1049
  offStarted();
932
1050
  offFinished();
1051
+ offMemorySaved();
933
1052
  };
934
1053
  }, [chatId, setMessages]);
935
1054
 
@@ -1075,6 +1194,53 @@ function AgentChatView({
1075
1194
  const handleSubmit = useCallback(
1076
1195
  (input: { content: string; metadata?: Record<string, unknown> }) => {
1077
1196
  const trimmedCmd = input.content.trim();
1197
+ const memoryCmd = parseMemorySlashCommand(trimmedCmd);
1198
+ if (memoryCmd) {
1199
+ if (memoryCmd.kind === "open-settings") {
1200
+ navigate(
1201
+ buildMemorySettingsUrl(
1202
+ chatProject
1203
+ ? { scope: "workspace", scopeId: chatProject.folderPath }
1204
+ : { scope: "user", scopeId: "default" },
1205
+ ),
1206
+ );
1207
+ return;
1208
+ }
1209
+ if (memoryCmd.kind === "missing-content") {
1210
+ setNewChatError(t("Usage: /refine <preference or project rule to remember>"));
1211
+ return;
1212
+ }
1213
+ if (hasHostBridge()) {
1214
+ const scope = chatProject ? ("workspace" as const) : ("user" as const);
1215
+ const scopeId = chatProject?.folderPath ?? "default";
1216
+ void proposeMemoryRefinement({
1217
+ scope,
1218
+ ...(chatProject ? { scopeId: chatProject.folderPath } : {}),
1219
+ chatId,
1220
+ turnId: `slash_${Date.now()}`,
1221
+ content: memoryCmd.content,
1222
+ })
1223
+ .then((res) => {
1224
+ if (res.accepted && res.meta) {
1225
+ setNewChatError(null);
1226
+ setManualMemoryNotice({
1227
+ refinementId: res.meta.id,
1228
+ scope: res.meta.scope,
1229
+ scopeId,
1230
+ summary: memoryCmd.content.slice(0, 72),
1231
+ });
1232
+ } else {
1233
+ setNewChatError(
1234
+ t("This memory rule was previously withdrawn or conflicts with manual edits."),
1235
+ );
1236
+ }
1237
+ })
1238
+ .catch((err: unknown) =>
1239
+ setNewChatError(err instanceof Error ? err.message : String(err)),
1240
+ );
1241
+ }
1242
+ return;
1243
+ }
1078
1244
  if (/^\/compact(?:\s+|$)/i.test(trimmedCmd) && hasHostBridge()) {
1079
1245
  const focusArg = trimmedCmd.replace(/^\/compact\s*/i, "").trim();
1080
1246
  void compactChat(chatId, focusArg ? { focus: focusArg } : {})
@@ -1141,7 +1307,16 @@ function AgentChatView({
1141
1307
  metadata: Object.keys(metadata).length > 0 ? metadata : undefined,
1142
1308
  });
1143
1309
  },
1144
- [sendUserMessage, modelOverride, effortOverride, execPolicy, chatId, onBranchTick],
1310
+ [
1311
+ sendUserMessage,
1312
+ modelOverride,
1313
+ effortOverride,
1314
+ execPolicy,
1315
+ chatId,
1316
+ onBranchTick,
1317
+ chatProject,
1318
+ navigate,
1319
+ ],
1145
1320
  );
1146
1321
 
1147
1322
  const handleEditUserMessage = useCallback(
@@ -1579,12 +1754,35 @@ function AgentChatView({
1579
1754
  !hasMapped && !tailLiveMetadata
1580
1755
  ? messages
1581
1756
  : messages.map((m, idx) => {
1582
- if ((m as ChatMessageWithMetadata).messageMetadata) return m;
1757
+ const existingMeta = (m as ChatMessageWithMetadata).messageMetadata;
1583
1758
  const mapped =
1584
1759
  liveMetadataByMessageId[m.id] ??
1585
1760
  (idx === messages.length - 1 && m.role === "assistant"
1586
1761
  ? (tailLiveMetadata ?? undefined)
1587
1762
  : undefined);
1763
+ if (typeof existingMeta === "string" && existingMeta) {
1764
+ if (!mapped || !mapped.includes('"savedMemories"')) return m;
1765
+ try {
1766
+ const parsedMapped = JSON.parse(mapped) as {
1767
+ savedMemories?: SavedMemoryNotice[];
1768
+ };
1769
+ if (
1770
+ Array.isArray(parsedMapped.savedMemories) &&
1771
+ parsedMapped.savedMemories.length > 0
1772
+ ) {
1773
+ return {
1774
+ ...m,
1775
+ messageMetadata: mergeSavedMemoriesJson(
1776
+ existingMeta,
1777
+ parsedMapped.savedMemories,
1778
+ ),
1779
+ } as ChatMessage;
1780
+ }
1781
+ } catch {
1782
+ return m;
1783
+ }
1784
+ return m;
1785
+ }
1588
1786
  if (!mapped) return m;
1589
1787
  return { ...m, messageMetadata: mapped } as ChatMessage;
1590
1788
  });
@@ -1818,6 +2016,7 @@ function AgentChatView({
1818
2016
  onShare={hasHostBridge() ? handleShare : undefined}
1819
2017
  suggestedReplies={visibleSuggestedReplies}
1820
2018
  onSelectSuggestion={handleSelectSuggestion}
2019
+ onOpenMemorySettings={handleOpenMemorySettings}
1821
2020
  onOpenSettings={
1822
2021
  hasHostBridge() && settingsChrome("llm")
1823
2022
  ? () => setLlmSettingsOpen(true)
@@ -1882,6 +2081,38 @@ function AgentChatView({
1882
2081
  </button>
1883
2082
  </div>
1884
2083
  ) : null}
2084
+ {manualMemoryNotice ? (
2085
+ <div
2086
+ data-testid="manual-memory-notice"
2087
+ className="mb-1 flex items-center justify-between gap-2 rounded-agent-md border border-agent-border/60 bg-agent-muted/40 px-2.5 py-1.5"
2088
+ >
2089
+ <MemorySaveNoticeBar
2090
+ refinementId={manualMemoryNotice.refinementId}
2091
+ scope={manualMemoryNotice.scope}
2092
+ summary={manualMemoryNotice.summary}
2093
+ chatId={chatId}
2094
+ workspaceId={
2095
+ manualMemoryNotice.scope === "workspace"
2096
+ ? manualMemoryNotice.scopeId
2097
+ : undefined
2098
+ }
2099
+ onEdit={() =>
2100
+ handleOpenMemorySettings({
2101
+ scope: manualMemoryNotice.scope,
2102
+ scopeId: manualMemoryNotice.scopeId,
2103
+ })
2104
+ }
2105
+ />
2106
+ <button
2107
+ type="button"
2108
+ onClick={() => setManualMemoryNotice(null)}
2109
+ className="rounded px-1 text-xs text-agent-muted-foreground hover:text-agent-foreground"
2110
+ aria-label={t("Dismiss")}
2111
+ >
2112
+ ✕
2113
+ </button>
2114
+ </div>
2115
+ ) : null}
1885
2116
  <GoalLoopStatusBar
1886
2117
  chatId={chatId}
1887
2118
  goal={goal}
@@ -1949,6 +2180,7 @@ function EmptyChatGate() {
1949
2180
  const [effortOverride, setEffortOverride] = useState<string | null>(null);
1950
2181
  const [isCreating, setIsCreating] = useState(false);
1951
2182
  const [createError, setCreateError] = useState<string | null>(null);
2183
+ const [homeMemoryNotice, setHomeMemoryNotice] = useState<SavedMemoryNotice | null>(null);
1952
2184
  const [llmSettingsOpen, setLlmSettingsOpen] = useState(false);
1953
2185
  const inputRef = useRef<ChatInputHandle>(null);
1954
2186
 
@@ -1993,6 +2225,58 @@ function EmptyChatGate() {
1993
2225
  async (rawText: string, overrideMode?: ChatMode) => {
1994
2226
  if (isCreating) return;
1995
2227
  let trimmed = rawText.trim();
2228
+ const memoryCmd = !overrideMode && trimmed ? parseMemorySlashCommand(trimmed) : null;
2229
+ if (memoryCmd) {
2230
+ const selectedProject =
2231
+ selectedProjectId && showProjectsChrome
2232
+ ? projects.find((p) => p.id === selectedProjectId) ?? null
2233
+ : null;
2234
+ if (memoryCmd.kind === "open-settings") {
2235
+ setInputValue("");
2236
+ navigate(
2237
+ buildMemorySettingsUrl(
2238
+ selectedProject
2239
+ ? { scope: "workspace", scopeId: selectedProject.folderPath }
2240
+ : { scope: "user", scopeId: "default" },
2241
+ ),
2242
+ );
2243
+ return;
2244
+ }
2245
+ if (memoryCmd.kind === "missing-content") {
2246
+ setCreateError(t("Usage: /refine <preference or project rule to remember>"));
2247
+ return;
2248
+ }
2249
+ if (hasHostBridge()) {
2250
+ const scope = selectedProject ? ("workspace" as const) : ("user" as const);
2251
+ const scopeId = selectedProject?.folderPath ?? "default";
2252
+ try {
2253
+ const res = await proposeMemoryRefinement({
2254
+ scope,
2255
+ ...(selectedProject ? { scopeId: selectedProject.folderPath } : {}),
2256
+ chatId: "home_slash",
2257
+ turnId: `slash_${Date.now()}`,
2258
+ content: memoryCmd.content,
2259
+ });
2260
+ if (res.accepted && res.meta) {
2261
+ setCreateError(null);
2262
+ setInputValue("");
2263
+ setHomeMemoryNotice({
2264
+ refinementId: res.meta.id,
2265
+ scope: res.meta.scope,
2266
+ scopeId,
2267
+ summary: memoryCmd.content.slice(0, 72),
2268
+ });
2269
+ } else {
2270
+ setCreateError(
2271
+ t("This memory rule was previously withdrawn or conflicts with manual edits."),
2272
+ );
2273
+ }
2274
+ } catch (err) {
2275
+ setCreateError(err instanceof Error ? err.message : String(err));
2276
+ }
2277
+ }
2278
+ return;
2279
+ }
1996
2280
  let effectiveMode = overrideMode ?? mode;
1997
2281
  const slashCmd = !overrideMode && trimmed ? parseModeSlashCommand(trimmed) : null;
1998
2282
  if (slashCmd) {
@@ -2085,6 +2369,8 @@ function EmptyChatGate() {
2085
2369
  isCreating,
2086
2370
  selectedProjectId,
2087
2371
  showProjectsChrome,
2372
+ projects,
2373
+ setInputValue,
2088
2374
  ctx,
2089
2375
  navigate,
2090
2376
  ],
@@ -2110,6 +2396,40 @@ function EmptyChatGate() {
2110
2396
  <div className="flex w-full max-w-3xl flex-col items-center gap-4">
2111
2397
  <EmptyChatHero />
2112
2398
  <div className="w-full">
2399
+ {homeMemoryNotice ? (
2400
+ <div
2401
+ data-testid="manual-memory-notice"
2402
+ className="mb-1.5 flex items-center justify-between gap-2 rounded-agent-md border border-agent-border/60 bg-agent-muted/40 px-2.5 py-1.5"
2403
+ >
2404
+ <MemorySaveNoticeBar
2405
+ refinementId={homeMemoryNotice.refinementId}
2406
+ scope={homeMemoryNotice.scope}
2407
+ summary={homeMemoryNotice.summary}
2408
+ chatId="home_slash"
2409
+ workspaceId={
2410
+ homeMemoryNotice.scope === "workspace"
2411
+ ? homeMemoryNotice.scopeId
2412
+ : undefined
2413
+ }
2414
+ onEdit={() =>
2415
+ navigate(
2416
+ buildMemorySettingsUrl({
2417
+ scope: homeMemoryNotice.scope,
2418
+ scopeId: homeMemoryNotice.scopeId,
2419
+ }),
2420
+ )
2421
+ }
2422
+ />
2423
+ <button
2424
+ type="button"
2425
+ onClick={() => setHomeMemoryNotice(null)}
2426
+ className="rounded px-1 text-xs text-agent-muted-foreground hover:text-agent-foreground"
2427
+ aria-label={t("Dismiss")}
2428
+ >
2429
+ ✕
2430
+ </button>
2431
+ </div>
2432
+ ) : null}
2113
2433
  <ChatInput
2114
2434
  ref={inputRef}
2115
2435
  value={inputValue}
@@ -236,7 +236,14 @@ export function SettingsPage() {
236
236
  </SettingPageShell>
237
237
  );
238
238
 
239
- case 'memory':
239
+ case 'memory': {
240
+ const rawScope = searchParams.get('scope');
241
+ const initialScope =
242
+ rawScope === 'user' || rawScope === 'workspace' || rawScope === 'tenant'
243
+ ? rawScope
244
+ : undefined;
245
+ const paramWorkspaceId = searchParams.get('workspaceId')?.trim() || undefined;
246
+ const latestChatProjectId = catalog?.chats?.[0]?.projectId ?? undefined;
240
247
  return (
241
248
  <SettingPageShell
242
249
  title={t('Memory')}
@@ -245,9 +252,14 @@ export function SettingsPage() {
245
252
  banner={previewBanner}
246
253
  testId="settings-section-memory"
247
254
  >
248
- <MemorySettingsPanel />
255
+ <MemorySettingsPanel
256
+ initialScope={initialScope}
257
+ workspaceId={paramWorkspaceId ?? 'default'}
258
+ defaultProjectId={paramWorkspaceId ? undefined : latestChatProjectId}
259
+ />
249
260
  </SettingPageShell>
250
261
  );
262
+ }
251
263
 
252
264
  case 'usage':
253
265
  return (