Skip to content

Commit f926dfa

Browse files
hotlongclaude
andauthored
refactor(app-shell): split AiChatPage into ChatPane and helper modules, move-only (#37803)
<!-- claude-projects-attribution: {"github_login":"hotlong"} --> _Requested by **Jack** · [project thread](https://claude.ai/code/project/chan_01EF41AQooqveF2DGD8nqPzS?thread=cmsg_01EF41AQooqveF2DGD8nqPzS5ABkjZhavN8ufqbqE2sRDe)_ Fixes #37730 ## 维护者速读 - 用户看到的变化:没有。全页 AI 对话和侧边停靠的对话照常工作,只是代码换了文件放。 - 为什么:`AiChatPage.tsx` 删完 build 后还有 2152 行,后续对话界面改进都要改它,先拆开减少冲突。 - 出问题会怎样:只搬代码不改逻辑,最坏是某个导入断了,类型检查和测试会直接红;回滚这一个合并即可。 - 需要你做的:改动行数 3305(搬家导致增删各一遍)超过 3000 行的人合门槛,按规定需要你点批准或亲手合并;其余照席位流程走。 ## What changes `ui/packages/app-shell/src/console/ai/AiChatPage.tsx` goes from 2152 to 652 lines. It keeps `AiChatPage`, `AiChatPageProps`, `EMPTY_INITIAL_MESSAGES`, the `useHomePath()` call and the top bar `<header>`. Everything else moves byte for byte into six modules in the same directory: | New module | What moved | |:---|:---| | `ChatPane.tsx` | `ChatPane`, `ChatPaneProps` | | `aiChatHydration.ts` | `hydratedMessagesToChatMessages`, `partToolState`, `partApproval`, `partString`, `firstUserMessageText` | | `aiChatLinks.ts` | `listLinkTarget`, `recordOpenTarget`, `nextSectionOpening` and the module counter `sectionOpenings` | | `useDeferredFirstSend.ts` | `PendingFirstMessage`, `useDeferredFirstSend`, `isSameFile`, `isSameFirstSend`, `useComposerDraftHandoff`, `ComposerDraftHandoff`, the module `composerDraftHandoffs` WeakMap | | `aiChatChrome.ts` | `matchAiChatShortcut`, `AiChatShortcut`, `TOGGLE_CHATS_LIST_SHORTCUT`, `NEW_CHAT_SHORTCUT`, `useCollapsibleChatsList`, `CollapsibleChatsList`, `CHATS_COLLAPSED_STORAGE_KEY`, `resolveCollapseToDockTarget` | | `agentCopy.ts` | `agentEmptyState`, `localizeAgentLabel`, `PLATFORM_AGENT_LABEL_KEYS`, `buildAgentSuggestions`, `genericSuggestions`, `dataChatSuggestions`, `TranslationFn` | - Every name `AiChatPage.tsx` exported is re-exported from it by name (`export { … } from`, `export type { … } from`; no `export *`), so every import path stands. `ChatDockConversation.tsx` still imports `ChatPane` from `AiChatPage.js`, so the four ChatDock tests that mock that path, and the dock's `React.lazy` boundary, are unchanged. - `ui/packages/app-shell/src/index.ts`, `ui/packages/plugin-chatbot/src/index.tsx` and `ui/packages/plugin-chatbot/src/core.ts` are untouched. - The two module-level singletons (`sectionOpenings`, `composerDraftHandoffs`) exist once, in their new modules. - No new module imports `AiChatPage.tsx`. The graph is `AiChatPage → ChatPane → {aiChatLinks, aiChatHydration, agentCopy, useDeferredFirstSend}`, plus `AiChatPage → {aiChatChrome, aiChatHydration, useDeferredFirstSend}`. - Three helpers that were file-private now cross a module boundary and gained `export` in their new module: `nextSectionOpening`, `firstUserMessageText`, `localizeAgentLabel`. They are not re-exported from `AiChatPage.tsx`, because they were never exported from it. ### What is not a moved line Apart from moved lines, the diff is only: import lists, the re-export block, a short header comment on each new module, and the three `export` keywords above. Checked by comparing the multiset of removed lines with the multiset of added lines over `console/ai/*.ts(x)`: everything left over on either side is one of those kinds. The import of `ChatbotEnhancedMessage as ChatMessage` keeps its long comment in `aiChatHydration.ts`, the file that produces those messages; `ChatPane.tsx` carries a two-line pointer to it. ``` git diff --color-moved=zebra --stat origin/main...HEAD .changeset/37730-ai-chat-page-split.md | 10 + .../homeRecoveryRedirectsFollowDeclaration-7373.test.ts | 10 +- ui/packages/app-shell/src/console/ai/AiChatPage.tsx | 1618 +----- ui/packages/app-shell/src/console/ai/ChatPane.tsx | 869 ++++ .../ai/__tests__/AiChatPage.runtimeMessageSeam.test.tsx | 5 +- ui/packages/app-shell/src/console/ai/agentCopy.ts | 82 + ui/packages/app-shell/src/console/ai/aiChatChrome.ts | 131 + ui/packages/app-shell/src/console/ai/aiChatHydration.ts | 195 + ui/packages/app-shell/src/console/ai/aiChatLinks.ts | 52 + ui/packages/app-shell/src/console/ai/useDeferredFirstSend.ts | 333 ++ 10 files changed, 1716 insertions(+), 1589 deletions(-) ``` ### Tests Only the two read-scope changes the card allows; no assertion changed: 1. `console/ai/__tests__/AiChatPage.runtimeMessageSeam.test.tsx`, the "#4437 source net": reads `AiChatPage.tsx` and `ChatPane.tsx` joined, since `const runtimeMessages = useMemo(() => toRuntimeMessages(messages), [messages]);` now lives in `ChatPane`. 2. `__tests__/homeRecoveryRedirectsFollowDeclaration-7373.test.ts`: the AiChatPage site lists the six new modules under its existing `alsoReads`. ## Why Card #37730 under epic #37690 (split C). The plan was reviewed against the code before the card was filed. Behaviour does not change; this only makes the next AI chat changes conflict less and review smaller. ## Verification Clause-②: no Metadata-protocol: none Read first: the re-export block at the top of `AiChatPage.tsx`, then `ChatPane.tsx`'s import list. Two-minute check: `pnpm --dir ui exec vitest run packages/app-shell/src/console/ai/__tests__/AiChatPage.runtimeMessageSeam.test.tsx packages/app-shell/src/__tests__/homeRecoveryRedirectsFollowDeclaration-7373.test.ts`. <details><summary>Local readings (objectstack-ai/objectstack, branch head on main 6e8f663)</summary> - `tsc --noEmit` in `ui/packages/app-shell`, `tsconfig.json` and `tsconfig.test.json`: exit 0. - `eslint --quiet packages/app-shell/src/console/ai/` plus the 7373 test: exit 0. Without `--quiet`, the warnings over the page and the six modules are 16, against 18 on the page before the split (`react-refresh/only-export-components` 13 → 11; the rest unchanged). - vitest over `console/ai/`, `layout/__tests__/`, `KeyboardShortcutsDialog.wiredOnly-11674`, `useChatConversation`, `homeRecoveryRedirectsFollowDeclaration-7373` and i18n `console-namespace-3546`: 203 files, 1768 tests passed. - `pnpm console:build`: exit 0. `pnpm --dir ui check:eager-closure`: exit 0; the eager closure's only chat chunk is `plugin-chatbot-core`; `@object-ui/plugin-chatbot`, `ChatDockConversation` and the split modules stay lazy. In this build the shared lazy chunk that holds `useChatConversation` takes its name from `aiChatHydration` (rolldown's naming pick, not a membership change the budget gate saw). - dispatch-gates: all 38 derived commands ran and exit 0; `dispatch-gates --ran` reconciles 38 of 38, 0 NOT-MEASURED. - `overlap-check`: merges cleanly with `origin/main`; no open PR shares a file. - The full ui suite was not run locally (it does not finish in this container); CI's sharded Test UI is the verdict. </details> ## Acceptance notes - Size: 3305 changed lines (+1716 / -1589), over the 3000-line threshold, so this lands the Tier H way (an authorized approval, or the maintainer's merge or enqueue), although the change is move-only. - `react-refresh/only-export-components` warnings over the page and the six modules drop from 13 to 11, because the non-component exports left the page file; no new lint warning class appears. ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes. - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: its generated artifacts are regenerated and committed. (Not touched.) - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. - [x] The *Before Submitting* list in CONTRIBUTING.md is done. --- _Generated by [Claude Code](https://claude.ai/code)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 754e216 commit f926dfa

10 files changed

Lines changed: 1715 additions & 1588 deletions
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@object-ui/app-shell': patch
3+
---
4+
5+
refactor(app-shell): split the AI chat page into modules, with no change in behaviour
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
`console/ai/AiChatPage.tsx` keeps the page itself (`AiChatPage`, `AiChatPageProps`); the rest moved, byte for byte, into six modules beside it: `ChatPane.tsx` (the conversation column), `aiChatHydration.ts` (stored history to rendered messages), `aiChatLinks.ts` (the list and record addresses the chat opens), `useDeferredFirstSend.ts` (the held first send and the composer draft hand-off across the pane's remount), `aiChatChrome.ts` (the collapsible conversations list, its shortcuts and the collapse-to-dock landing) and `agentCopy.ts` (agent labels, empty state and starter suggestions). Every name the page exported is still exported from `AiChatPage.js` by name, and the package entry is unchanged, so no import changes.

‎ui/packages/app-shell/src/__tests__/homeRecoveryRedirectsFollowDeclaration-7373.test.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,14 @@ const RECOVERY_SITES: ReadonlyArray<{
131131
},
132132
{
133133
file: 'packages/app-shell/src/console/ai/AiChatPage.tsx',
134+
alsoReads: [
135+
'packages/app-shell/src/console/ai/ChatPane.tsx',
136+
'packages/app-shell/src/console/ai/aiChatHydration.ts',
137+
'packages/app-shell/src/console/ai/aiChatLinks.ts',
138+
'packages/app-shell/src/console/ai/useDeferredFirstSend.ts',
139+
'packages/app-shell/src/console/ai/aiChatChrome.ts',
140+
'packages/app-shell/src/console/ai/agentCopy.ts',
141+
],
134142
site: 'the AI page: no-agent screen + collapse-to-dock landing',
135143
expression: /const homePath = useHomePath\(\)/,
136144
},

‎ui/packages/app-shell/src/console/ai/AiChatPage.tsx‎

Lines changed: 31 additions & 1587 deletions
Large diffs are not rendered by default.

‎ui/packages/app-shell/src/console/ai/ChatPane.tsx‎

Lines changed: 869 additions & 0 deletions
Large diffs are not rendered by default.

‎ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.runtimeMessageSeam.test.tsx‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -298,7 +298,10 @@ describe('#4437 fold-sensitivity: the two insensitive compute sites stay insensi
298298
*/
299299
describe('#4437 source net: the five casts do not come back', () => {
300300
const PAGE = resolve(dirname(fileURLToPath(import.meta.url)), '..', 'AiChatPage.tsx');
301-
const source = readFileSync(PAGE, 'utf8');
301+
// objectstack#37730 — `ChatPane` was split out of the page move-only, so the
302+
// guarded text is the page plus that module, read as one.
303+
const PANE = resolve(dirname(fileURLToPath(import.meta.url)), '..', 'ChatPane.tsx');
304+
const source = [PAGE, PANE].map((file) => readFileSync(file, 'utf8')).join('\n');
302305
const codeOnly = source
303306
.split('\n')
304307
.filter((line) => !/^\s*(\/\/|\/\*|\*)/.test(line))
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* The AI chat's per-agent copy: the localized agent label, the empty state and
5+
* the starter suggestions. Split out of `AiChatPage.tsx` move-only
6+
* (objectstack#37730).
7+
*/
8+
9+
import { agentRouteName, isAskAgent } from '@object-ui/plugin-chatbot/core';
10+
11+
// Keyed by the FRIENDLY agent name (alias-group head) so the new id, the legacy
12+
// id, and the route segment all localize to the same label.
13+
const PLATFORM_AGENT_LABEL_KEYS: Record<string, { key: string; defaultValue: string }> = {
14+
ask: { key: 'console.ai.agentLabels.ask', defaultValue: 'Ask' },
15+
};
16+
17+
export function localizeAgentLabel(
18+
t: (key: string, options?: Record<string, unknown>) => string,
19+
agentName: string | undefined,
20+
fallback: string,
21+
): string {
22+
const known = agentName ? PLATFORM_AGENT_LABEL_KEYS[agentRouteName(agentName)] : undefined;
23+
if (!known) return fallback;
24+
return t(known.key, { defaultValue: known.defaultValue });
25+
}
26+
27+
/**
28+
* Per-surface empty-state branding: the Ask surface reads as data Q&A ("ask
29+
* about your records"). Keyed by friendly name; falls back to the generic
30+
* empty state for custom agents.
31+
*/
32+
export function agentEmptyState(
33+
t: (key: string, options?: Record<string, unknown>) => string,
34+
agentName: string | undefined,
35+
): { title: string; description: string } {
36+
if (isAskAgent(agentName)) {
37+
return {
38+
title: t('console.ai.empty.ask.title', { defaultValue: 'Ask your data' }),
39+
description: t('console.ai.empty.ask.description', {
40+
defaultValue:
41+
'Ask questions about your records — counts, lists, and summaries across the data you can access.',
42+
}),
43+
};
44+
}
45+
return {
46+
title: t('console.ai.emptyTitle', { defaultValue: 'Start a conversation' }),
47+
description: t('console.ai.emptyDescription', {
48+
defaultValue: 'Ask anything — the assistant has access to your current app context.',
49+
}),
50+
};
51+
}
52+
53+
type TranslationFn = (key: string, options?: Record<string, unknown>) => string;
54+
55+
function dataChatSuggestions(t: TranslationFn): string[] {
56+
return [
57+
t('console.ai.suggestions.dataChat.userCount', { defaultValue: 'How many users are in the system? List their emails.' }),
58+
t('console.ai.suggestions.dataChat.recentRecords', { defaultValue: 'List the 5 most recently created records.' }),
59+
t('console.ai.suggestions.dataChat.recordCounts', { defaultValue: 'Count records for each object.' }),
60+
];
61+
}
62+
63+
function genericSuggestions(t: TranslationFn): string[] {
64+
return [
65+
t('console.ai.suggestions.generic.help', { defaultValue: 'What can you help me with?' }),
66+
t('console.ai.suggestions.generic.availableObjects', { defaultValue: 'List the available data objects.' }),
67+
t('console.ai.suggestions.generic.recentActivity', { defaultValue: 'Summarize my recent activity.' }),
68+
];
69+
}
70+
71+
export function buildAgentSuggestions(
72+
agentName: string | undefined,
73+
agentLabel: string,
74+
t: TranslationFn,
75+
): string[] {
76+
// Alias-aware: `ask`/`data_chat` → data starters. Custom agents fall back to
77+
// a name/label heuristic.
78+
if (isAskAgent(agentName)) return dataChatSuggestions(t);
79+
const lower = (agentName ?? agentLabel).toLowerCase();
80+
if (lower.includes('data')) return dataChatSuggestions(t);
81+
return genericSuggestions(t);
82+
}
Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,131 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* The full-page AI chat's chrome: the collapsible conversations list, its
5+
* keyboard shortcuts, and where "collapse to dock" lands. Split out of
6+
* `AiChatPage.tsx` move-only (objectstack#37730).
7+
*/
8+
9+
import { useCallback, useState } from 'react';
10+
import type { AdvertisedShortcut, ShortcutLabelTranslate } from '../../chrome/advertisedShortcuts.js';
11+
12+
const CHATS_COLLAPSED_STORAGE_KEY = 'ai-chats-collapsed';
13+
14+
export interface CollapsibleChatsList {
15+
/** Whether the desktop conversations list is currently hidden. */
16+
collapsed: boolean;
17+
/** User-driven collapse/expand; persists the preference. */
18+
toggle: () => void;
19+
}
20+
21+
/**
22+
* State for the collapsible desktop conversations list. Exported for tests.
23+
* `toggle()` flips it and PERSISTS the preference (localStorage).
24+
*
25+
* objectstack#34610 — the Live Canvas split that used to tuck the list away
26+
* while a preview was open is gone (the draft is the main area now), so the
27+
* user's toggle is the only driver.
28+
*/
29+
export function useCollapsibleChatsList(): CollapsibleChatsList {
30+
const [collapsed, setCollapsed] = useState<boolean>(() => {
31+
try {
32+
return localStorage.getItem(CHATS_COLLAPSED_STORAGE_KEY) === '1';
33+
} catch {
34+
return false;
35+
}
36+
});
37+
const toggle = useCallback(() => {
38+
setCollapsed((prev) => {
39+
const next = !prev;
40+
try {
41+
localStorage.setItem(CHATS_COLLAPSED_STORAGE_KEY, next ? '1' : '0');
42+
} catch {
43+
/* private mode / disabled storage — preference just won't persist */
44+
}
45+
return next;
46+
});
47+
}, []);
48+
49+
return { collapsed, toggle };
50+
}
51+
52+
export type AiChatShortcut = 'toggle-list' | 'new-chat';
53+
54+
/**
55+
* Match a keydown to an AI-chat shortcut, mirroring ChatGPT/Claude:
56+
* - ⌘/Ctrl+Shift+O → new chat
57+
* - ⌘/Ctrl+Shift+S → toggle the conversations list
58+
*
59+
* Both use the ⌘/Ctrl+Shift modifier so they're safe to fire even while the
60+
* composer is focused (they can't be produced by ordinary typing). Pure +
61+
* exported for tests.
62+
*/
63+
export function matchAiChatShortcut(e: {
64+
key: string;
65+
metaKey: boolean;
66+
ctrlKey: boolean;
67+
shiftKey: boolean;
68+
altKey: boolean;
69+
}): AiChatShortcut | null {
70+
if (!(e.metaKey || e.ctrlKey) || !e.shiftKey || e.altKey) return null;
71+
switch (e.key.toLowerCase()) {
72+
case 'o':
73+
return 'new-chat';
74+
case 's':
75+
return 'toggle-list';
76+
default:
77+
return null;
78+
}
79+
}
80+
81+
/**
82+
* The two {@link matchAiChatShortcut} chords, advertised to the
83+
* keyboard-shortcuts dialog by `AiChatPage` beside the listener that calls it,
84+
* so they are listed only where that page is mounted (objectui#11674).
85+
*/
86+
export const NEW_CHAT_SHORTCUT: AdvertisedShortcut = {
87+
id: 'ai-new-chat',
88+
group: 'aiChat',
89+
chord: { key: 'o', mod: true, shift: true },
90+
label: (t: ShortcutLabelTranslate) => t('console.shortcuts.newChat'),
91+
};
92+
93+
export const TOGGLE_CHATS_LIST_SHORTCUT: AdvertisedShortcut = {
94+
id: 'ai-toggle-chats-list',
95+
group: 'aiChat',
96+
chord: { key: 's', mod: true, shift: true },
97+
label: (t: ShortcutLabelTranslate) => t('console.shortcuts.toggleChatsList'),
98+
};
99+
100+
/**
101+
* ADR-0057 P3c — where the "collapse to dock" affordance navigates, in
102+
* preference order:
103+
*
104+
* 1. The REMEMBERED maximize origin (`storedPath`, written by the dock's own
105+
* maximize handlers at click time) — the exact page the user left, immune
106+
* to in-page history churn (conversation switches push `/ai/...` entries,
107+
* so blind history-back can land on a prior `/ai` URL instead of the
108+
* console).
109+
* 2. History back, when react-router has an in-app entry to return to
110+
* (`window.history.state.idx > 0` — the router stamps a monotonically
111+
* increasing `idx` on entries it creates).
112+
* 3. `homePath` — the page was the entry point (deep link, fresh tab).
113+
*
114+
* `homePath` is a PARAMETER, not a literal, since objectui#7373: home is
115+
* whatever the deployment declared (`useHomePath()` at the call site), and on a
116+
* control plane the environment launcher is the wrong screen to land a customer
117+
* on. Required rather than defaulted, so a new call site cannot silently
118+
* reintroduce the literal this card removed.
119+
*
120+
* The dock itself is armed to open expanded separately
121+
* ({@link armChatDockExpanded}); this only picks the landing. Pure + exported
122+
* for tests.
123+
*/
124+
export function resolveCollapseToDockTarget(
125+
historyIdx: unknown,
126+
storedPath: string | undefined,
127+
homePath: string,
128+
): string | -1 {
129+
if (storedPath) return storedPath;
130+
return typeof historyIdx === 'number' && historyIdx > 0 ? -1 : homePath;
131+
}

0 commit comments

Comments
 (0)