@steerable/agent-shell-web 0.13.1 → 0.14.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.13.1",
3
+ "version": "0.14.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.13.1",
49
- "@steerable/agent-ui": "0.13.1"
48
+ "@steerable/agent-protocol": "0.14.1",
49
+ "@steerable/agent-ui": "0.14.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.13.1"
62
+ "@steerable/pack-sdk": "0.14.1"
63
63
  },
64
64
  "scripts": {
65
65
  "gen": "echo agent-shell-web",
@@ -20,6 +20,7 @@ import type { ChildInfo } from './OrchestrationChildrenCard';
20
20
  import { collectTurnParticipants, extractMentionedAgentIds } from './executed-actions-model';
21
21
  import type { InspectTaskInput } from './executed-actions-model';
22
22
  import { StreamingStatus } from './StreamingStatus';
23
+ import { classifyErrorMessage } from '@steerable/agent-protocol';
23
24
  import { TurnFailureCard, type TurnFailureCardProps } from './TurnFailureCard';
24
25
  import { readFailureDetail, type TurnFailureDetail } from './turn-failure';
25
26
  import type { RetryState } from './RetryStatus';
@@ -286,34 +287,48 @@ function readTurnStatus(message: ChatMessage): 'failed' | 'cancelled' | 'complet
286
287
  }
287
288
 
288
289
  function readTurnFailure(message: ChatMessage, content: string): TurnFailure | null {
289
- if (content.startsWith(STREAM_ERROR_PREFIX)) {
290
- // Live path: the framework stamped the reason into the content before the
291
- // turn was persisted, so nothing structured is available yet.
292
- return { reason: content.slice(STREAM_ERROR_PREFIX.length), contentIsError: true };
293
- }
290
+ const isStreamErrorContent = content.startsWith(STREAM_ERROR_PREFIX);
294
291
  const raw = (message as { messageMetadata?: unknown }).messageMetadata;
295
- if (typeof raw !== 'string' || !raw) return null;
296
- try {
297
- const meta = JSON.parse(raw) as {
298
- completionStatus?: unknown;
299
- completionReason?: unknown;
300
- failure?: unknown;
301
- traceId?: unknown;
302
- };
303
- if (
304
- meta?.completionStatus === 'failed' &&
305
- typeof meta.completionReason === 'string' &&
306
- meta.completionReason
307
- ) {
308
- return {
309
- reason: meta.completionReason,
310
- contentIsError: false,
311
- detail: readFailureDetail(meta.failure),
312
- traceId: typeof meta.traceId === 'string' && meta.traceId ? meta.traceId : undefined,
292
+ if (typeof raw === 'string' && raw) {
293
+ try {
294
+ const meta = JSON.parse(raw) as {
295
+ completionStatus?: unknown;
296
+ completionReason?: unknown;
297
+ failure?: unknown;
298
+ failureInfo?: unknown;
299
+ traceId?: unknown;
313
300
  };
301
+ if (
302
+ meta?.completionStatus === 'failed' &&
303
+ typeof meta.completionReason === 'string' &&
304
+ meta.completionReason
305
+ ) {
306
+ const parsedDetail =
307
+ readFailureDetail(meta.failure) ?? readFailureDetail(meta.failureInfo);
308
+ const fallbackKind = classifyErrorMessage(meta.completionReason);
309
+ return {
310
+ reason: meta.completionReason,
311
+ contentIsError: isStreamErrorContent,
312
+ detail:
313
+ parsedDetail ??
314
+ (fallbackKind !== 'unknown' ? { kind: fallbackKind } : undefined),
315
+ traceId: typeof meta.traceId === 'string' && meta.traceId ? meta.traceId : undefined,
316
+ };
317
+ }
318
+ } catch {
319
+ // 元数据损坏按无失败处理——落回下方的流式前缀兜底或空消息展示。
314
320
  }
315
- } catch {
316
- // 元数据损坏按无失败处理——落回原有的空消息展示。
321
+ }
322
+ if (isStreamErrorContent) {
323
+ // Live path before message_id arrives: the framework stamped the reason
324
+ // into the content before the turn was persisted.
325
+ const rawReason = content.slice(STREAM_ERROR_PREFIX.length);
326
+ const fallbackKind = classifyErrorMessage(rawReason);
327
+ return {
328
+ reason: rawReason,
329
+ contentIsError: true,
330
+ detail: fallbackKind !== 'unknown' ? { kind: fallbackKind } : undefined,
331
+ };
317
332
  }
318
333
  return null;
319
334
  }
@@ -1165,7 +1165,21 @@ export const ChatInput = forwardRef<ChatInputHandle, ChatInputProps>(
1165
1165
  useEffect(() => {
1166
1166
  if (slashQuery) {
1167
1167
  const query = slashQuery.query;
1168
- const skillMatches: SlashSuggestion[] = skills
1168
+ const builtinCommandSkills: SkillItem[] = [
1169
+ {
1170
+ name: 'compact',
1171
+ displayName: 'Compact context',
1172
+ description: t('Summarize earlier messages to free up context window space'),
1173
+ isBuiltin: true,
1174
+ },
1175
+ ];
1176
+ const allSkills = [
1177
+ ...builtinCommandSkills.filter(
1178
+ (b) => !skills.some((s) => s.name.toLowerCase() === b.name),
1179
+ ),
1180
+ ...skills,
1181
+ ];
1182
+ const skillMatches: SlashSuggestion[] = allSkills
1169
1183
  .filter(
1170
1184
  (s) =>
1171
1185
  s.name.toLowerCase().includes(query) ||
@@ -0,0 +1,249 @@
1
+ import { useCallback, useEffect, useRef, useState } from 'react';
2
+ import { LuMinimize2 } from 'react-icons/lu';
3
+ import { t } from '@/i18n';
4
+ import { hasHostBridge } from '@/lib/host-bridge';
5
+ import {
6
+ compactChat,
7
+ getChatContextStatus,
8
+ type ChatContextStatus,
9
+ type CompactChatOptions,
10
+ type CompactChatResult,
11
+ } from '@/lib/local-api';
12
+
13
+ export interface ContextUsagePillProps {
14
+ chatId: string;
15
+ messageCount: number;
16
+ isStreaming: boolean;
17
+ /** Optional latest in-memory turn usage when streaming just finished. */
18
+ livePromptTokens?: number;
19
+ liveCachedPromptTokens?: number;
20
+ onCompacted?: (result: CompactChatResult) => void;
21
+ }
22
+
23
+ function formatCompactCount(n: number): string {
24
+ if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1).replace(/\.0$/, '')}M`;
25
+ if (n >= 1_000) return `${Math.round(n / 1_000)}k`;
26
+ return String(n);
27
+ }
28
+
29
+ function formatMegabytes(bytes: number): string {
30
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
31
+ }
32
+
33
+ export function ContextUsagePill({
34
+ chatId,
35
+ messageCount,
36
+ isStreaming,
37
+ livePromptTokens,
38
+ liveCachedPromptTokens,
39
+ onCompacted,
40
+ }: ContextUsagePillProps) {
41
+ const [status, setStatus] = useState<ChatContextStatus | null>(null);
42
+ const [open, setOpen] = useState(false);
43
+ const [focus, setFocus] = useState('');
44
+ const [compacting, setCompacting] = useState(false);
45
+ const [feedback, setFeedback] = useState<string | null>(null);
46
+ const containerRef = useRef<HTMLDivElement>(null);
47
+
48
+ const refreshStatus = useCallback(async () => {
49
+ if (!chatId || !hasHostBridge()) return;
50
+ try {
51
+ const next = await getChatContextStatus(chatId);
52
+ setStatus(next);
53
+ } catch {
54
+ // Ignore transient status fetch errors so composer toolbar never flickers.
55
+ }
56
+ }, [chatId]);
57
+
58
+ useEffect(() => {
59
+ if (messageCount === 0) {
60
+ setStatus(null);
61
+ return;
62
+ }
63
+ if (!isStreaming) {
64
+ void refreshStatus();
65
+ }
66
+ }, [chatId, messageCount, isStreaming, refreshStatus]);
67
+
68
+ useEffect(() => {
69
+ if (!open) return;
70
+ void refreshStatus();
71
+ const handlePointerDown = (event: PointerEvent) => {
72
+ if (
73
+ event.target instanceof Node &&
74
+ containerRef.current?.contains(event.target)
75
+ ) {
76
+ return;
77
+ }
78
+ setOpen(false);
79
+ };
80
+ window.addEventListener('pointerdown', handlePointerDown);
81
+ return () => window.removeEventListener('pointerdown', handlePointerDown);
82
+ }, [open, refreshStatus]);
83
+
84
+ if (!hasHostBridge() || messageCount === 0) {
85
+ return null;
86
+ }
87
+
88
+ const maxTokens = status?.maxContextTokens ?? 131_072;
89
+ const estTokens = Math.max(status?.estimatedTokens ?? 0, livePromptTokens ?? 0);
90
+ const maxBytes = status?.maxRequestBytes ?? 4_194_304;
91
+ const estBytes = status?.estimatedBytes ?? 0;
92
+ const promptTokens = livePromptTokens ?? status?.promptTokens ?? 0;
93
+ const cachedTokens = liveCachedPromptTokens ?? status?.cachedPromptTokens ?? 0;
94
+ const cacheHitPct =
95
+ promptTokens > 0 ? Math.min(100, Math.round((cachedTokens / promptTokens) * 100)) : null;
96
+
97
+ const tokenRatio = maxTokens > 0 ? Math.min(1, estTokens / maxTokens) : 0;
98
+ const byteRatio = maxBytes > 0 ? Math.min(1, estBytes / maxBytes) : 0;
99
+ const dominantRatio = Math.max(tokenRatio, byteRatio);
100
+ const dominantPct = Math.round(dominantRatio * 100);
101
+
102
+ const toneClass =
103
+ dominantRatio >= 0.85
104
+ ? 'border-red-500/40 bg-red-500/10 text-red-600 dark:text-red-400'
105
+ : dominantRatio >= 0.7
106
+ ? 'border-amber-500/40 bg-amber-500/10 text-amber-600 dark:text-amber-400'
107
+ : 'border-agent-border/60 bg-agent-muted/40 text-agent-muted-foreground hover:text-agent-foreground';
108
+
109
+ const barColor =
110
+ dominantRatio >= 0.85
111
+ ? 'bg-red-500'
112
+ : dominantRatio >= 0.7
113
+ ? 'bg-amber-500'
114
+ : 'bg-agent-primary';
115
+
116
+ const handleCompactNow = async () => {
117
+ if (compacting) return;
118
+ setCompacting(true);
119
+ setFeedback(null);
120
+ try {
121
+ const opts: CompactChatOptions = {};
122
+ if (focus.trim()) opts.focus = focus.trim();
123
+ const res = await compactChat(chatId, opts);
124
+ setFocus('');
125
+ await refreshStatus();
126
+ if (res.queuedOnActiveTurn) {
127
+ setFeedback(t('Compaction queued for the next step.'));
128
+ } else if (res.compacted > 0) {
129
+ setFeedback(t('Compacted {count} earlier messages.', { count: res.compacted }));
130
+ onCompacted?.(res);
131
+ } else {
132
+ setFeedback(t('Context is already compact.'));
133
+ }
134
+ } catch (err) {
135
+ setFeedback(err instanceof Error ? err.message : String(err));
136
+ } finally {
137
+ setCompacting(false);
138
+ }
139
+ };
140
+
141
+ return (
142
+ <div ref={containerRef} className="relative inline-flex items-center">
143
+ <button
144
+ type="button"
145
+ data-testid="context-usage-pill"
146
+ onClick={() => setOpen((prev) => !prev)}
147
+ title={t('Context window and payload usage')}
148
+ className={`inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[11px] leading-tight transition-colors ${toneClass}`}
149
+ >
150
+ <LuMinimize2 className="h-3 w-3 shrink-0 opacity-80" />
151
+ <span>
152
+ {formatCompactCount(estTokens)} · {dominantPct}%
153
+ </span>
154
+ </button>
155
+
156
+ {open && (
157
+ <div
158
+ data-testid="context-usage-popover"
159
+ className="absolute bottom-full left-0 z-50 mb-2 w-72 rounded-agent-lg border border-agent-border bg-agent-canvas p-3 text-xs shadow-lg"
160
+ >
161
+ <div className="font-medium text-agent-foreground">
162
+ {t('Context budget')}
163
+ </div>
164
+
165
+ <div className="mt-2 space-y-2">
166
+ <div>
167
+ <div className="flex items-center justify-between text-[11px] text-agent-muted-foreground">
168
+ <span>{t('Token window')}</span>
169
+ <span>
170
+ {formatCompactCount(estTokens)} / {formatCompactCount(maxTokens)} (
171
+ {Math.round(tokenRatio * 100)}%)
172
+ </span>
173
+ </div>
174
+ <div className="mt-1 h-1.5 w-full overflow-hidden rounded-full bg-agent-muted">
175
+ <div
176
+ className={`h-full transition-all ${barColor}`}
177
+ style={{ width: `${Math.max(2, Math.round(tokenRatio * 100))}%` }}
178
+ />
179
+ </div>
180
+ </div>
181
+
182
+ <div>
183
+ <div className="flex items-center justify-between text-[11px] text-agent-muted-foreground">
184
+ <span>{t('Request body')}</span>
185
+ <span>
186
+ {formatMegabytes(estBytes)} / {formatMegabytes(maxBytes)} (
187
+ {Math.round(byteRatio * 100)}%)
188
+ </span>
189
+ </div>
190
+ <div className="mt-1 h-1.5 w-full overflow-hidden rounded-full bg-agent-muted">
191
+ <div
192
+ className={`h-full transition-all ${barColor}`}
193
+ style={{ width: `${Math.max(2, Math.round(byteRatio * 100))}%` }}
194
+ />
195
+ </div>
196
+ </div>
197
+
198
+ {cacheHitPct !== null && (
199
+ <div className="flex items-center justify-between text-[11px] text-agent-muted-foreground">
200
+ <span>{t('Prompt cache hit')}</span>
201
+ <span>{cacheHitPct}%</span>
202
+ </div>
203
+ )}
204
+
205
+ {(status?.compactionCount ?? 0) > 0 && (
206
+ <div className="text-[11px] text-agent-muted-foreground">
207
+ {t('Auto-compacted {count} times in this chat', {
208
+ count: status?.compactionCount ?? 0,
209
+ })}
210
+ </div>
211
+ )}
212
+ </div>
213
+
214
+ <div className="mt-3 border-t border-agent-border/60 pt-2.5">
215
+ <label className="block text-[11px] text-agent-muted-foreground">
216
+ {t('Keep specific details (optional)')}
217
+ </label>
218
+ <input
219
+ type="text"
220
+ data-testid="compact-focus-input"
221
+ value={focus}
222
+ onChange={(e) => setFocus(e.target.value)}
223
+ placeholder={t('e.g. SQL schema and error codes')}
224
+ className="mt-1 w-full rounded-agent-md border border-agent-border bg-agent-card px-2 py-1 text-xs text-agent-foreground placeholder:text-agent-muted-foreground/60 focus:outline-none focus:ring-1 focus:ring-agent-primary"
225
+ />
226
+ <button
227
+ type="button"
228
+ data-testid="compact-now-btn"
229
+ disabled={compacting}
230
+ onClick={() => void handleCompactNow()}
231
+ className="mt-2 flex w-full items-center justify-center gap-1.5 rounded-agent-md bg-agent-primary px-2.5 py-1.5 text-xs font-medium text-agent-primary-foreground transition hover:bg-agent-primary/90 disabled:opacity-50"
232
+ >
233
+ {compacting ? t('Compacting context…') : t('Compact context now')}
234
+ </button>
235
+ {feedback && (
236
+ <div
237
+ role="status"
238
+ data-testid="compact-feedback"
239
+ className="mt-1.5 text-[11px] text-agent-muted-foreground"
240
+ >
241
+ {feedback}
242
+ </div>
243
+ )}
244
+ </div>
245
+ </div>
246
+ )}
247
+ </div>
248
+ );
249
+ }
@@ -211,6 +211,36 @@ interface MessageListProps {
211
211
  onSelectSuggestion?: (text: string) => void;
212
212
  }
213
213
 
214
+ const COMPACTED_SUMMARY_PREFIX = '[context compacted: earlier conversation summarized]';
215
+
216
+ function CompactionSummaryDivider({ content }: { content: string }) {
217
+ const [expanded, setExpanded] = useState(false);
218
+ const body = content.startsWith(COMPACTED_SUMMARY_PREFIX)
219
+ ? content.slice(COMPACTED_SUMMARY_PREFIX.length).trim()
220
+ : content;
221
+ return (
222
+ <div data-testid="compaction-divider" className="my-2">
223
+ <div className="flex items-center gap-2 text-[11px] text-agent-muted-foreground">
224
+ <div className="h-px flex-1 bg-agent-border/60" />
225
+ <button
226
+ type="button"
227
+ onClick={() => setExpanded((v) => !v)}
228
+ aria-expanded={expanded}
229
+ className="rounded-full border border-agent-border/60 bg-agent-muted/40 px-2.5 py-0.5 transition-colors hover:text-agent-foreground"
230
+ >
231
+ {t('Earlier conversation compacted')}
232
+ </button>
233
+ <div className="h-px flex-1 bg-agent-border/60" />
234
+ </div>
235
+ {expanded && body ? (
236
+ <div className="mt-1.5 rounded-agent-md border border-agent-border/60 bg-agent-muted/30 px-3 py-2 text-xs whitespace-pre-wrap text-agent-muted-foreground">
237
+ {body}
238
+ </div>
239
+ ) : null}
240
+ </div>
241
+ );
242
+ }
243
+
214
244
  export function MessageList({
215
245
  messages,
216
246
  isStreaming,
@@ -453,6 +483,11 @@ export function MessageList({
453
483
  {turn.userGroup.messages.length === 1 ? (
454
484
  internalTrigger(turn.userGroup.messages[0]) ? (
455
485
  null
486
+ ) : turn.userGroup.messages[0].content.startsWith(COMPACTED_SUMMARY_PREFIX) ? (
487
+ <CompactionSummaryDivider
488
+ key={turn.userGroup.messages[0].id}
489
+ content={turn.userGroup.messages[0].content}
490
+ />
456
491
  ) : (
457
492
  <UserMessage
458
493
  key={turn.userGroup.messages[0].id}
@@ -477,6 +512,10 @@ export function MessageList({
477
512
  {turn.userGroup.messages.map((msg, idx) => (
478
513
  internalTrigger(msg) ? (
479
514
  null
515
+ ) : msg.content.startsWith(COMPACTED_SUMMARY_PREFIX) ? (
516
+ <div key={msg.id} className="px-3 py-1">
517
+ <CompactionSummaryDivider content={msg.content} />
518
+ </div>
480
519
  ) : (
481
520
  <UserMessage
482
521
  key={msg.id}
@@ -152,10 +152,14 @@ function actionLabel(action: FailureAction): string {
152
152
  switch (action.kind) {
153
153
  case 'retry':
154
154
  return t('Continue');
155
+ case 'compact-and-retry':
156
+ return t('Compact context and continue');
155
157
  case 'network-diagnostics':
156
158
  return t('Network diagnostics');
157
159
  case 'open-model-settings':
158
160
  return t('Open model settings');
161
+ case 'open-license-settings':
162
+ return t('Manage license');
159
163
  case 'new-chat':
160
164
  return t('New chat');
161
165
  }
@@ -174,6 +178,8 @@ function causeSummary(detail: TurnFailureDetail | undefined, reason: string): st
174
178
  return t('The service reported its own failure.');
175
179
  case 'context_overflow':
176
180
  return t('The request exceeds the model window.');
181
+ case 'license':
182
+ return t('The system deployment license is expired or invalid.');
177
183
  case 'invalid_request':
178
184
  return t('The service rejected the request.');
179
185
  default:
@@ -193,6 +199,8 @@ function categoryLabel(kind: string | undefined): string {
193
199
  return t('Service error');
194
200
  case 'context_overflow':
195
201
  return t('Conversation too long');
202
+ case 'license':
203
+ return t('System license');
196
204
  case 'invalid_request':
197
205
  return t('Rejected request');
198
206
  default:
@@ -23,8 +23,10 @@ export { readTurnFailureDetail, readTurnFailureKind };
23
23
  /** One action a failed turn can offer. */
24
24
  export type FailureAction =
25
25
  | { kind: 'retry' }
26
+ | { kind: 'compact-and-retry' }
26
27
  | { kind: 'network-diagnostics' }
27
28
  | { kind: 'open-model-settings' }
29
+ | { kind: 'open-license-settings' }
28
30
  | { kind: 'new-chat' };
29
31
 
30
32
  /** Everything the card renders, derived from one failure. */
@@ -111,9 +113,19 @@ export function failurePresentation(
111
113
  case 'context_overflow':
112
114
  return {
113
115
  title: t('This conversation is too long for the model'),
114
- body: t('Start a new chat, or select Regenerate to try a different approach.'),
115
- primary: { kind: 'new-chat' },
116
- secondary: [{ kind: 'retry' }],
116
+ body: t('Compact earlier messages to free up space and continue, or start a new chat.'),
117
+ primary: { kind: 'compact-and-retry' },
118
+ secondary: [{ kind: 'new-chat' }, { kind: 'retry' }],
119
+ classified: true,
120
+ };
121
+ case 'license':
122
+ return {
123
+ title: t('Enterprise license expired or invalid'),
124
+ body: t(
125
+ 'New AI turns are paused until an administrator updates the license. Your chat history, files, and exports remain fully accessible.',
126
+ ),
127
+ primary: { kind: 'open-license-settings' },
128
+ secondary: [],
117
129
  classified: true,
118
130
  };
119
131
  case 'invalid_request':
@@ -110,6 +110,8 @@ function kindLabel(kind: string): string {
110
110
  return t('Service error');
111
111
  case 'context_overflow':
112
112
  return t('Conversation too long');
113
+ case 'license':
114
+ return t('System license');
113
115
  case 'invalid_request':
114
116
  return t('Rejected request');
115
117
  default:
@@ -19,7 +19,7 @@ import { trackBehavior } from '@/lib/insights';
19
19
  import { getHostBridge, hasHostBridge } from '@/lib/host-bridge';
20
20
  import { deleteChatIfEmpty, pruneEmptyChats } from '@/lib/local-api';
21
21
  import { PORTABLE_CHATS_CHANGED_EVENT } from '@/lib/portable';
22
- import { getPackChatSlots, type PackChatSlotContribution } from '@/packs/registry';
22
+ import { getPackChatSlots, getPackTopBanners, type PackChatSlotContribution } from '@/packs/registry';
23
23
  import {
24
24
  useChatsAndAgents,
25
25
  type UseChatsAndAgentsResult,
@@ -779,6 +779,9 @@ function AgentLayoutContent() {
779
779
  }}
780
780
  />
781
781
  )}
782
+ {getPackTopBanners().map((BannerComponent, idx) => (
783
+ <BannerComponent key={idx} />
784
+ ))}
782
785
  <div className="min-h-0 flex-1 overflow-hidden">
783
786
  <Outlet
784
787
  context={{
@@ -466,6 +466,67 @@ async function request<T>(input: LocalBackendRequestInput): Promise<T> {
466
466
  return { tasks: [] } as T;
467
467
  }
468
468
 
469
+ if (method === 'GET' && rest === '/context-status') {
470
+ const msgs = state.messagesByChatId[chatId] ?? [];
471
+ const rawChars = msgs.reduce((sum, m) => sum + (m.content?.length ?? 0), 0);
472
+ const hasSummary = msgs.some((m) => m.content?.includes('<summary>'));
473
+ const estimatedTokens = hasSummary
474
+ ? Math.max(1_800, Math.round(rawChars / 3.5))
475
+ : Math.max(92_000, Math.round(rawChars / 3.5) + 90_000);
476
+ const estimatedBytes = Math.max(16_384, rawChars * 2);
477
+ return {
478
+ chatId,
479
+ recordId: `rec-${chatId}`,
480
+ estimatedTokens,
481
+ maxContextTokens: 128_000,
482
+ estimatedBytes,
483
+ maxRequestBytes: 4_194_304,
484
+ promptTokens: estimatedTokens,
485
+ cachedPromptTokens: Math.round(estimatedTokens * 0.62),
486
+ cacheCreationTokens: 0,
487
+ compactionCount: msgs.filter((m) => m.content?.includes('<summary>')).length,
488
+ compactionEpoch: msgs.filter((m) => m.content?.includes('<summary>')).length,
489
+ } as T;
490
+ }
491
+
492
+ if (method === 'POST' && rest === '/compact') {
493
+ const body = (input.body ?? {}) as {
494
+ focus?: string;
495
+ keepHeadTurns?: number;
496
+ keepTailMessages?: number;
497
+ };
498
+ const msgs = state.messagesByChatId[chatId] ?? [];
499
+ const keepTail = Math.max(1, body.keepTailMessages ?? 2);
500
+ const tail = msgs.slice(-keepTail);
501
+ const preTokens = Math.max(92_000, msgs.length * 4_500);
502
+ const postTokens = Math.max(3_200, tail.length * 1_600);
503
+ const focusNote = body.focus?.trim()
504
+ ? `Focused retention: ${body.focus.trim()}\n- `
505
+ : '';
506
+ const summaryText = `<summary>\n- ${focusNote}Compacted ${Math.max(1, msgs.length - tail.length)} earlier messages in the interactive browser demo while preserving active task state and deliverables.\n</summary>`;
507
+ const summaryMsg: MutableMessage = {
508
+ id: `msg-compact-${Date.now()}`,
509
+ chatId,
510
+ role: 'user',
511
+ content: summaryText,
512
+ createdAt: new Date().toISOString(),
513
+ messageMetadata: JSON.stringify({ compactionSummary: true, preTokens, postTokens }),
514
+ };
515
+ state.messagesByChatId[chatId] = [summaryMsg, ...tail];
516
+ const epochs = state.messagesByChatId[chatId].filter((m) =>
517
+ m.content?.includes('<summary>'),
518
+ ).length;
519
+ return {
520
+ compacted: Math.max(1, msgs.length - tail.length),
521
+ preTokens,
522
+ postTokens,
523
+ preBytes: preTokens * 4,
524
+ postBytes: postTokens * 4,
525
+ summaryText,
526
+ compactionEpoch: epochs,
527
+ } as T;
528
+ }
529
+
469
530
  if (method === 'GET' && rest === '/project-context') {
470
531
  const chat = state.chats.find((c) => c.id === chatId);
471
532
  const project = chat?.projectId
@@ -649,6 +649,54 @@ export async function forkChat(chatId: string) {
649
649
  });
650
650
  }
651
651
 
652
+ export interface CompactChatOptions {
653
+ focus?: string;
654
+ keepHeadTurns?: number;
655
+ keepTailMessages?: number;
656
+ }
657
+
658
+ export interface CompactChatResult {
659
+ compacted: number;
660
+ queuedOnActiveTurn?: boolean;
661
+ preTokens?: number;
662
+ postTokens?: number;
663
+ preBytes?: number;
664
+ postBytes?: number;
665
+ summaryText?: string;
666
+ compactionEpoch?: number;
667
+ }
668
+
669
+ /** Authoritatively compact a chat session's context (Phase 10 R3). */
670
+ export async function compactChat(chatId: string, options: CompactChatOptions = {}) {
671
+ return bridge().localBackend.request<CompactChatResult>({
672
+ method: 'POST',
673
+ path: `/api/v2/chats/${encodeURIComponent(chatId)}/compact`,
674
+ body: options,
675
+ });
676
+ }
677
+
678
+ export interface ChatContextStatus {
679
+ chatId: string;
680
+ recordId: string;
681
+ estimatedTokens: number;
682
+ maxContextTokens: number;
683
+ estimatedBytes: number;
684
+ maxRequestBytes: number;
685
+ promptTokens: number;
686
+ cachedPromptTokens: number;
687
+ cacheCreationTokens: number;
688
+ compactionCount: number;
689
+ compactionEpoch: number;
690
+ }
691
+
692
+ /** Read live token & wire-byte budget status for a chat (Phase 10 R3). */
693
+ export async function getChatContextStatus(chatId: string) {
694
+ return bridge().localBackend.request<ChatContextStatus>({
695
+ method: 'GET',
696
+ path: `/api/v2/chats/${encodeURIComponent(chatId)}/context-status`,
697
+ });
698
+ }
699
+
652
700
  /** 用户重命名。409 表示会话锁被占用,调用方恢复旧名。 */
653
701
  export async function updateChatTitle(chatId: string, title: string) {
654
702
  return bridge().localBackend.request<{ id: string; title: string }>({
@@ -9,6 +9,7 @@
9
9
  * 的 web/ 目录)。
10
10
  */
11
11
 
12
+ import type { ComponentType } from 'react';
12
13
  import type {
13
14
  PackChatSlotAutoRevealApi,
14
15
  PackChatSlotContribution,
@@ -33,6 +34,7 @@ export type {
33
34
  const routes: PackRouteContribution[] = [];
34
35
  const settingsPanels: PackSettingsPanelContribution[] = [];
35
36
  const chatSlots: PackChatSlotContribution[] = [];
37
+ const topBanners: ComponentType[] = [];
36
38
  const hiddenSlashSkills = new Set<string>();
37
39
  const registeredPacks = new Set<string>();
38
40
 
@@ -45,6 +47,7 @@ export function registerPackRenderer(packId: string, contributions: PackRenderer
45
47
  routes.push(...(contributions.routes ?? []));
46
48
  settingsPanels.push(...(contributions.settingsPanels ?? []));
47
49
  chatSlots.push(...(contributions.chatSlots ?? []));
50
+ topBanners.push(...(contributions.topBanners ?? []));
48
51
  for (const name of contributions.hiddenSlashSkills ?? []) hiddenSlashSkills.add(name);
49
52
  }
50
53
 
@@ -60,6 +63,10 @@ export function getPackChatSlots(): readonly PackChatSlotContribution[] {
60
63
  return chatSlots;
61
64
  }
62
65
 
66
+ export function getPackTopBanners(): readonly ComponentType[] {
67
+ return topBanners;
68
+ }
69
+
63
70
  /** 包贡献的隐藏 slash 技能名集合(bootstrap 完成后稳定,渲染期只读)。 */
64
71
  export function getPackHiddenSlashSkills(): ReadonlySet<string> {
65
72
  return hiddenSlashSkills;
@@ -12,6 +12,7 @@ import { ChatHeader } from "@/components/ChatHeader";
12
12
  import { EmptyChatHero } from "@/components/chat/EmptyChatHero";
13
13
  import type { RetryState } from "@/components/chat/RetryStatus";
14
14
  import type { FailureAction } from "@/components/chat/turn-failure";
15
+ import { ContextUsagePill } from "@/components/chat/ContextUsagePill";
15
16
  import { LocalChatPanel } from "@/components/chat/LocalChatPanel";
16
17
  import { ModelPicker } from "@/components/chat/ModelPicker";
17
18
  import {
@@ -58,6 +59,7 @@ import {
58
59
  } from "@/components/chat/ChatProjectBadge";
59
60
  import { ProjectTrustBanner } from "@/components/chat/ProjectTrustBanner";
60
61
  import {
62
+ compactChat,
61
63
  getChatLiveStream,
62
64
  type ChatLiveStream,
63
65
  type LocalChatMessage,
@@ -686,6 +688,13 @@ function AgentChatView({
686
688
  persistExecPolicy(next);
687
689
  }, []);
688
690
 
691
+ const [liveMetadataByMessageId, setLiveMetadataByMessageId] = useState<
692
+ Record<string, string>
693
+ >({});
694
+ const [tailLiveMetadata, setTailLiveMetadata] = useState<string | null>(null);
695
+ const tailLiveMetadataRef = useRef<string | null>(null);
696
+ const latestMessagesRef = useRef<ChatMessage[]>(initialMessages ?? []);
697
+
689
698
  const handleUnknownEvent = useCallback((event: SSEEvent) => {
690
699
  const ev = event as any;
691
700
  if (ev.type !== "agent") return;
@@ -825,6 +834,15 @@ function AgentChatView({
825
834
  }
826
835
  pendingTurnUsageRef.current = undefined;
827
836
  setTailAssistantDbId(messageId);
837
+ const persistedMetadata = ev.payload?.messageMetadata;
838
+ if (typeof persistedMetadata === "string" && persistedMetadata) {
839
+ tailLiveMetadataRef.current = persistedMetadata;
840
+ setTailLiveMetadata(persistedMetadata);
841
+ setLiveMetadataByMessageId((prev) => ({
842
+ ...prev,
843
+ [messageId]: persistedMetadata,
844
+ }));
845
+ }
828
846
  }
829
847
  // AI 标题更新走的是后台 IPC 广播(chat-title-updated)而不是 SSE——
830
848
  // 见 AgentLayout 里的订阅。SSE 通道在 [DONE] 之后就不再监听了,title-gen
@@ -857,9 +875,12 @@ function AgentChatView({
857
875
  onUnknownEvent: handleUnknownEvent,
858
876
  onStreamError: handleStreamError,
859
877
  });
878
+ latestMessagesRef.current = messages;
860
879
  const awaitingRemoteActiveSnapshotRef = useRef(false);
861
880
  useEffect(() => {
862
881
  awaitingRemoteActiveSnapshotRef.current = false;
882
+ tailLiveMetadataRef.current = null;
883
+ setTailLiveMetadata(null);
863
884
  }, [chatId]);
864
885
 
865
886
  useEffect(() => {
@@ -1040,6 +1061,20 @@ function AgentChatView({
1040
1061
 
1041
1062
  const handleSubmit = useCallback(
1042
1063
  (input: { content: string; metadata?: Record<string, unknown> }) => {
1064
+ const trimmedCmd = input.content.trim();
1065
+ if (/^\/compact(?:\s+|$)/i.test(trimmedCmd) && hasHostBridge()) {
1066
+ const focusArg = trimmedCmd.replace(/^\/compact\s*/i, "").trim();
1067
+ void compactChat(chatId, focusArg ? { focus: focusArg } : {})
1068
+ .then((res) => {
1069
+ if (res.compacted > 0) {
1070
+ onBranchTick();
1071
+ }
1072
+ })
1073
+ .catch((err: unknown) =>
1074
+ setNewChatError(err instanceof Error ? err.message : String(err)),
1075
+ );
1076
+ return;
1077
+ }
1043
1078
  trackBehavior('composer_send', {
1044
1079
  empty: !input.content.trim(),
1045
1080
  mode: input.metadata?.mode === 'plan' ? 'plan' : 'agent',
@@ -1082,12 +1117,21 @@ function AgentChatView({
1082
1117
  ...(execPolicy === "full" ? { execPolicy: "full" } : {}),
1083
1118
  orchestration: readOrchestrationSetting(),
1084
1119
  };
1120
+ const prevTailMeta = tailLiveMetadataRef.current;
1121
+ if (prevTailMeta) {
1122
+ const last = latestMessagesRef.current[latestMessagesRef.current.length - 1];
1123
+ if (last?.role === "assistant") {
1124
+ setLiveMetadataByMessageId((prev) => ({ ...prev, [last.id]: prevTailMeta }));
1125
+ }
1126
+ }
1127
+ tailLiveMetadataRef.current = null;
1128
+ setTailLiveMetadata(null);
1085
1129
  return sendUserMessage({
1086
1130
  ...input,
1087
1131
  metadata: Object.keys(metadata).length > 0 ? metadata : undefined,
1088
1132
  });
1089
1133
  },
1090
- [sendUserMessage, modelOverride, effortOverride, execPolicy],
1134
+ [sendUserMessage, modelOverride, effortOverride, execPolicy, chatId, onBranchTick],
1091
1135
  );
1092
1136
 
1093
1137
  const handleEditUserMessage = useCallback(
@@ -1270,6 +1314,15 @@ function AgentChatView({
1270
1314
  ...(mode === "plan" ? { mode: "plan" as const } : {}),
1271
1315
  ...(execPolicy === "full" ? { execPolicy: "full" as const } : {}),
1272
1316
  };
1317
+ const prevTailMeta = tailLiveMetadataRef.current;
1318
+ if (prevTailMeta) {
1319
+ const last = latestMessagesRef.current[latestMessagesRef.current.length - 1];
1320
+ if (last?.role === "assistant") {
1321
+ setLiveMetadataByMessageId((prev) => ({ ...prev, [last.id]: prevTailMeta }));
1322
+ }
1323
+ }
1324
+ tailLiveMetadataRef.current = null;
1325
+ setTailLiveMetadata(null);
1273
1326
  return resumeTurn({
1274
1327
  metadata: Object.keys(metadata).length > 0 ? metadata : undefined,
1275
1328
  });
@@ -1297,6 +1350,27 @@ function AgentChatView({
1297
1350
  disabled: isStreaming,
1298
1351
  hint: isStreaming ? t("This chat is running. Continue when it finishes.") : undefined,
1299
1352
  };
1353
+ case "compact-and-retry":
1354
+ return hasHostBridge()
1355
+ ? {
1356
+ onClick: () => {
1357
+ void compactChat(chatId)
1358
+ .then(() => {
1359
+ onBranchTick();
1360
+ void handleContinueInterrupted();
1361
+ })
1362
+ .catch((err: unknown) =>
1363
+ setNewChatError(err instanceof Error ? err.message : String(err)),
1364
+ );
1365
+ },
1366
+ disabled: isStreaming,
1367
+ hint: isStreaming
1368
+ ? t("This chat is running. Continue when it finishes.")
1369
+ : undefined,
1370
+ }
1371
+ : null;
1372
+ case "open-license-settings":
1373
+ return null;
1300
1374
  case "network-diagnostics":
1301
1375
  // 诊断区挂在设置页「通用」下(settingsChrome('diagnose') 控制显隐)。
1302
1376
  return settingsChrome("diagnose")
@@ -1330,10 +1404,12 @@ function AgentChatView({
1330
1404
  [
1331
1405
  chat?.agentId,
1332
1406
  chat?.projectId,
1407
+ chatId,
1333
1408
  ctx,
1334
1409
  handleContinueInterrupted,
1335
1410
  isStreaming,
1336
1411
  navigate,
1412
+ onBranchTick,
1337
1413
  ],
1338
1414
  );
1339
1415
 
@@ -1433,9 +1509,23 @@ function AgentChatView({
1433
1509
  // ── 把远端运行中的快照叠进渲染层 ────────────────────────────────────
1434
1510
  const remoteContent = remoteStreaming ? (liveStream.content ?? "") : null;
1435
1511
  const effectiveMessages = useMemo<ChatMessage[]>(() => {
1436
- if (remoteContent === null) return messages;
1512
+ const hasMapped = Object.keys(liveMetadataByMessageId).length > 0;
1513
+ const base =
1514
+ !hasMapped && !tailLiveMetadata
1515
+ ? messages
1516
+ : messages.map((m, idx) => {
1517
+ if ((m as ChatMessageWithMetadata).messageMetadata) return m;
1518
+ const mapped =
1519
+ liveMetadataByMessageId[m.id] ??
1520
+ (idx === messages.length - 1 && m.role === "assistant"
1521
+ ? (tailLiveMetadata ?? undefined)
1522
+ : undefined);
1523
+ if (!mapped) return m;
1524
+ return { ...m, messageMetadata: mapped } as ChatMessage;
1525
+ });
1526
+ if (remoteContent === null) return base;
1437
1527
  return [
1438
- ...messages,
1528
+ ...base,
1439
1529
  {
1440
1530
  id: `live_${chatId}`,
1441
1531
  role: "assistant",
@@ -1443,7 +1533,7 @@ function AgentChatView({
1443
1533
  createdAt: new Date().toISOString(),
1444
1534
  },
1445
1535
  ];
1446
- }, [messages, remoteContent, chatId]);
1536
+ }, [messages, liveMetadataByMessageId, tailLiveMetadata, remoteContent, chatId]);
1447
1537
  const effectiveIsStreaming = isStreaming || remoteStreaming;
1448
1538
 
1449
1539
  useEffect(() => {
@@ -1602,18 +1692,28 @@ function AgentChatView({
1602
1692
  : undefined
1603
1693
  }
1604
1694
  inputToolbarExtras={
1605
- <ModelPicker
1606
- model={modelOverride}
1607
- reasoningEffort={effortOverride}
1608
- onSelectModel={setModelOverride}
1609
- onSelectEffort={setEffortOverride}
1610
- onOpenSettings={
1611
- hasHostBridge() && settingsChrome("llm")
1612
- ? () => setLlmSettingsOpen(true)
1613
- : undefined
1614
- }
1615
- disabled={isStreaming}
1616
- />
1695
+ <div className="inline-flex items-center gap-1.5">
1696
+ <ModelPicker
1697
+ model={modelOverride}
1698
+ reasoningEffort={effortOverride}
1699
+ onSelectModel={setModelOverride}
1700
+ onSelectEffort={setEffortOverride}
1701
+ onOpenSettings={
1702
+ hasHostBridge() && settingsChrome("llm")
1703
+ ? () => setLlmSettingsOpen(true)
1704
+ : undefined
1705
+ }
1706
+ disabled={isStreaming}
1707
+ />
1708
+ <ContextUsagePill
1709
+ chatId={chatId}
1710
+ messageCount={effectiveMessages.length}
1711
+ isStreaming={effectiveIsStreaming}
1712
+ livePromptTokens={currentTurnUsage?.promptTokens}
1713
+ liveCachedPromptTokens={currentTurnUsage?.cachedPromptTokens}
1714
+ onCompacted={() => onBranchTick()}
1715
+ />
1716
+ </div>
1617
1717
  }
1618
1718
  mode={mode}
1619
1719
  onModeChange={handleModeChange}