源码快照 @ 2026-09-01 (source-only, 剔除非源码素材)
Dependency audit / audit (push) Canceled after 0s
CI / plan (push) Canceled after 0s
Gitoxide helper admission / macos-latest (push) Canceled after 0s
Gitoxide helper admission / ubuntu-latest (push) Canceled after 0s
Gitoxide helper admission / windows-latest (push) Canceled after 0s
Runtime Host peer admission / quality (push) Canceled after 0s
Windows recovery / windows_recovery (push) Canceled after 0s
CI / heavy (push) Canceled after 0s
CI / test (push) Canceled after 0s

This commit is contained in:
agent-radar committed 2026-09-01 19:05:14 +08:00
commit 7be535059e
3358 files changed
+1306357

No files matched your search

@@ -0,0 +1,152 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import type { Meta, StoryObj } from '@storybook/react-vite';
import { expect, fn, userEvent, waitFor, within } from 'storybook/test';
import { useState } from 'react';
import { createScheduledTaskFormSeed } from '../src/scheduled-task-helpers.js';
import { ScheduledTaskFormDialog } from '../src/scheduled-task-form-dialog.js';
import { Markdown } from '../src/markdown.js';
import { SessionRenameDialog } from '../src/session-rename-dialog.js';
const meta = {
title: 'Product/Accessibility Dialogs',
parameters: { layout: 'fullscreen' },
} satisfies Meta;
export default meta;
type Story = StoryObj<typeof meta>;
const renameConversation = fn();
const closeRenameDialog = fn();
const closeScheduledTaskDialog = fn();
function RenameConversationStory() {
const [open, setOpen] = useState(false);
return (
<>
<button type="button" onClick={() => setOpen(true)}>重命名任务</button>
{open ? (
<SessionRenameDialog
target={{ kind: 'session', id: 'session-story', name: '发布前检查' }}
onOpenChange={(nextOpen) => {
closeRenameDialog(nextOpen);
setOpen(nextOpen);
}}
onRename={renameConversation}
/>
) : null}
</>
);
}
// Real path: conversation sidebar → row actions → rename.
export const RenameConversation: Story = {
render: () => <RenameConversationStory />,
play: async ({ canvasElement }) => {
renameConversation.mockClear();
closeRenameDialog.mockClear();
const body = within(canvasElement.ownerDocument.body);
const trigger = body.getByRole('button', { name: '重命名任务' });
await userEvent.click(trigger);
const field = await body.findByRole('textbox', { name: '重命名任务' });
await expect(field).toHaveFocus();
await userEvent.clear(field);
await userEvent.type(field, '发布前 AX 检查');
await userEvent.click(body.getByRole('button', { name: '保存' }));
await expect(closeRenameDialog).toHaveBeenCalledWith(false);
await expect(renameConversation).toHaveBeenCalledWith(
expect.objectContaining({ id: 'session-story' }),
'发布前 AX 检查',
);
await waitFor(() =>
expect(body.queryByRole('dialog', { name: '重命名任务' })).not.toBeInTheDocument());
await userEvent.click(trigger);
await expect(body.findByRole('dialog', { name: '重命名任务' })).resolves.toBeTruthy();
},
};
function CreateScheduledTaskStory() {
const [open, setOpen] = useState(false);
return (
<>
<button type="button" onClick={() => setOpen(true)}>新建定时任务</button>
<ScheduledTaskFormDialog
open={open}
seed={createScheduledTaskFormSeed()}
tasks={[]}
onOpenChange={(nextOpen) => {
closeScheduledTaskDialog(nextOpen);
setOpen(nextOpen);
}}
onCreate={() => undefined}
/>
</>
);
}
// Real path: sidebar → 定时任务 → 新建定时任务.
export const CreateScheduledTask: Story = {
render: () => <CreateScheduledTaskStory />,
play: async ({ canvasElement }) => {
closeScheduledTaskDialog.mockClear();
const body = within(canvasElement.ownerDocument.body);
const trigger = body.getByRole('button', { name: '新建定时任务' });
await userEvent.click(trigger);
const dialog = await body.findByRole('dialog', { name: '新建定时任务' });
await expect(within(dialog).getByRole('textbox', { name: /标题/ })).toHaveFocus();
await userEvent.click(within(dialog).getByRole('button', { name: '关闭' }));
await expect(closeScheduledTaskDialog).toHaveBeenCalledWith(false);
await waitFor(() =>
expect(body.queryByRole('dialog', { name: '新建定时任务' })).not.toBeInTheDocument());
await expect(trigger).toHaveFocus();
await userEvent.click(trigger);
await expect(body.findByRole('dialog', { name: '新建定时任务' })).resolves.toBeTruthy();
},
};
// Real path: conversation or Daily Review Markdown → Mermaid diagram → 全屏查看图表.
export const MermaidFullscreen: Story = {
render: () => (
<div style={{ margin: '0 auto', maxWidth: 720, padding: 24 }}>
<Markdown
text={[
'```mermaid',
'flowchart LR',
' Observe --> Resolve',
' Resolve --> Act',
' Act --> Verify',
'```',
].join('\n')}
/>
</div>
),
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
const expand = await waitFor(
() => canvas.getByRole('button', { name: '全屏查看图表' }),
{ timeout: 10_000 },
);
await userEvent.click(expand);
await expect(
within(canvasElement.ownerDocument.body).findByRole('dialog', {
name: 'Mermaid 图表',
}),
).resolves.toBeTruthy();
},
};
+260
View File
@@ -0,0 +1,260 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import type { Meta, StoryObj } from '@storybook/react-vite';
import type { ComponentProps } from 'react';
import type { AttachmentRef } from '@maka/core/events';
import type { SessionSummary, StoredMessage } from '@maka/core/session';
import { ChatSurfaceLayout, ChatView, Composer } from '../src/components.js';
import type { ChatModelChoice } from '../src/chat-model-helpers.js';
const NOW = Date.UTC(2026, 6, 1, 9, 30, 0);
// 64x64 solid-color PNGs so the thumbnail/lightbox actually show an image
// (the story feeds them through the injected `onReadAttachmentBytes` reader below).
const RED_PNG =
'iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAIAAADTED8xAAACv0lEQVR4nO3TMQ0AMAzAsELcPcSDNRg9YskA8mTeuZA16wWwyACkGYA0A5BmANIMQJoBSDMAaQYgzQCkGYA0A5BmANIMQJoBSDMAaQYgzQCkGYA0A5BmANIMQJoBSDMAaQYgzQCkGYA0A5BmANIMQJoBSDMAaQYgzQCkGYA0A5BmANIMQJoBSDMAaQYgzQCkGYA0A5BmANIMQJoBSDMAaQYgzQCkGYA0A5BmANIMQJoBSDMAaQYgzQCkGYA0A5BmANIMQJoBSDMAaQYgzQCkGYA0A5BmANIMQJoBSDMAaQYgzQCkGYA0A5BmANIMQJoBSDMAaQYgzQCkGYA0A5BmANIMQJoBSDMAaQYgzQCkGYA0A5BmANIMQJoBSDMAaQYgzQCkGYA0A5BmANIMQJoBSDMAaQYgzQCkGYA0A5BmANIMQJoBSDMAaQYgzQCkGYA0A5BmANIMQJoBSDMAaQYgzQCkGYA0A5BmANIMQJoBSDMAaQYgzQCkGYA0A5BmANIMQJoBSDMAaQYgzQCkGYA0A5BmANIMQJoBSDMAaQYgzQCkGYA0A5BmANIMQJoBSDMAaQYgzQCkGYA0A5BmANIMQJoBSDMAaQYgzQCkGYA0A5BmANIMQJoBSDMAaQYgzQCkGYA0A5BmANIMQJoBSDMAaQYgzQCkGYA0A5BmANIMQJoBSDMAaQYgzQCkGYA0A5BmANIMQJoBSDMAaQYgzQCkGYA0A5BmANIMQJoBSPvHHhWvMw1VrQAAAABJRU5ErkJggg==';
const BLUE_PNG =
'iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAIAAADTED8xAAACwElEQVR4nO3TMQ0AMAzAsEIckuEcrMHoEUsGkCdz7oOsWS+ARQYgzQCkGYA0A5BmANIMQJoBSDMAaQYgzQCkGYA0A5BmANIMQJoBSDMAaQYgzQCkGYA0A5BmANIMQJoBSDMAaQYgzQCkGYA0A5BmANIMQJoBSDMAaQYgzQCkGYA0A5BmANIMQJoBSDMAaQYgzQCkGYA0A5BmANIMQJoBSDMAaQYgzQCkGYA0A5BmANIMQJoBSDMAaQYgzQCkGYA0A5BmANIMQJoBSDMAaQYgzQCkGYA0A5BmANIMQJoBSDMAaQYgzQCkGYA0A5BmANIMQJoBSDMAaQYgzQCkGYA0A5BmANIMQJoBSDMAaQYgzQCkGYA0A5BmANIMQJoBSDMAaQYgzQCkGYA0A5BmANIMQJoBSDMAaQYgzQCkGYA0A5BmANIMQJoBSDMAaQYgzQCkGYA0A5BmANIMQJoBSDMAaQYgzQCkGYA0A5BmANIMQJoBSDMAaQYgzQCkGYA0A5BmANIMQJoBSDMAaQYgzQCkGYA0A5BmANIMQJoBSDMAaQYgzQCkGYA0A5BmANIMQJoBSDMAaQYgzQCkGYA0A5BmANIMQJoBSDMAaQYgzQCkGYA0A5BmANIMQJoBSDMAaQYgzQCkGYA0A5BmANIMQJoBSDMAaQYgzQCkGYA0A5BmANIMQJoBSDMAaQYgzQCkGYA0A5BmANIMQJoBSDMAaQYgzQCkGYA0A5BmANIMQJoBSDMAaQYgzQCkGYA0A5BmANIMQJoBSDMAaQYgzQCkGYA0A5BmANIMQJoBSDMAaQYgzQCkGYA0A5BmANIMQJoBSDMAaQYgzQCkGYA0A5BmANIMQJoBSDMAaQYgzQCkGYA0A5BmANIMQJoBSDMAaQYgzQCkGYA0A5BmANIMQNoHahEW2x9npg0AAAAASUVORK5CYII=';
// @maka/ui is host-agnostic: image thumbnails read bytes through the injected
// `onReadAttachmentBytes` prop, not a host global. The story supplies a fake
// reader that echoes the two solid-color PNGs above.
const mockReadBytes = async (_sessionId: string, artifactId: string) => ({
ok: true as const,
base64: artifactId.includes('metrics') ? BLUE_PNG : RED_PNG,
mimeType: 'image/png',
});
// Fidelity convention (#1433): every story below names the real app path
// that reaches it. See apps/desktop/stories/FIDELITY.md.
const meta = {
title: 'Product/Attachments',
parameters: { layout: 'fullscreen' },
} satisfies Meta;
export default meta;
type Story = StoryObj<typeof meta>;
type ComposerProps = ComponentProps<typeof Composer>;
type ChatViewProps = ComponentProps<typeof ChatView>;
const modelChoices: ChatModelChoice[] = [
{ connectionId: 'connection-anthropic-main', connectionSlug: 'anthropic-main', providerType: 'anthropic', providerLabel: 'Anthropic', model: 'claude-sonnet-4-5', label: 'Claude Sonnet 4.5', isDefault: true, thinkingLevels: [] },
];
function noop() {
return undefined;
}
function session(o: Partial<SessionSummary> = {}): SessionSummary {
return {
id: 's',
name: '附件展示',
isFlagged: false,
isArchived: false,
labels: [],
hasUnread: false,
lastMessageAt: NOW,
lastMessagePreview: '帮我看下这几个文件。',
status: 'active',
backend: 'ai-sdk',
llmConnectionId: 'connection-anthropic-main',
llmConnectionSlug: 'anthropic-main',
connectionLocked: false,
model: 'claude-sonnet-4-5',
permissionMode: 'ask',
...o,
};
}
function attachment(kind: AttachmentRef['kind'], name: string, mimeType: string, bytes = 1024): AttachmentRef {
return { kind, name, mimeType, bytes, ref: { kind: 'session_file', sessionId: 's', relativePath: name } };
}
const imageAttachment = attachment('image', 'dashboard.png', 'image/png', 480_000);
const metricsAttachment = attachment('image', 'metrics.png', 'image/png', 920_000);
const pdfAttachment = attachment('pdf', 'design-spec.pdf', 'application/pdf', 512_000);
const docAttachment = attachment('doc', '周报.docx', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 128_000);
const codeAttachment = attachment('code', 'handler.ts', 'text/typescript', 4_096);
const otherAttachment = attachment('other', 'archive.zip', 'application/zip', 88_000);
const baseComposer: ComposerProps = {
draftKey: 'storybook-attachments',
onSend: noop,
onStop: noop,
modelLabel: 'Claude Sonnet 4.5',
activeSession: session(),
activeModel: 'claude-sonnet-4-5',
activeModelLabel: 'Claude Sonnet 4.5',
modelChoices,
permissionMode: 'ask',
onPermissionModeChange: noop,
onPickAttachments: noop,
onAttachFilePaths: noop,
};
const baseChat: ChatViewProps = {
messages: [],
scrollBehavior: 'smooth',
activeSession: session(),
activeConnectionLabel: 'Anthropic',
activeModel: 'claude-sonnet-4-5',
activeModelLabel: 'Claude Sonnet 4.5',
modelChoices,
userLabel: '你',
onReadAttachmentBytes: mockReadBytes,
onNew: noop,
onPromptSuggestion: noop,
};
function user(id: string, turnId: string, text: string, attachments: AttachmentRef[]): StoredMessage {
return { type: 'user', id, turnId, ts: NOW, text, attachments };
}
function Frame({ children, width = 960 }: { children: React.ReactNode; width?: number }) {
return (
<div
style={{
width,
maxWidth: 'calc(100vw - 48px)',
margin: '0 auto',
background: 'var(--background)',
display: 'flex',
minHeight: 360,
}}
>
{children}
</div>
);
}
function AttachmentChat(props: ComponentProps<typeof ChatView>) {
return (
<ChatSurfaceLayout composer={null}>
<ChatView {...props} />
</ChatSurfaceLayout>
);
}
// Real path: composer → + → attach files → the pending chips before the message is sent.
export const ComposerPendingChips: Story = {
render: () => (
<Frame>
<div style={{ padding: '0 24px 24px', width: '100%' }}>
<Composer
{...baseComposer}
draftKey="composer-pending-chips"
pendingAttachments={[
{ displayName: 'chart.png', kind: 'image', mimeType: 'image/png', size: 480_000 },
{ displayName: 'design-spec.pdf', kind: 'pdf', mimeType: 'application/pdf', size: 512_000 },
{ displayName: 'handler.ts', kind: 'code', mimeType: 'text/typescript', size: 4_096 },
{ displayName: 'archive.zip', kind: 'other', mimeType: 'application/zip', size: 88_000 },
]}
onRemoveAttachment={noop}
/>
</div>
</Frame>
),
};
// Real path: send a message with attachments → the chips as they render inside the sent
// turn.
export const ChatAttachmentChips: Story = {
render: () => (
<Frame>
<AttachmentChat
{...baseChat}
messages={[user('u1', 't1', '帮我看下这几个文件,哪些要改。', [pdfAttachment, docAttachment, codeAttachment, otherAttachment])]}
/>
</Frame>
),
};
// Real path: attach images → their thumbnails in the sent turn.
export const ImageThumbnails: Story = {
render: () => (
<Frame>
<AttachmentChat
{...baseChat}
messages={[user('u2', 't2', '这两张截图帮我对比一下。', [imageAttachment, metricsAttachment])]}
/>
</Frame>
),
};
// Real path: the assistant cites a Session attachment ref in Markdown → the
// chat's session-scoped reader resolves it through the same image authority as
// the sent-message thumbnail above.
export const AssistantMarkdownImage: Story = {
render: () => (
<Frame>
<AttachmentChat
{...baseChat}
messages={[
user('u-markdown', 't-markdown', '把这张图显示在回答里。', []),
{
type: 'assistant',
id: 'a-markdown',
turnId: 't-markdown',
ts: NOW + 1,
text: '会话附件预览:\n\n![dashboard](maka://runtime/attachments/attachment-dashboard)',
modelId: 'claude-sonnet-4-5',
},
]}
/>
</Frame>
),
};
// Real path: send one prompt with every durable reference kind → file tokens sit
// above the bubble, while inline Skill/file tokens, quote and image keep their own hierarchy.
// The narrow frame verifies wrapping without inventing a second product layout.
export const SentReferenceHierarchy: Story = {
render: () => (
<Frame width={420}>
<AttachmentChat
{...baseChat}
messages={[{
type: 'user',
id: 'u3',
turnId: 't3',
ts: NOW,
text: '请用 /skill:writer 对照 @packages/ui/src/chat-turn.tsx 检查这些材料。',
inlineReferences: [
{ kind: 'skill', value: '/skill:writer', label: 'writer', start: 3 },
{
kind: 'workspace_file',
value: '@packages/ui/src/chat-turn.tsx',
label: 'chat-turn.tsx',
start: 20,
},
],
attachments: [pdfAttachment, codeAttachment, imageAttachment],
quotes: [{
text: 'Inline references preserve the exact Composer token after send and reload.',
label: 'Architecture note',
sourceTurnId: 't2',
}],
}]}
/>
</Frame>
),
};
@@ -0,0 +1,133 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import type { Meta, StoryObj } from '@storybook/react-vite';
import type { CapabilityAuditReport } from '@maka/core/capability-audit';
import { CapabilityAuditStrip } from '../src/capability-audit-strip.js';
// Fidelity convention (#1433): every story below names the real app path
// that reaches it. See apps/desktop/stories/FIDELITY.md.
//
// This file had four stories and three of them rendered nothing. The strip
// reports by exception — `capabilityAuditIssues` returns [] and the component
// returns null unless a source needs auth or is erroring, or a scheduled task
// failed or was skipped — and `report()` defaults all four of those counts to
// 0. So the former healthy-focus and empty stories were blank
// panels carrying confident "Real path:" sentences that described behavior the
// component lost when it stopped summarizing healthy state. The app state they
// named is "this strip is not on the page", which needs no story.
const meta = {
title: 'Product/Capability Audit Strip',
parameters: {
layout: 'fullscreen',
},
} satisfies Meta;
export default meta;
type Story = StoryObj<typeof meta>;
const NOW = Date.now();
function report(input: Partial<CapabilityAuditReport['summary']>): CapabilityAuditReport {
return {
checkedAt: NOW,
sources: [],
skills: [],
scheduledTasks: [],
summary: {
sourceCount: 0,
readySourceCount: 0,
needsAuthSourceCount: 0,
errorSourceCount: 0,
disabledSourceCount: 0,
skillCount: 0,
enabledSkillCount: 0,
skillsWithDeclaredTools: 0,
declaredToolKindCount: 0,
scheduledTaskCount: 0,
enabledScheduledTaskCount: 0,
activeScheduledTaskCount: 0,
failedScheduledTaskCount: 0,
skippedScheduledTaskCount: 0,
...input,
},
};
}
/**
* The skills page's frame: the wrapper the strip renders inside on the real
* page (skills-panel.tsx) — `.maka-module-page-panel`, a padded grid block
* in the module page's single scrolling content column. The previous frame
* here exercised a `.maka-module-main` grid row assignment and its
* `:has(> .maka-capability-audit-strip)` third-row rule; both were deleted
* when the module pages moved onto the Astryx Layout shell (#2236), where
* the strip is ordinary content, not a grid row.
*
* What this frame does not reproduce: the 900px centred column, which is
* Astryx LayoutContent's own box. Width measurements taken here do not
* transfer to the app; the strip's internal rhythm does. The scheduled-task
* page mounts the same component inside `.maka-module-page-body` — a
* different padded block in the same kind of column — and the same caveat
* applies there.
*/
function ModulePage(props: { children: React.ReactNode }) {
return (
<section
className="maka-main detailPane maka-module-main agents-chat-panel"
data-page-shell="layout"
aria-label="Capability audit module content"
>
<div className="maka-module-page-panel">{props.children}</div>
</section>
);
}
// Real path: sidebar → 扩展 → 技能, once something needs attention — a managed
// skill source waiting for auth or erroring, a scheduled task whose last run failed
// or was skipped. The strip renders exactly one warning line naming what is
// wrong. With all four of those counts at zero it returns null and the page
// carries no strip, so that state has no story: it has no pixels.
//
// 定时任务 → 定时任务 reaches the same component in a different frame; see
// ModulePage above for what that changes and why it is not a second story.
export const WithRisks: Story = {
render: () => (
<ModulePage>
<CapabilityAuditStrip
report={report({
sourceCount: 4,
readySourceCount: 2,
needsAuthSourceCount: 1,
errorSourceCount: 1,
skillCount: 10,
enabledSkillCount: 7,
skillsWithDeclaredTools: 6,
declaredToolKindCount: 5,
scheduledTaskCount: 6,
enabledScheduledTaskCount: 5,
activeScheduledTaskCount: 4,
failedScheduledTaskCount: 1,
skippedScheduledTaskCount: 1,
})}
/>
</ModulePage>
),
};
@@ -0,0 +1,119 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import type { Meta, StoryObj } from '@storybook/react-vite';
import type { SessionSummary } from '@maka/core/session';
import { userEvent } from 'storybook/test';
import { SessionRail, type SessionRailStoryProps } from './session-rail-harness.js';
// Compares the resting, hover and focus states of two DIFFERENT row components
// — Astryx's side-nav item and its list item — as the sidebar composes them.
// That cross-component seam is why this sits here rather than in
// session-list-panel.stories.tsx, which owns SessionListPanel's own states.
//
// The Astryx Button state matrices that used to share this file were deleted:
// Astryx owns Button and publishes its states upstream.
const meta = {
title: 'Design System/Composite Row States',
parameters: { layout: 'padded' },
} satisfies Meta;
export default meta;
type Story = StoryObj<typeof meta>;
const noop = () => undefined;
const COMPOSITE_ROW_SESSIONS: SessionSummary[] = [
{
id: 'interaction-active',
name: '整理中文 compact controls',
isFlagged: false,
isArchived: false,
labels: [],
hasUnread: false,
status: 'active',
backend: 'fake',
llmConnectionSlug: 'fixture',
connectionLocked: false,
model: 'fixture-model',
permissionMode: 'ask',
},
{
id: 'interaction-default',
name: 'Review English interaction states',
isFlagged: false,
isArchived: false,
labels: [],
hasUnread: true,
status: 'active',
backend: 'fake',
llmConnectionSlug: 'fixture',
connectionLocked: false,
model: 'fixture-model',
permissionMode: 'ask',
},
];
function StoryFrame(props: { children: React.ReactNode; description: string; title: string }) {
return (
<section style={{ display: 'grid', gap: 16, maxWidth: 900 }}>
<div>
<h2 style={{ fontSize: 16, margin: 0 }}>{props.title}</h2>
<p style={{ color: 'var(--foreground-secondary)', fontSize: 12, margin: '4px 0 0' }}>
{props.description}
</p>
</div>
{props.children}
</section>
);
}
export const ListRowStates: Story = {
render: () => (
<StoryFrame
title="复合行 / Composite rows"
description="真实侧栏导航与会话行保留自己的布局、选中态和 focus-within seam。"
>
<div style={{ height: 440, overflow: 'hidden', width: 260 }}>
<SessionRail
selection={{ section: 'extensions', module: 'skills' }}
sessions={COMPOSITE_ROW_SESSIONS}
activeId="interaction-active"
onSelectSession={noop}
onSelect={noop}
onOpenSettings={noop}
onNew={noop}
/>
</div>
</StoryFrame>
),
play: async ({ canvasElement }) => {
const hoverTarget = canvasElement.querySelector<HTMLButtonElement>('.astryx-side-nav-item');
hoverTarget?.setAttribute('data-state-target', 'hover');
const focusTarget = canvasElement.querySelector<HTMLButtonElement>('[data-maka-contract="session-row"] [aria-current="true"]');
focusTarget?.setAttribute('data-state-target', 'focus');
const tabStops = Array.from(canvasElement.querySelectorAll<HTMLButtonElement>('button:not([disabled])'));
const focusIndex = focusTarget ? tabStops.indexOf(focusTarget) : -1;
if (focusIndex > 0) {
tabStops[focusIndex - 1]?.focus();
await userEvent.tab();
}
},
};
@@ -0,0 +1,64 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import type { Meta, StoryObj } from '@storybook/react-vite';
import { Spinner } from '@astryxdesign/core/Spinner';
// The two functional animations the product keeps: a spinner and the streaming
// shimmer. Both are load-bearing rather than decorative, so they outlive the
// motion-token rename — unlike the duration/easing scales that used to sit here
// and catalogued Maka's parallel motion vocabulary as if it were the contract.
const meta = {
title: 'Design System/Functional Motion',
parameters: { layout: 'centered' },
} satisfies Meta;
export default meta;
type Story = StoryObj<typeof meta>;
export const RetainedFunctionalMotion: Story = {
render: () => (
<div style={{ alignItems: 'end', display: 'grid', gap: 24, gridTemplateColumns: 'repeat(2, minmax(96px, 1fr))' }}>
{/* This story is the keyframe's only consumer since the product's
`.maka-shimmer` recipe died (#1980), so the keyframe lives here
rather than in maka-tokens.css. */}
<style>{'@keyframes maka-shimmer { 0% { background-position: -200% 0; } 100% { background-position: 200% 0; } }'}</style>
<div style={{ alignItems: 'center', display: 'grid', gap: 8, justifyItems: 'center' }}>
<Spinner style={{ height: 20, width: 20 }} />
<span style={{ color: 'var(--foreground-secondary)', fontSize: 12, fontWeight: 600 }}>Spinner</span>
</div>
<div style={{ alignItems: 'center', display: 'grid', gap: 8, justifyItems: 'center' }}>
<span
aria-hidden="true"
style={{
animation: 'maka-shimmer 1.8s var(--ease-linear) infinite',
background:
'linear-gradient(120deg, transparent 40%, oklch(from var(--foreground) l c h / 0.16), transparent 60%) var(--foreground-5) 0 0 / 200% 100%',
borderRadius: 'var(--radius-surface)',
display: 'inline-block',
height: 20,
width: 96,
}}
/>
<span style={{ color: 'var(--foreground-secondary)', fontSize: 12, fontWeight: 600 }}>Shimmer</span>
</div>
</div>
),
};
+128
View File
@@ -0,0 +1,128 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import type { Meta, StoryObj } from '@storybook/react-vite';
import type { ElementType } from 'react';
import * as Icons from '../src/icons.js';
import { BOT_BRAND, BotBrandLogo } from '../src/index.js';
const meta = {
title: 'Design System/Icons',
parameters: { layout: 'padded' },
} satisfies Meta;
export default meta;
type Story = StoryObj<typeof meta>;
interface IconEntry {
name: string;
Comp: ElementType<{ size?: number | string; strokeWidth?: number | string; 'aria-hidden'?: boolean }>;
}
// The icon seam also exports shared metadata such as ICON_SIZE. Keep the story
// self-updating without assuming every runtime export can be rendered.
function isIconComponent(value: unknown): value is IconEntry['Comp'] {
return (
typeof value === 'function' ||
(typeof value === 'object' &&
value !== null &&
'render' in value &&
typeof value.render === 'function')
);
}
const LUCIDE_ICONS: IconEntry[] = Object.entries(Icons)
.flatMap(([name, value]) => (isIconComponent(value) ? [{ name, Comp: value }] : []))
.sort((a, b) => a.name.localeCompare(b.name));
// Derived from BOT_BRAND, the registry BotBrandLogo itself reads. A hand-kept
// list here is satisfied by any subset, so a newly supported channel would
// silently never render.
const BOT_BRAND_PROVIDERS = Object.keys(BOT_BRAND) as Array<keyof typeof BOT_BRAND>;
export const LucideIcons: Story = {
render: () => (
<section style={{ display: 'grid', gap: 20, maxWidth: 920 }}>
<div style={{ display: 'grid', gap: 4 }}>
<h2 style={{ fontSize: 16, fontWeight: 600, margin: 0 }}>Lucide Icons</h2>
<p style={{ color: 'var(--foreground-secondary)', fontSize: 12, margin: 0, lineHeight: 1.5 }}>
{LUCIDE_ICONS.length} 个通用 UI 图标,通过 icons.tsx 的 lucide-react re-export 自动追踪。业务代码仍只从 @maka/ui/icons 取图标。
</p>
</div>
<div
style={{
display: 'grid',
gap: 8,
gridTemplateColumns: 'repeat(auto-fill, minmax(120px, 1fr))',
}}
>
{LUCIDE_ICONS.map(({ name, Comp }) => (
<div
key={name}
style={{
display: 'grid',
gap: 6,
padding: 10,
borderRadius: 'var(--radius-surface)',
boxShadow: 'var(--ring-soft)',
placeItems: 'center',
textAlign: 'center',
}}
>
<Comp size={20} />
<code style={{ color: 'var(--foreground-secondary)', fontSize: 10, wordBreak: 'break-word' }}>{name}</code>
</div>
))}
</div>
</section>
),
};
export const BotBrandIcons: Story = {
render: () => (
<section style={{ display: 'grid', gap: 20, maxWidth: 760 }}>
<div style={{ display: 'grid', gap: 4 }}>
<h2 style={{ fontSize: 16, fontWeight: 600, margin: 0 }}>Bot Brand Icons</h2>
<p style={{ color: 'var(--foreground-secondary)', fontSize: 12, margin: 0, lineHeight: 1.5 }}>
{BOT_BRAND_PROVIDERS.length} 个 IM 渠道品牌图标,本地 React SVG,零运行时 CDN 依赖。
</p>
</div>
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 12 }}>
{BOT_BRAND_PROVIDERS.map((provider) => (
<div
key={provider}
style={{
display: 'grid',
gap: 6,
padding: 12,
borderRadius: 'var(--radius-surface)',
boxShadow: 'var(--ring-soft)',
placeItems: 'center',
textAlign: 'center',
}}
>
<BotBrandLogo provider={provider} width={32} height={32} />
<code style={{ color: 'var(--foreground-secondary)', fontSize: 10 }}>{provider}</code>
</div>
))}
</div>
</section>
),
};
+220
View File
@@ -0,0 +1,220 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import type { Meta, StoryObj } from '@storybook/react-vite';
import { ChatMessageBubble } from '@astryxdesign/core';
import { Markdown } from '../src/markdown.js';
// Fidelity convention (#1433): every story below names the real app path
// that reaches it. See apps/desktop/stories/FIDELITY.md.
const meta = {
title: 'Product/Markdown',
parameters: {
layout: 'fullscreen',
},
} satisfies Meta;
export default meta;
type Story = StoryObj<typeof meta>;
function ProseFrame(props: { children: React.ReactNode; width?: number }) {
return (
<div
data-maka-e2e-fixture="true"
style={{
background: 'var(--surface-canvas)',
padding: 24,
}}
>
<div style={{ margin: '0 auto', maxWidth: props.width ?? 720, width: '100%' }}>
{props.children}
</div>
</div>
);
}
// The two stories above render markdown at document density, which is the Daily
// Review's mode — not the transcript's. The transcript passes
// `density="compact"` (chat-turn.tsx), a different block rhythm AND a different
// heading scale, so neither story showed what a chat turn actually looks like.
// This one does.
//
// The frame is written out rather than imported: the real host is `ChatTurn`,
// which needs a full TurnViewModel and a runtime to build one. What is
// reproduced here is the part that reaches markdown — the `.maka-turn` wrapper
// and the assistant bubble. Nothing in the markdown rhythm keys on `.maka-turn`
// any more (it keys on Astryx's `data-density`), so the wrapper is here for
// frame fidelity, not to make the styles apply.
//
// Real path: chat → any assistant turn whose reply uses nested headings and a
// list — i.e. the ordinary long answer, rendered as the transcript renders it.
export const TranscriptTurn: Story = {
render: () => (
<ProseFrame>
<div className="maka-turn">
<ChatMessageBubble variant="ghost" width="100%" className="maka-chat-message-bubble maka-chat-message-bubble-assistant">
<Markdown
density="compact"
text={[
'## 改动思路',
'',
'这次把会话列表收敛成置顶和最近两段,状态只保留在行图标上。好处是**所有会话都遵循同一条时间排序规则**。',
'',
'### 具体做法',
'',
'主要做了三件事:',
'',
'1. 置顶会话固定在最上方;',
'2. 其余会话按最近活动时间排序;',
'3. 运行中、等待和阻塞等状态只显示为低干扰行图标。',
'',
'#### 边界情况',
'',
'按项目视图仍然保留项目折叠,扁平化只作用于按时间视图。',
'',
'> 注意:新增状态只需补一个行图标。',
'',
'如果后续要加新状态,只需补充对应的行图标,不再扩张侧栏信息架构。',
].join('\n')}
/>
</ChatMessageBubble>
</div>
</ProseFrame>
),
};
// Real path: chat → an assistant turn containing source code. The wide frame
// keeps the desktop chat measure, rather than the Storybook viewport, as the
// visible limit so code-line regressions are easy to compare.
export const TranscriptCodeBlock: Story = {
render: () => (
<ProseFrame width={1040}>
<div className="maka-turn">
<ChatMessageBubble variant="ghost" width="100%" className="maka-chat-message-bubble maka-chat-message-bubble-assistant">
<Markdown
density="compact"
text={[
'## Runtime connection',
'',
'The desktop keeps the full request readable without wrapping source code into short visual fragments.',
'',
'```ts',
'const connection = await runtimeHost.connect({ workspaceRoot, expectedRootId, initialConnectionTimeoutMs: 45_000 });',
'await connection.send({ type: \'session.message\', sessionId, content, attachments });',
'```',
].join('\n')}
/>
</ChatMessageBubble>
</div>
</ProseFrame>
),
};
// Real path: 每日回顾 → a generated report that mixes headings, emphasis, a list,
// a quote and a table. This is the document density — the Daily Review panel is
// the caller that leaves `density` unset. (It was annotated as a chat answer,
// but chat passes `density="compact"`; see TranscriptTurn above.)
export const RichAssistantAnswer: Story = {
render: () => (
<ProseFrame>
<ChatMessageBubble variant="ghost" width="100%" className="maka-chat-message-bubble maka-chat-message-bubble-assistant">
<Markdown
text={[
'## 改动思路',
'',
'这次把会话列表收敛成置顶和最近两段,状态只保留在行图标上。好处是**所有会话都遵循同一条时间排序规则**,不会因为生命周期变化突然跳到别的分组。',
'',
'主要做了三件事:',
'',
'1. 置顶会话固定在最上方;',
'2. 其余会话按最近活动时间排序;',
'3. 运行中、等待和阻塞等状态只显示为低干扰行图标。',
'',
'> 注意:按项目视图仍然保留项目折叠,扁平化只作用于按时间视图。',
'',
'| 行状态 | 视觉标识 | 是否改变分组 |',
'| --- | --- | --- |',
'| running | 旋转图标 | 否 |',
'| waiting_for_user | 等待图标 | 否 |',
'| blocked | 警示图标 | 否 |',
'| active | 无图标 | 否 |',
'',
'如果后续要加新状态,只需补充对应的行图标,不再扩张侧栏信息架构。',
].join('\n')}
/>
</ChatMessageBubble>
</ProseFrame>
),
};
// Real path: 每日回顾 → a long generated report, pinned at the 680px prose measure
// to check vertical rhythm across many blocks at document density.
export const LongFormArticle: Story = {
render: () => (
<ProseFrame width={680}>
<ChatMessageBubble variant="ghost" width="100%" className="maka-chat-message-bubble maka-chat-message-bubble-assistant">
<Markdown
text={[
'# Storybook 表面覆盖:为什么单独可看很重要',
'',
'当一次改动同时影响多个状态时,靠手动把桌面 app 驱动到每条路径太慢,也容易漏。把每个可见状态固定成 Storybook 的一帧,reviewer 可以逐个点开核对,回归截图也能自动比对。',
'',
'## 范围',
'',
'这次补的主要是高频但此前没有 story 的页面:',
'',
'- 权限弹窗(8 种 reason + 3 种 health)',
'- 顶层布局(侧栏 + 主区 + overlay 堆叠)',
'- 首次启动引导',
'',
'## 非目标',
'',
'`AppShell` 这个集成根不在 Storybook 里整体挂载。它深度依赖桌面 preload 的 IPC,整体挂载需要造一整套 mock,维护成本高、容易脆。改为用真实的子组件拼出布局,能稳定反映页面长什么样。',
'',
'| 页面 | 方式 | 原因 |',
'| --- | --- | --- |',
'| 权限弹窗 | 直接挂载 | 叶子组件,props 驱动 |',
'| 顶层布局 | 组合子组件 | 避开 IPC 耦合 |',
'| 设置各页 | 桥接 mock | 已有 `ConnectionsBridge` 模式 |',
'',
'## 验证',
'',
'写完后跑一次 `npm run build-storybook`,确认所有 story 编译通过;再视情况补回归截图。',
'',
'### 截图基线怎么补',
'',
'新 story 落地后跑一遍采集脚本,把首轮产物当作基线入库。',
'',
'#### 已知噪声',
'',
'字体渲染在不同 GPU 下有亚像素差异,比对时用容差阈值。',
'',
// hr; `***` instead of triple-dash so the storybook-baseline token
// scan doesn't read the quoted literal as a custom-property token.
'***',
'',
'以上是全部范围;有疑问先在 issue 里讨论再动手。',
].join('\n')}
/>
</ChatMessageBubble>
</ProseFrame>
),
};
@@ -0,0 +1,514 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { useState } from 'react';
import type { Meta, StoryObj } from '@storybook/react-vite';
import { expect, userEvent, within } from 'storybook/test';
import type { ProviderType } from '@maka/core/llm-connections';
import type { ThinkingLevel } from '@maka/core/model-thinking';
import type { SessionSummary } from '@maka/core/session';
import { ChatModelSwitcher, ModelChipStatic, NewChatModelPicker, ThinkingLevelSelector } from '../src/chat-model-switcher.js';
import {
exactModelChoiceValue,
modelChoiceValue,
modelMenuGroups,
type ChatModelChoice,
} from '../src/chat-model-helpers.js';
import { ModelPicker } from '../src/model-picker.js';
import { getConversationCopy } from '../src/conversation-copy.js';
import { useUiLocale } from '../src/locale-context.js';
// Fidelity convention (#1433): every story below names the real app path
// that reaches it. See apps/desktop/stories/FIDELITY.md.
const meta = {
title: 'Product/Model Picker',
parameters: { layout: 'padded' },
} satisfies Meta;
export default meta;
type Story = StoryObj<typeof meta>;
function choice(
connectionSlug: string,
providerType: ChatModelChoice['providerType'],
providerLabel: string,
model: string,
label: string,
): ChatModelChoice {
return { connectionId: `connection-${connectionSlug}`, connectionSlug, providerType, providerLabel, model, label, isDefault: false, thinkingLevels: [] };
}
const CHOICES: ChatModelChoice[] = [
choice('openai-main', 'openai', 'OpenAI', 'gpt-5', 'GPT-5'),
choice('openai-main', 'openai', 'OpenAI', 'gpt-5-mini', 'GPT-5 mini'),
choice('openai-main', 'openai', 'OpenAI', 'o3', 'o3'),
choice('anthropic-team', 'anthropic', 'Anthropic', 'claude-opus-4-1', 'Claude Opus 4.1'),
choice('anthropic-team', 'anthropic', 'Anthropic', 'claude-sonnet-4', 'Claude Sonnet 4'),
choice('google-lab', 'google', 'Google Gemini', 'gemini-3-pro', 'Gemini 3 Pro'),
choice('openrouter', 'openai-compatible', 'Custom relay', 'vendor/a-very-long-model-name-with-reasoning-and-tools-preview', 'A very long model name with reasoning and tools preview'),
];
// Canonical user-facing ladder when a model offers the common set.
const THINKING_LEVELS: ThinkingLevel[] = ['off', 'low', 'medium', 'high', 'xhigh'];
// A workspace with far more connections than any reference screen probes. Two
// OpenAI keys share a provider, so `modelMenuGroups` disambiguates their
// headings with the connection slug.
const MANY_CHOICES: ChatModelChoice[] = (
[
{ slug: 'openai-main', type: 'openai', label: 'OpenAI', models: ['gpt-5', 'gpt-5-mini', 'gpt-5-nano', 'o3', 'o4-mini', 'gpt-4.1'] },
{ slug: 'openai-alt', type: 'openai', label: 'OpenAI', models: ['gpt-5', 'o3'] },
{ slug: 'anthropic-team', type: 'anthropic', label: 'Anthropic', models: ['claude-opus-4-1', 'claude-sonnet-4', 'claude-haiku-4-5'] },
{ slug: 'google-lab', type: 'google', label: 'Google Gemini', models: ['gemini-3-pro', 'gemini-3-flash'] },
{ slug: 'deepseek-main', type: 'deepseek', label: 'DeepSeek', models: ['deepseek-chat', 'deepseek-reasoner'] },
{ slug: 'moonshot-main', type: 'moonshot', label: 'Moonshot', models: ['kimi-k2-0711', 'kimi-k1-8k'] },
{ slug: 'relay', type: 'openai-compatible', label: 'Custom relay', models: ['vendor/alpha', 'vendor/beta', 'vendor/gamma'] },
] satisfies Array<{ slug: string; type: ProviderType; label: string; models: string[] }>
).flatMap((group) => group.models.map((model) => choice(group.slug, group.type, group.label, model, model)));
// A relay whose connection name, model ids, and descriptions all overflow the
// trigger and option widths — the "very long text" state truncation must honour.
const LONG_MODEL_LABEL =
'A very long model name that keeps going well past any reasonable trigger width so wrapping and truncation get exercised';
const LONG_CHOICES: ChatModelChoice[] = [
{
connectionId: 'connection-relay-verbose',
connectionSlug: 'relay-verbose',
providerType: 'openai-compatible',
providerLabel: 'Custom relay',
connectionName: 'My self-hosted relay with an unusually descriptive connection name that also overflows',
model: 'vendor/a-very-long-model-identifier-with-reasoning-tools-and-a-2026-preview-suffix',
label: LONG_MODEL_LABEL,
description:
'A deliberately verbose description that runs onto several lines so the option body’s overflow handling stays legible instead of pushing the menu wider.',
knowledgeCutoff: '2026-01',
isDefault: false,
thinkingLevels: [],
},
{
connectionId: 'connection-relay-verbose',
connectionSlug: 'relay-verbose',
providerType: 'openai-compatible',
providerLabel: 'Custom relay',
connectionName: 'My self-hosted relay with an unusually descriptive connection name that also overflows',
model: 'vendor/second-extremely-long-model-identifier-preview-with-an-extended-context-window',
label: 'Another exhaustively named preview model with an extended context window and a trailing note',
isDefault: false,
thinkingLevels: [],
},
];
function providerMark(type: ProviderType) {
const labels: Partial<Record<ProviderType, string>> = {
openai: 'O',
anthropic: 'A',
google: 'G',
'openai-compatible': 'R',
};
return <span style={{ fontSize: 11, fontWeight: 700 }}>{labels[type] ?? 'M'}</span>;
}
function choiceValue(choice: ChatModelChoice) {
return exactModelChoiceValue(choice.connectionId, choice.connectionSlug, choice.model);
}
function selectedLabel(value: string) {
return CHOICES.find((choice) => choiceValue(choice) === value)?.label ?? value;
}
function choiceForTarget(input: { llmConnectionId: string; llmConnectionSlug: string; model: string }) {
return CHOICES.find(
(choice) =>
choice.connectionId === input.llmConnectionId &&
choice.connectionSlug === input.llmConnectionSlug &&
choice.model === input.model,
);
}
function ModelPickerFrame(props: { initialValue?: string }) {
const [value, setValue] = useState(props.initialValue ?? choiceValue(CHOICES[4]!));
return (
<div style={{ width: 460 }}>
<NewChatModelPicker
label={selectedLabel(value)}
choices={CHOICES}
currentValue={value}
currentProviderType="anthropic"
renderProviderMark={providerMark}
onPick={(next) => {
const nextChoice = choiceForTarget(next);
if (nextChoice) setValue(choiceValue(nextChoice));
}}
/>
</div>
);
}
// Real path: chat → composer footer model control.
export const Default: Story = {
render: () => <ModelPickerFrame />,
};
// Real path: an existing conversation -> composer footer model control. The
// cache notice belongs inside this picker's open decision surface; the resting
// trigger and the new-chat picker below stay quiet.
export const ExistingConversation: Story = {
render: function ExistingConversationRender() {
const [activeChoice, setActiveChoice] = useState(CHOICES[4]!);
const activeSession = {
id: 'storybook-model-switch',
name: 'Model switch warning',
isFlagged: false,
isArchived: false,
labels: [],
hasUnread: false,
status: 'active',
backend: 'ai-sdk',
llmConnectionId: activeChoice.connectionId,
llmConnectionSlug: activeChoice.connectionSlug,
connectionLocked: true,
model: activeChoice.model,
permissionMode: 'ask',
} satisfies SessionSummary;
return (
<div style={{ width: 460, maxWidth: '100%' }}>
<ChatModelSwitcher
activeSession={activeSession}
activeModelLabel={activeChoice.label}
currentProviderType="anthropic"
choices={CHOICES}
hasConversationHistory
renderProviderMark={providerMark}
onChange={(next) => {
const nextChoice = choiceForTarget(next);
if (nextChoice) setActiveChoice(nextChoice);
}}
/>
</div>
);
},
play: async ({ canvasElement, globals }) => {
const english = globals.locale === 'en';
const warning = english
? 'Switching may rebuild the provider prompt cache, making the next request slower or more expensive.'
: '切换模型可能需要重建服务商提示缓存,使下一次请求更慢或成本更高。';
const trigger = within(canvasElement).getByRole('button', {
name: /切换当前任务模型|Switch model for this task/,
});
const announcement = canvasElement.querySelector<HTMLElement>('.maka-model-switch-announcement');
await expect(announcement).toHaveAttribute('role', 'status');
await expect(trigger).not.toHaveAttribute('aria-description');
await expect(announcement).toBeEmptyDOMElement();
await expect(document.body.querySelector('.maka-model-switch-notice')).not.toBeInTheDocument();
await userEvent.hover(trigger);
await within(document.body).findByText(
english ? 'Switch model for this task' : '切换当前任务模型',
);
await userEvent.unhover(trigger);
await userEvent.click(trigger);
const notice = document.body.querySelector('.maka-model-switch-notice');
await expect(notice).toBeInTheDocument();
await expect(notice).toHaveAttribute('aria-hidden', 'true');
await expect(notice).toHaveTextContent(warning);
await expect(announcement).toHaveTextContent(warning);
await expect(announcement).toHaveAttribute('aria-live', 'polite');
await expect(announcement).toHaveAttribute('aria-atomic', 'true');
const menu = within(document.body).getByRole('menu');
await expect(menu).not.toContainElement(announcement);
await userEvent.keyboard('{Escape}');
await expect(announcement).toBeEmptyDOMElement();
await expect(document.body.querySelector('.maka-model-switch-notice')).not.toBeInTheDocument();
await userEvent.keyboard('{ArrowDown}');
await expect(announcement).toHaveTextContent(warning);
await expect(document.body.querySelector('.maka-model-switch-notice')).toBeInTheDocument();
},
};
// Real path: an existing but still-empty Session. There is no conversation
// prefix to abandon yet, so this stays as quiet as the new-chat picker.
export const EmptyConversation: Story = {
render: () => (
<div style={{ width: 460, maxWidth: '100%' }}>
<ChatModelSwitcher
activeSession={{
id: 'storybook-empty-model-switch',
name: 'Empty conversation',
isFlagged: false,
isArchived: false,
labels: [],
hasUnread: false,
status: 'active',
backend: 'ai-sdk',
llmConnectionId: 'connection-anthropic-team',
llmConnectionSlug: 'anthropic-team',
connectionLocked: false,
model: 'claude-sonnet-4',
permissionMode: 'ask',
}}
activeModelLabel="Claude Sonnet 4"
currentProviderType="anthropic"
choices={CHOICES}
renderProviderMark={providerMark}
onChange={() => undefined}
/>
</div>
),
play: async ({ canvasElement }) => {
const trigger = within(canvasElement).getByRole('button', {
name: /切换当前任务模型|Switch model for this task/,
});
const announcement = canvasElement.querySelector<HTMLElement>('.maka-model-switch-announcement');
await expect(announcement).toHaveAttribute('role', 'status');
await expect(trigger).not.toHaveAttribute('aria-description');
await expect(announcement).toBeEmptyDOMElement();
await expect(document.body.querySelector('.maka-model-switch-notice')).not.toBeInTheDocument();
await userEvent.click(trigger);
await expect(announcement).toBeEmptyDOMElement();
await expect(document.body.querySelector('.maka-model-switch-notice')).not.toBeInTheDocument();
},
};
// Real path: Settings → 通用 before any provider exposes a model choice.
// The 260px frame stands in for the one part that cannot be imported from
// this package: the desktop's `select.css` sizes the trigger to 260px via
// `.settingsRows .settingsModelPickerTrigger`, which only exists in the
// renderer's stylesheet. Size and state are the production ones.
export const EmptyCatalog: Story = {
render: () => (
<div style={{ width: 260 }}>
<ModelPicker
groups={[]}
value=""
ariaLabel="默认模型"
disabled
onValueChange={async () => {}}
/>
</div>
),
};
// Real path: quiet composer left footer — model + adjacent thinking menu.
export const ThinkingLevelSeparate: Story = {
render: function ThinkingLevelSeparateRender() {
const [value, setValue] = useState(choiceValue(CHOICES[4]!));
const [thinkingLevel, setThinkingLevel] = useState<ThinkingLevel | undefined>('medium');
return (
<div className="maka-model-selection-controls" style={{ width: 'max-content' }}>
<NewChatModelPicker
label={selectedLabel(value)}
choices={CHOICES}
currentValue={value}
currentProviderType="anthropic"
renderProviderMark={providerMark}
onPick={(next) => {
const nextChoice = choiceForTarget(next);
if (nextChoice) setValue(choiceValue(nextChoice));
}}
/>
<ThinkingLevelSelector
levels={THINKING_LEVELS}
current={thinkingLevel}
onChange={setThinkingLevel}
/>
</div>
);
},
play: async ({ canvasElement }) => {
const thinking = within(canvasElement).getByRole('button', { name: /思考级别/ });
await userEvent.click(thinking);
await within(document.body).findByRole('menuitem', { name: '中' });
},
};
// Real path: Settings → 通用 → default model, while the just-picked model is
// being saved. Production drives `ModelPicker.loading` from the save in flight
// (general-settings-page.tsx `loading={saving}`), with the catalog present and
// the row disabled — not an empty catalog. (When the catalog itself is
// unavailable the settings row renders a skeleton, which is a different
// component, so that is not modelled here.)
export const SavingDefaultModel: Story = {
render: () => (
<div style={{ width: 260 }}>
<ModelPicker
groups={modelMenuGroups(CHOICES)}
value={modelChoiceValue(CHOICES[4]!.connectionSlug, CHOICES[4]!.model)}
leadingOption={{ value: '', label: '未设置' }}
renderProviderMark={providerMark}
ariaLabel="默认模型"
disabled
loading
triggerClassName="settingsModelPickerTrigger"
onValueChange={async () => {}}
/>
</div>
),
};
// Real path: composer left footer when no connection yields a usable model —
// what a failed / offline / unauthorised catalog fetch all collapse to. The
// picker cannot exist without choices, so the composer swaps in an honest
// "configure a connection" chip (ModelChipStatic's onOpenSettings button)
// rather than a dropdown with nothing behind it.
export const NoModelsAvailable: Story = {
render: function NoModelsAvailableRender() {
const copy = getConversationCopy(useUiLocale()).composer;
return (
<div className="maka-model-selection-controls" style={{ width: 'max-content' }}>
<ModelChipStatic label={copy.selectModel} onOpenSettings={() => {}} />
</div>
);
},
play: async ({ canvasElement }) => {
// It is a real button into Settings, not inert text wearing a dead chevron.
await expect(
within(canvasElement).getByRole('button', {
name: /配置模型连接|Configure model connections/,
}),
).toBeInTheDocument();
},
};
// Real path: home / new-chat model control for a workspace with many configured
// connections — the breadth #3446 F5 says a single reference screen never
// exercises. Two OpenAI keys land in the same provider, so their headings carry
// the disambiguating slug suffix.
export const ManyConnections: Story = {
render: function ManyConnectionsRender() {
const [value, setValue] = useState(choiceValue(MANY_CHOICES[0]!));
return (
<div style={{ width: 460, maxWidth: '100%' }}>
<NewChatModelPicker
label={MANY_CHOICES.find((candidate) => choiceValue(candidate) === value)?.label ?? value}
choices={MANY_CHOICES}
currentValue={value}
currentProviderType="openai"
renderProviderMark={providerMark}
onPick={(next) => {
const picked = MANY_CHOICES.find(
(candidate) =>
candidate.connectionId === next.llmConnectionId &&
candidate.connectionSlug === next.llmConnectionSlug &&
candidate.model === next.model,
);
if (picked) setValue(choiceValue(picked));
}}
/>
</div>
);
},
play: async ({ canvasElement }) => {
const trigger = within(canvasElement).getByRole('button', {
name: /选择新任务模型|Choose a model for the new task/,
});
await userEvent.click(trigger);
const menu = within(document.body);
// Every connection is its own labelled group and the last group's model is
// reachable in the menu's accessibility tree. This drives the visual state;
// selection behaviour and scroll geometry are contracts left to focused
// tests / e2e, not asserted here.
const groups = await menu.findAllByRole('group');
await expect(groups.length).toBeGreaterThanOrEqual(7);
await menu.findByRole('menuitem', { name: 'vendor/gamma' });
},
};
// Real path: a custom relay connection exposing verbose model identifiers with
// a long user-set connection name — very long text in the trigger, the option
// labels, and the descriptions at once.
export const LongModelNames: Story = {
render: () => (
<div style={{ width: 460, maxWidth: '100%' }}>
<NewChatModelPicker
label={LONG_CHOICES[0]!.label}
choices={LONG_CHOICES}
currentValue={choiceValue(LONG_CHOICES[0]!)}
currentProviderType="openai-compatible"
renderProviderMark={providerMark}
onPick={() => undefined}
/>
</div>
),
play: async ({ canvasElement }) => {
const trigger = within(canvasElement).getByRole('button', {
name: /选择新任务模型|Choose a model for the new task/,
});
await userEvent.click(trigger);
// Verifies the long-labelled model is reachable as a menuitem. Whether the
// long text truncates or wraps within the menu bounds is a visual check,
// not asserted here.
await within(document.body).findByRole('menuitem', {
name: /A very long model name that keeps going/,
});
},
};
// Real path: an existing Session whose connection is still configured but whose
// pinned model was dropped from that connection's catalog. ChatModelSwitcher
// surfaces the unknown current model as a leading row above the connection's
// remaining models (the `leadingOption` branch), labelled with the raw model id
// the session carries — not a hand-written label, and without removing the
// connection itself.
export const StaleCurrentModel: Story = {
render: function StaleCurrentModelRender() {
return (
<div style={{ width: 460, maxWidth: '100%' }}>
<ChatModelSwitcher
activeSession={{
id: 'storybook-stale-model',
name: 'Retired model',
isFlagged: false,
isArchived: false,
labels: [],
hasUnread: false,
status: 'active',
backend: 'ai-sdk',
llmConnectionId: 'connection-anthropic-team',
llmConnectionSlug: 'anthropic-team',
connectionLocked: false,
model: 'claude-opus-3-retired',
permissionMode: 'ask',
}}
activeModelLabel="claude-opus-3-retired"
currentProviderType="anthropic"
choices={CHOICES}
renderProviderMark={providerMark}
onChange={() => undefined}
/>
</div>
);
},
play: async ({ canvasElement }) => {
const trigger = within(canvasElement).getByRole('button', {
name: /切换当前任务模型|Switch model for this task/,
});
await userEvent.click(trigger);
const menu = within(document.body);
// The dropped model leads the menu as the current selection…
await menu.findByRole('menuitem', { name: /claude-opus-3-retired/ });
// …while its connection's remaining models still follow underneath.
await menu.findByRole('menuitem', { name: 'Claude Sonnet 4' });
},
};
@@ -0,0 +1,135 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
* The one Design System story that survived the token-catalog cut, because the
* test that removed the others does not apply to it.
*
* Those stories were tables of Maka's own `--space-*`, `--font-size-*`,
* `--shadow-*` and `--z-*` values. Astryx ships parallel contracts for all of
* them and `maka-tokens.css` dies with Slice 13 (#1565), so a catalog of var
* names carries little review value and a short remaining life. That is the
* reason they went — NOT that Astryx has already taken the domain over, which
* is not true today: `maka-tokens.css` is still the single authority and
* `makaTheme` is a plain extend of Astryx's neutral theme.
*
* The palette matrix is different in kind. `THEME_PALETTES` is a product
* feature — the palettes a user picks in 设置 → 外观 — and every one of them
* except `default` is unreachable from any other story, including the
* appearance page's own. The smoke's catalog pass renders wide/light/default
* only, so without this story ten palettes have no oracle whatsoever.
*/
import type { Meta, StoryObj } from '@storybook/react-vite';
import { useSyncExternalStore } from 'react';
import { THEME_PALETTES } from '../../../packages/core/src/settings.js';
const meta = {
title: 'Design System/Palette Matrix',
parameters: { layout: 'padded' },
} satisfies Meta;
export default meta;
type Story = StoryObj<typeof meta>;
function subscribe(callback: () => void): () => void {
const el = document.documentElement;
const observer = new MutationObserver(callback);
observer.observe(el, { attributes: true, attributeFilter: ['class'] });
return () => observer.disconnect();
}
function getSnapshot(): boolean {
return document.documentElement.classList.contains('dark');
}
function getServerSnapshot(): boolean {
return false;
}
function useIsDark(): boolean {
return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
}
const paletteTokens = [
['background', '--background'],
['foreground', '--foreground'],
['accent', '--accent'],
['info', '--info'],
['success', '--success'],
['destructive', '--destructive'],
] as const;
export const AllPalettes: Story = {
render: () => {
const isDark = useIsDark();
return (
<section style={{ display: 'grid', gap: 20, maxWidth: 920 }}>
<div style={{ display: 'grid', gap: 4 }}>
<h2 style={{ fontSize: 16, fontWeight: 600, margin: 0 }}>Palette Matrix</h2>
<p style={{ color: 'var(--foreground-secondary)', fontSize: 12, margin: 0, lineHeight: 1.5 }}>
{THEME_PALETTES.length} 个 palette,用工具栏切 light/dark 查看另一组。每个块独立应用 data-maka-theme。
</p>
</div>
<div
style={{
display: 'grid',
gap: 12,
gridTemplateColumns: 'repeat(auto-fill, minmax(240px, 1fr))',
}}
>
{THEME_PALETTES.map((palette) => (
<div
key={palette}
data-maka-theme={palette}
className={isDark ? 'dark' : undefined}
style={{
display: 'grid',
gap: 8,
padding: 12,
borderRadius: 'var(--radius-surface)',
boxShadow: 'var(--ring-soft)',
background: 'var(--background)',
color: 'var(--foreground)',
}}
>
<strong style={{ fontSize: 13, fontWeight: 650 }}>{palette}</strong>
<div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
{paletteTokens.map(([name, token]) => (
<div key={token} style={{ display: 'grid', gap: 3, placeItems: 'center' }}>
<div
style={{
background: `var(${token})`,
borderRadius: 'var(--radius-control)',
boxShadow: 'inset 0 0 0 1px var(--border)',
height: 28,
width: 28,
}}
title={`${name}: ${token}`}
/>
</div>
))}
</div>
</div>
))}
</div>
</section>
);
},
};
@@ -0,0 +1,91 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import type { SandboxBoundaryRequestEvent } from '@maka/core/events';
import type { Meta, StoryObj } from '@storybook/react-vite';
import { SandboxBoundaryPrompt } from '../src/sandbox-boundary-prompt.js';
// Product-level stories document the real shipped path that reaches each state.
// See apps/desktop/stories/FIDELITY.md.
const meta = {
title: 'Product/Sandbox Boundary Prompt',
component: SandboxBoundaryPrompt,
parameters: {
layout: 'fullscreen',
},
decorators: [
(Story) => (
<div style={{ minHeight: '100vh', padding: '48px 24px', background: 'var(--surface-canvas)' }}>
<Story />
</div>
),
],
} satisfies Meta<typeof SandboxBoundaryPrompt>;
export default meta;
type Story = StoryObj<typeof meta>;
const filesystemAndNetworkRequest = {
id: 'boundary-event-1',
turnId: 'turn-1',
ts: Date.now(),
type: 'sandbox_boundary_request',
requestId: 'boundary-request-1',
toolUseId: 'tool-1',
justification: '下载构建依赖,并把产物写入工作区外的发布目录。',
expansion: {
filesystem: {
entries: [
{ path: '/Users/maka/release', access: 'write', scope: 'subtree' },
{ path: '/Users/maka/.config/signing.json', access: 'read', scope: 'exact' },
],
},
network: { enabled: true },
},
} satisfies SandboxBoundaryRequestEvent;
// Real path: an Auto session calls request_sandbox_boundary after a tool reports
// sandbox_boundary_required; the prompt takes over the composer slot.
export const FilesystemAndNetwork: Story = {
args: {
request: filesystemAndNetworkRequest,
onRespond: async () => {},
},
};
// Real path: the same Auto-session prompt when the requested expansion enables
// network access without adding filesystem entries.
export const NetworkOnly: Story = {
args: {
request: {
...filesystemAndNetworkRequest,
id: 'boundary-event-2',
requestId: 'boundary-request-2',
justification: '访问远程 API 以完成当前会话。',
expansion: {
network: { enabled: true },
},
},
onRespond: async () => {},
},
};
@@ -0,0 +1,473 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { useEffect, useRef, type ReactNode } from 'react';
import type { Meta, StoryObj } from '@storybook/react-vite';
import { expect, waitFor, within } from 'storybook/test';
import type { ProjectRecord } from '@maka/core/project';
import type { SessionBlockedReason, SessionStatus, SessionSummary } from '@maka/core/session';
import { SessionRail, type SessionRailStoryProps } from './session-rail-harness.js';
const NOW = Date.now();
// Fidelity convention (#1433): every story below names the real app path
// that reaches it. See apps/desktop/stories/FIDELITY.md.
const meta = {
title: 'Product/Sidebar Session List',
parameters: {
layout: 'fullscreen',
},
} satisfies Meta;
export default meta;
type Story = StoryObj<typeof meta>;
type SessionListPanelProps = SessionRailStoryProps;
const noop = () => undefined;
function makeSession(input: {
id: string;
name: string;
status?: SessionStatus;
blockedReason?: SessionBlockedReason;
lastMessageAt?: number;
isFlagged?: boolean;
isArchived?: boolean;
hasUnread?: boolean;
backend?: SessionSummary['backend'];
llmConnectionSlug?: string;
}): SessionSummary {
const status = input.status ?? 'active';
return {
id: input.id,
name: input.name,
isFlagged: input.isFlagged ?? false,
isArchived: input.isArchived ?? false,
labels: [],
hasUnread: input.hasUnread ?? false,
status,
...(input.blockedReason ? { blockedReason: input.blockedReason } : {}),
...(input.lastMessageAt !== undefined ? { lastMessageAt: input.lastMessageAt } : {}),
backend: input.backend ?? 'ai-sdk',
llmConnectionSlug: input.llmConnectionSlug ?? 'zai-live',
connectionLocked: false,
model: 'glm-4.7',
permissionMode: 'ask',
};
}
const rowActions: NonNullable<SessionListPanelProps['rowActions']> = {
onToggleFlag: noop,
onArchive: noop,
onUnarchive: noop,
onRename: noop,
onDelete: noop,
};
function panelProps(input: {
sessions: SessionSummary[];
selection?: SessionListPanelProps['selection'];
activeId?: string;
streamingSessionIds?: Set<string>;
staleSessionIds?: Set<string>;
width?: number;
viewMode?: SessionListPanelProps['viewMode'];
groups?: SessionListPanelProps['groups'];
projectActions?: SessionListPanelProps['projectActions'];
worktreeSessionIds?: SessionListPanelProps['worktreeSessionIds'];
}): SessionListPanelProps {
return {
selection: input.selection ?? { section: 'sessions' },
sessions: input.sessions,
// The rail's own width, not just the frame's: SideNav keeps its width in
// `resizable`, so a narrow frame alone only clips a 260px rail instead of
// showing what the narrow one looks like.
...(input.width === undefined ? {} : { width: input.width }),
...(input.activeId ? { activeId: input.activeId } : {}),
...(input.streamingSessionIds ? { streamingSessionIds: input.streamingSessionIds } : {}),
...(input.staleSessionIds ? { staleSessionIds: input.staleSessionIds } : {}),
...(input.groups ? { groups: input.groups } : {}),
...(input.projectActions ? { projectActions: input.projectActions } : {}),
...(input.worktreeSessionIds ? { worktreeSessionIds: input.worktreeSessionIds } : {}),
onSelectSession: noop,
onSelect: noop,
onOpenSettings: noop,
onNew: noop,
viewMode: input.viewMode ?? 'conversation',
onViewModeChange: noop,
rowActions,
};
}
function makeProject(
input: Partial<ProjectRecord> & Pick<ProjectRecord, 'id' | 'name'>,
): ProjectRecord {
return {
id: input.id,
name: input.name,
available: input.available ?? true,
preferredPath: input.preferredPath ?? `/workspace/${input.id}`,
locations: input.locations ?? [
{ path: input.preferredPath ?? `/workspace/${input.id}`, isWorktree: false },
],
...(input.archivedAt !== undefined ? { archivedAt: input.archivedAt } : {}),
...(input.aliases ? { aliases: input.aliases } : {}),
};
}
function StoryFrame(props: {
children: ReactNode;
width?: number;
height?: number;
openSessionMenuId?: string;
}) {
// 260 is `SessionListPanel`'s own default width. The frame used to default to
// 240 and clip the rail by 20px in every story that did not pass a width —
// which lands squarely on the trailing slot, so the stories could not show
// whether the timestamp fits. Stories that want a narrow rail pass the width
// to both, as `panelProps` explains.
const {
children,
width = 260,
height = 680,
openSessionMenuId,
} = props;
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!openSessionMenuId) return;
const timeout = window.setTimeout(() => {
const targetRow = Array.from(
ref.current?.querySelectorAll<HTMLElement>('[data-maka-contract="session-row"]') ?? [],
).find((row) => row.dataset.sessionId === openSessionMenuId);
if (!targetRow) {
throw new Error(`Missing task row fixture: ${openSessionMenuId}`);
}
const menuButton = targetRow.querySelector<HTMLButtonElement>(
'[aria-label$="任务操作"]',
);
if (!menuButton) {
throw new Error('Task row is missing its actions menu');
}
menuButton.click();
}, 0);
return () => window.clearTimeout(timeout);
}, [openSessionMenuId]);
return (
<div
ref={ref}
data-maka-e2e-fixture="true"
style={{
background: 'var(--surface-canvas)',
height,
overflow: 'hidden',
width,
}}
>
{children}
</div>
);
}
const statusSessions = [
makeSession({
id: 'status-running',
name: '运行中的工具链检查',
status: 'running',
lastMessageAt: NOW - 1 * 60 * 1000,
}),
makeSession({
id: 'status-waiting',
name: '等待权限确认',
status: 'waiting_for_user',
lastMessageAt: NOW - 8 * 60 * 1000,
hasUnread: true,
}),
makeSession({
id: 'status-blocked',
name: 'OAuth 需要重新授权',
status: 'blocked',
blockedReason: 'auth',
lastMessageAt: NOW - 20 * 60 * 1000,
}),
makeSession({
id: 'status-aborted',
name: '中止的临时尝试',
status: 'aborted',
lastMessageAt: NOW - 15 * 24 * 60 * 60 * 1000,
}),
];
const longTitleSessions = [
makeSession({
id: 'long-title-active',
name: '这是一个非常长的中文会话标题,用来检查窄侧边栏里标题、状态和时间不会互相挤压',
lastMessageAt: NOW - 6 * 60 * 1000,
}),
makeSession({
id: 'long-title-stale',
name: 'Artifact Pane 验收路径和 sidebar row overflow menu 的长标题组合测试',
status: 'blocked',
blockedReason: 'permission_required',
lastMessageAt: NOW - 31 * 60 * 1000,
}),
makeSession({
id: 'long-title-pinned',
name: 'PR #390 Sidebar session-list storyboard 状态覆盖范围确认',
isFlagged: true,
lastMessageAt: NOW - 52 * 60 * 1000,
}),
];
const liveRunAuthoritySessions: SessionSummary[] = [
{
...makeSession({
id: 'live-unknown',
name: 'Unknown:兼容旧 Host 的 persisted fallback',
status: 'running',
lastMessageAt: NOW - 4 * 60 * 1000,
}),
},
{
...makeSession({
id: 'live-known-empty',
name: 'Known empty:忽略崩溃遗留的 running',
status: 'running',
lastMessageAt: NOW - 3 * 60 * 1000,
}),
runningTurnIds: [],
},
{
...makeSession({
id: 'live-remote-running',
name: 'Remote running:来自机器人或第二窗口',
lastMessageAt: NOW - 2 * 60 * 1000,
}),
runningTurnIds: ['turn-remote'],
},
{
...makeSession({
id: 'live-local-race',
name: 'Local streaming:catalog 刷新前仍显示运行',
lastMessageAt: NOW - 1 * 60 * 1000,
}),
runningTurnIds: [],
},
];
// Real path: a fresh workspace with no tasks yet — the rail's list before
// anything is created.
export const Empty: Story = {
render: () => (
<StoryFrame>
<SessionRail {...panelProps({ sessions: [] })} />
</StoryFrame>
),
};
// Real path: the same list once its rows carry lifecycle state (running / waiting /
// failed), which the row shows as an indicator rather than a bucket (#1459).
export const ConversationStates: Story = {
render: () => (
<StoryFrame>
<SessionRail {...panelProps({
sessions: statusSessions,
activeId: 'status-waiting',
streamingSessionIds: new Set(['status-running']),
staleSessionIds: new Set(['status-blocked']),
})} />
</StoryFrame>
),
};
// Real path: the active task row's overflow menu after its semantic trigger is
// opened. The menu is portaled outside the rail, so the play assertion reads
// from the owning document rather than only the story canvas.
export const ActiveTaskActionsOpen: Story = {
render: () => (
<StoryFrame openSessionMenuId="status-waiting">
<SessionRail {...panelProps({
sessions: statusSessions,
activeId: 'status-waiting',
})} />
</StoryFrame>
),
play: async ({ canvasElement }) => {
const page = within(canvasElement.ownerDocument.body);
await waitFor(() => expect(page.getByRole('menu')).toBeVisible());
expect(page.getByRole('menuitem', { name: '重命名' })).toBeVisible();
},
};
// Real path: Runtime Host catalog refreshes distinguish an older Host (unknown),
// an authoritative empty run set, a run started by another Client, and the
// renderer-local synchronization window immediately after send.
export const LiveRunAuthorityStates: Story = {
render: () => (
<StoryFrame>
<SessionRail {...panelProps({
sessions: liveRunAuthoritySessions,
activeId: 'live-remote-running',
streamingSessionIds: new Set(['live-local-race']),
})} />
</StoryFrame>
),
};
// Real path: a workspace with long task titles, with the rail dragged to its
// narrow end (180px, the panel's own minWidth).
export const LongTitlesAndNarrow: Story = {
render: () => (
<StoryFrame width={180}>
<SessionRail {...panelProps({
width: 180,
sessions: longTitleSessions,
activeId: 'long-title-active',
staleSessionIds: new Set(['long-title-stale']),
})} />
</StoryFrame>
),
};
// Real path: time-sort with both flagged and unflagged sessions — two
// SideNavSection zones (置顶 / 最近), not a single labeled exception.
export const PinnedAndRecentSections: Story = {
render: () => (
<StoryFrame>
<SessionRail
{...panelProps({
sessions: [
makeSession({
id: 'pinned-a',
name: '发布风险清单',
isFlagged: true,
lastMessageAt: NOW - 40 * 60 * 1000,
}),
makeSession({
id: 'pinned-b',
name: '长期跟踪的客户反馈',
isFlagged: true,
status: 'running',
lastMessageAt: NOW - 5 * 60 * 1000,
}),
makeSession({
id: 'recent-a',
name: '刚结束的 smoke 回归',
lastMessageAt: NOW - 12 * 60 * 1000,
}),
makeSession({
id: 'recent-b',
name: '整理 compact controls',
lastMessageAt: NOW - 2 * 60 * 60 * 1000,
}),
],
activeId: 'recent-a',
streamingSessionIds: new Set(['pinned-b']),
})}
/>
</StoryFrame>
),
};
// Real path: group-by-project — collapsible project rows, sessions nested 8px
// under the project so titles share one x, worktree mark + count badge.
export const ProjectGroups: Story = {
render: () => {
const maka = makeProject({
id: 'project-maka',
name: 'maka-agent',
preferredPath: '/workspace/maka-agent',
locations: [
{ path: '/workspace/maka-agent', isWorktree: false },
{ path: '/workspace/maka-agent/.worktree/sidebar', isWorktree: true },
],
});
const docs = makeProject({
id: 'project-docs',
name: '产品文档',
preferredPath: '/workspace/docs',
});
const missing = makeProject({
id: 'project-missing',
name: '旧版桌面端',
available: false,
});
const sessions = [
makeSession({
id: 'proj-main',
name: '主仓会话',
lastMessageAt: NOW - 4 * 60 * 1000,
}),
makeSession({
id: 'proj-worktree',
name: 'worktree 上的修复',
status: 'running',
lastMessageAt: NOW - 1 * 60 * 1000,
}),
makeSession({
id: 'proj-docs',
name: '文档站改版',
lastMessageAt: NOW - 30 * 60 * 1000,
}),
];
return (
<StoryFrame height={720}>
<SessionRail
{...panelProps({
sessions,
activeId: 'proj-worktree',
streamingSessionIds: new Set(['proj-worktree']),
viewMode: 'project',
worktreeSessionIds: new Set(['proj-worktree']),
groups: [
{
id: `project:${maka.id}`,
label: maka.name,
project: maka,
sessions: [sessions[0]!, sessions[1]!],
},
{
id: `project:${docs.id}`,
label: docs.name,
project: docs,
sessions: [sessions[2]!],
},
{
id: `project:${missing.id}`,
label: missing.name,
project: missing,
sessions: [],
},
],
projectActions: {
onNew: noop,
onRename: noop,
onArchive: noop,
onRestore: noop,
onRelink: noop,
},
})}
/>
</StoryFrame>
);
},
};
@@ -0,0 +1,78 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { SessionListPanel } from '../src/session-list-panel.js';
import {
SessionRailProvider,
type SessionRailChrome,
type SessionRailData,
} from '../src/session-rail-context.js';
export type SessionRailStoryProps = Partial<SessionRailData> &
Partial<SessionRailChrome> &
Pick<SessionRailData, 'sessions'> &
Pick<SessionRailChrome, 'selection'>;
/**
* The rail, described as one flat bag of state.
*
* In the app the rail reads two contexts and takes no props, which is what
* keeps the shell's renders off it. A story has no shell to be kept off, and
* one state per story reads better than two objects, so the split happens here.
*/
export function SessionRail(props: SessionRailStoryProps) {
const data: SessionRailData = {
sessions: props.sessions,
activeId: props.activeId,
streamingSessionIds: props.streamingSessionIds,
staleSessionIds: props.staleSessionIds,
worktreeSessionIds: props.worktreeSessionIds,
groups: props.groups,
groupVariant: props.groupVariant ?? props.viewMode ?? 'conversation',
sessionMeta: props.sessionMeta,
onSelectSession: props.onSelectSession ?? (() => undefined),
rowActions: props.rowActions,
projectActions: props.projectActions,
};
const chrome: SessionRailChrome = {
collapsed: props.collapsed ?? false,
onCollapsedChange: props.onCollapsedChange ?? (() => undefined),
collapseHandleRef: props.collapseHandleRef,
width: props.width ?? 260,
onWidthChange: props.onWidthChange ?? (() => undefined),
minWidth: props.minWidth ?? 180,
maxWidth: props.maxWidth ?? 480,
viewMode: props.viewMode ?? 'conversation',
onViewModeChange: props.onViewModeChange,
selection: props.selection,
scheduledTasks: props.scheduledTasks,
moduleMemory: props.moduleMemory,
onSelect: props.onSelect ?? (() => undefined),
onNew: props.onNew ?? (() => undefined),
onOpenSettings: props.onOpenSettings ?? (() => undefined),
updateReminder: props.updateReminder,
onOpenUpdate: props.onOpenUpdate,
workHubEntry: props.workHubEntry,
};
return (
<SessionRailProvider data={data} chrome={chrome}>
<SessionListPanel />
</SessionRailProvider>
);
}
+58
View File
@@ -0,0 +1,58 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import type { Meta, StoryObj } from '@storybook/react-vite';
import { StatTile, type StatTileTone } from '../src/primitives/stat-tile.js';
const meta = {
title: 'Primitives/StatTile',
parameters: {
layout: 'centered',
},
} satisfies Meta;
export default meta;
type Story = StoryObj<typeof meta>;
const TONES: StatTileTone[] = ['neutral', 'info', 'success', 'warning', 'destructive'];
export const ToneAndEmphasisMatrix: Story = {
render: () => (
<div style={{ display: 'grid', gap: 16 }}>
{(['outline', 'filled'] as const).map((emphasis) => (
<div key={emphasis} style={{ display: 'grid', gap: 8 }}>
<span style={{ color: 'var(--muted-foreground)', fontSize: 12 }}>{emphasis}</span>
<div style={{ display: 'grid', gap: 8, gridTemplateColumns: 'repeat(5, minmax(120px, 1fr))' }}>
{TONES.map((tone, index) => (
<StatTile
key={`${emphasis}-${tone}`}
emphasis={emphasis}
tone={tone}
label={tone}
value={index === 0 ? 0 : index * 12}
detail={index === 0 ? 'zero neutral' : 'sample'}
/>
))}
</div>
</div>
))}
</div>
),
};
+240
View File
@@ -0,0 +1,240 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { useEffect, useState } from 'react';
import type { Meta, StoryObj } from '@storybook/react-vite';
import { expect, userEvent, waitFor, within } from 'storybook/test';
import { ToastProvider, useToast, type ToastVariant } from '../src/toast.js';
import { Button } from '../src/index.js';
const meta = {
title: 'Primitives/Toast',
parameters: {
layout: 'fullscreen',
},
decorators: [
(Story) => (
<ToastProvider>
<Story />
</ToastProvider>
),
],
} satisfies Meta;
export default meta;
type Story = StoryObj<typeof meta>;
const VARIANTS: ToastVariant[] = ['info', 'success', 'warning', 'error'];
export const Seeded: Story = {
render: () => {
const toast = useToast();
useEffect(() => {
for (const variant of VARIANTS) {
toast.toast({ title: `${variant} 标题`, description: `${variant} 说明文字`, variant, duration: 0 });
}
}, [toast]);
return <div style={{ minHeight: 360 }} />;
},
};
function ConfirmQueueExample() {
const toast = useToast();
const [results, setResults] = useState<boolean[]>([]);
return (
<div style={{ display: 'grid', gap: 12, padding: 24, width: 360 }}>
<span>结果:{results.map(String).join(',')}</span>
<Button
variant="secondary"
label="连续确认"
onClick={() => {
const first = toast.confirm({
title: '确认 A?',
confirmLabel: '确认 A',
});
const second = toast.confirm({
title: '确认 B?',
confirmLabel: '确认 B',
});
void Promise.all([first, second]).then(setResults);
}}
/>
</div>
);
}
export const ConfirmQueued: Story = {
render: () => <ConfirmQueueExample />,
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
const page = within(document.body);
const opener = canvas.getByRole('button', { name: '连续确认' });
await userEvent.click(opener);
const first = await page.findByRole('alertdialog', { name: '确认 A?' });
await expect(page.queryAllByRole('alertdialog')).toHaveLength(1);
await expect(page.queryByRole('alertdialog', { name: '确认 B?' })).not.toBeInTheDocument();
const firstCancel = within(first).getByRole('button', { name: '取消' });
await expect(firstCancel).toHaveFocus();
await userEvent.click(firstCancel);
await waitFor(() => {
expect(page.queryByRole('alertdialog', { name: '确认 A?' })).not.toBeInTheDocument();
});
const second = await page.findByRole('alertdialog', { name: '确认 B?' });
await expect(page.queryAllByRole('alertdialog')).toHaveLength(1);
const secondCancel = within(second).getByRole('button', { name: '取消' });
await expect(secondCancel).toHaveFocus();
await userEvent.click(
within(second).getByRole('button', { name: '确认 B' }),
);
await waitFor(() => expect(canvas.getByText('结果:false,true')).toBeInTheDocument());
await expect(page.queryAllByRole('alertdialog')).toHaveLength(0);
await expect(opener).toHaveFocus();
},
};
// The diagnostics affordance the provider wires onto every error toast — and
// the branch where opening it also fails, so the provider raises its own
// failure toast instead of swallowing the rejection.
const DIAGNOSTICS_ERROR_ACTION = {
label: '查看详情',
failureTitle: '无法打开诊断',
failureDescription: '日志服务未响应,请稍后重试。',
onClick: async () => {
throw new Error('diagnostics unavailable');
},
};
// Real trigger: any failed operation surfaced through `toast.error` (a failed
// save, an offline sync, an unauthorised request — this surface has one error
// affordance, so they all share its shape). A bare `error` variant never
// exercises the action button or its own failure path.
export const ErrorWithDiagnostics: Story = {
decorators: [
(Story) => (
<ToastProvider errorAction={DIAGNOSTICS_ERROR_ACTION}>
<Story />
</ToastProvider>
),
],
render: () => {
const toast = useToast();
useEffect(() => {
toast.toast({
title: '保存失败',
description: '网络中断,更改未同步。',
variant: 'error',
duration: 0,
});
}, [toast]);
return <div style={{ minHeight: 360 }} />;
},
play: async () => {
const page = within(document.body);
// The error toast carries the provider's diagnostics action…
const diagnostics = await page.findByRole('button', { name: '查看详情' });
await userEvent.click(diagnostics);
// …and when that action itself fails, the provider surfaces its own
// failure toast rather than dropping the rejection on the floor.
await page.findByText('无法打开诊断');
},
};
function DestructiveConfirmExample() {
const toast = useToast();
return (
<div style={{ display: 'grid', gap: 12, padding: 24, width: 360 }}>
<Button
variant="secondary"
label="删除项目"
onClick={() => {
void toast.confirm({
title: '删除项目?',
description: '此操作会移除该项目的全部本地记录,且不可撤销。',
confirmLabel: '删除',
cancelLabel: '取消',
destructive: true,
});
}}
/>
</div>
);
}
// Real trigger: an irreversible action (delete a project / task). The confirm
// button wears the destructive variant and initial focus rests on cancel, so
// the dangerous path is never the default.
export const DestructiveConfirm: Story = {
render: () => <DestructiveConfirmExample />,
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
const page = within(document.body);
await userEvent.click(canvas.getByRole('button', { name: '删除项目' }));
const dialog = await page.findByRole('alertdialog', { name: '删除项目?' });
await expect(within(dialog).getByRole('button', { name: '删除' })).toBeInTheDocument();
// The least-destructive choice holds initial focus.
await expect(within(dialog).getByRole('button', { name: '取消' })).toHaveFocus();
},
};
const LONG_TOAST_TITLE =
'同步到远程工作区时发生了一个需要你注意的、标题本身就相当冗长的问题';
const LONG_TOAST_DESCRIPTION =
'远程主机在多次重试后仍未确认写入:连接在握手阶段被重置,随后的退避重试也接连超时。' +
'本地更改已安全保留,你可以稍后重新同步;这段说明刻意写得很长,用来检验 toast 卡片在多行文本下是否仍然清晰,而不会把操作区挤出可视范围。';
// Very long title and body: the card must wrap legibly rather than clip text
// or shove the layout off-screen.
export const LongContent: Story = {
render: () => {
const toast = useToast();
useEffect(() => {
toast.toast({
title: LONG_TOAST_TITLE,
description: LONG_TOAST_DESCRIPTION,
variant: 'warning',
duration: 0,
});
}, [toast]);
return <div style={{ minHeight: 360 }} />;
},
};
// Many notifications at once — a burst of background results stacking up.
// Exercises the stack's density and whatever cap or scroll the layer applies,
// which a single seeded toast never shows.
export const ManyStacked: Story = {
render: () => {
const toast = useToast();
useEffect(() => {
for (let i = 1; i <= 8; i += 1) {
toast.toast({
title: `后台任务 ${i} 已完成`,
description: `第 ${i} 条通知的说明文字。`,
variant: VARIANTS[i % VARIANTS.length]!,
duration: 0,
});
}
}, [toast]);
return <div style={{ minHeight: 360 }} />;
},
};
@@ -0,0 +1,396 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import type { ToolResultContent } from '@maka/core/events';
import type { ToolActivityItem, ToolOutputChunk } from '../src/materialize.js';
const NOW = 1_735_689_600_000;
const longStdout = Array.from({ length: 506 }, (_, index) => `stdout line ${index + 1}: package task output`).join('\n');
const terminalResult = {
kind: 'terminal',
cwd: '/Users/yuhan/workspace/oss/maka-agent',
cmd: 'npm run -w @maka/desktop build-storybook',
status: 'completed',
exitCode: 0,
output: pipeOutput(longStdout, 'storybook build completed with a large output preview\n'),
} satisfies ToolResultContent;
const terminalFailureResult = {
kind: 'terminal',
cwd: '/Users/yuhan/workspace/oss/maka-agent',
cmd: 'npm run -w @maka/eval test',
status: 'failed',
exitCode: 1,
output: pipeOutput(
'running eval tests\n',
['Error: expected earliest valid attempt', 'at packages/eval/src/result.ts:42:11'].join('\n'),
),
} satisfies ToolResultContent;
function pipeOutput(stdout = '', stderr = '') {
return {
mode: 'pipes' as const,
stdout,
stderr,
stdoutTruncated: false,
stderrTruncated: false,
redacted: false,
};
}
// Background Bash (`run_in_background: true`) settles as `shell_run`, not
// `terminal`. It shares the command surface with the foreground and live paths,
// so the three belong in one story to compare.
const shellRunResult = {
kind: 'shell_run',
mode: 'pipes',
ref: 'shell-7f21',
cwd: '/Users/yuhan/workspace/oss/maka-agent',
cmd: 'npm run -w @maka/ui test -- --watch',
status: 'running',
startedAt: NOW - 1_400,
updatedAt: NOW,
revision: 3,
output: pipeOutput('watching packages/ui/src for changes\n341 passing\n'),
} satisfies ToolResultContent;
const fileDiffResult = {
kind: 'file_diff',
paths: ['packages/ui/src/tool-activity.tsx', 'packages/ui/stories/tool-activity.stories.tsx'],
diff: [
'diff --git a/packages/ui/src/tool-activity.tsx b/packages/ui/src/tool-activity.tsx',
'--- a/packages/ui/src/tool-activity.tsx',
'+++ b/packages/ui/src/tool-activity.tsx',
'@@ -139,7 +139,8 @@ export function ToolActivity(props: { items: ToolActivityItem[] }) {',
'- {item.intent && <p>{item.intent}</p>}',
'+ {item.intent && !permissionDenied && (',
'+ <p>{formatToolIntent(item.intent)}</p>',
'+ )}',
' {item.args !== undefined && (',
].join('\n'),
} satisfies ToolResultContent;
const webSearchResult = {
kind: 'web_search',
provider: 'tavily',
query: 'Maka Storybook ToolActivity review states',
rows: [
{
title: 'Storybook interaction testing',
url: 'https://storybook.js.org/docs/writing-tests/interaction-testing',
snippet: 'Use stories to capture states that are hard to reproduce by driving the app.',
source: 'storybook.js.org',
},
{
title: 'Visual review checklist',
url: 'https://example.com/design-review',
snippet: 'Stable fixtures make spacing, hierarchy, and copy density easier to compare.',
source: 'example.com',
},
],
} satisfies ToolResultContent;
const webSearchErrorResult = {
kind: 'web_search_error',
ok: false,
provider: 'tavily',
query: 'latest package metadata',
reason: 'invalid_credentials',
message: 'Tavily rejected the saved API key.',
credentialSource: 'saved',
} satisfies ToolResultContent;
const liveOutputChunks: ToolOutputChunk[] = [
{ seq: 1, stream: 'stdout', text: 'installing dependencies\n', redacted: false, createdAt: NOW - 7_000 },
{ seq: 2, stream: 'stderr', text: 'warning: optional peer dependency not installed\n', redacted: false, createdAt: NOW - 6_000 },
{ seq: 3, stream: 'stdout', text: 'running build pipeline\n', redacted: false, createdAt: NOW - 5_000 },
{ seq: 4, stream: 'stderr', text: '', redacted: true, createdAt: NOW - 4_000 },
{ seq: 5, stream: 'stdout', text: 'waiting for Storybook static generation\n', redacted: false, createdAt: NOW - 3_000 },
];
function toolItem(item: ToolActivityItem): ToolActivityItem {
return item;
}
export const statusOverviewItems = [
toolItem({
toolUseId: 'status-long-running',
toolName: 'bash',
displayName: 'Shell command',
intent: 'Run a command that has not returned yet.',
status: 'running',
args: { cmd: 'npm run typecheck' },
}),
toolItem({
toolUseId: 'status-running',
toolName: 'bash',
displayName: 'Build Storybook',
intent: 'Generate the static Storybook bundle.',
status: 'running',
args: { cmd: 'npm run -w @maka/desktop build-storybook' },
outputChunks: liveOutputChunks.slice(0, 3),
}),
toolItem({
toolUseId: 'status-completed',
toolName: 'read_file',
displayName: 'Read fixture',
status: 'completed',
args: { path: 'packages/ui/stories/tool-activity.fixtures.ts' },
result: { kind: 'text', text: 'Fixture loaded successfully.' },
durationMs: 842,
}),
toolItem({
toolUseId: 'status-errored',
toolName: 'bash',
displayName: 'Eval test',
status: 'errored',
args: { cmd: 'npm run -w @maka/eval test' },
result: terminalFailureResult,
durationMs: 2_480,
}),
toolItem({
toolUseId: 'status-interrupted',
toolName: 'Grep',
displayName: 'Search repository',
status: 'interrupted',
args: { pattern: 'ToolActivity', path: 'packages/ui/src' },
result: { kind: 'text', text: 'The turn was interrupted after partial output was retained.' },
durationMs: 9_360,
}),
] satisfies ToolActivityItem[];
export const terminalAndLiveOutputItems = [
toolItem({
toolUseId: 'terminal-result',
toolName: 'bash',
displayName: 'Storybook build',
intent: 'Build Storybook and keep long terminal output bounded.',
status: 'completed',
args: { cmd: terminalResult.cmd, cwd: terminalResult.cwd },
result: terminalResult,
durationMs: 31_240,
}),
toolItem({
toolUseId: 'live-output',
toolName: 'bash',
displayName: 'Live output',
intent: 'Stream interleaved stdout and stderr while the tool runs.',
status: 'running',
args: { cmd: 'npm run build' },
outputChunks: liveOutputChunks,
outputTruncated: true,
durationMs: 8_120,
}),
] satisfies ToolActivityItem[];
/** The same shell command in all three shapes it can reach the detail panel in. */
export const shellCommandSurfaceItems = [
toolItem({
toolUseId: 'shell-surface-live',
toolName: 'Bash',
displayName: 'Live output',
intent: 'Stream interleaved stdout and stderr while the tool runs.',
status: 'running',
args: { command: 'npm run build' },
outputChunks: liveOutputChunks,
outputTruncated: true,
durationMs: 8_120,
}),
toolItem({
toolUseId: 'shell-surface-terminal',
toolName: 'Bash',
displayName: 'Storybook build',
intent: 'Foreground run that settled with long bounded output.',
status: 'completed',
args: { command: terminalResult.cmd },
result: terminalResult,
durationMs: 31_240,
}),
toolItem({
toolUseId: 'shell-surface-background',
toolName: 'Bash',
displayName: 'Background watcher',
intent: 'Background run tracked by ref instead of returning inline.',
status: 'running',
args: { command: shellRunResult.cmd, run_in_background: true },
result: shellRunResult,
durationMs: 1_400,
}),
toolItem({
toolUseId: 'shell-surface-failed',
toolName: 'Bash',
displayName: 'Failing test',
intent: 'Failure keeps the same surface and only re-tints its border.',
status: 'errored',
args: { command: terminalFailureResult.cmd },
result: terminalFailureResult,
durationMs: 2_480,
}),
] satisfies ToolActivityItem[];
/**
* What the runtime now produces for real Edit/Write calls (#2232): no
* `diff --git` preamble, straight `---`/`+++` headers; `/dev/null` for a
* created file. The collapsed rows are where the green `+N` / red `-N`
* stats show.
*/
const editDiffResult = {
kind: 'file_diff',
paths: ['packages/ui/src/tool-activity.tsx'],
diff: [
'--- a/packages/ui/src/tool-activity.tsx',
'+++ b/packages/ui/src/tool-activity.tsx',
'@@ -286,7 +286,8 @@',
' const calls: ChatToolCallItem[] = items.map((item) => ({',
' key: item.toolUseId,',
' name: resolveToolDisplayName(item, locale),',
' status: astryxToolStatus(item),',
'+ ...(item.result?.kind === \'file_diff\' ? diffRowStats(item.result.diff) : {}),',
' duration: formatDuration(item.durationMs) ?? undefined,',
' stats: outcomeWord(item, locale),',
' resultDetail: (',
].join('\n'),
} satisfies ToolResultContent;
const writeNewFileDiffResult = {
kind: 'file_diff',
paths: ['docs/tool-result-diff.md'],
diff: [
'--- /dev/null',
'+++ b/docs/tool-result-diff.md',
'@@ -0,0 +1,4 @@',
'+# Tool result diffs',
'+',
'+Edit/Write/FormatJson carry a unified diff in their tool result,',
'+rendered by FileDiffPreview on desktop and renderDiffResult in the TUI.',
].join('\n'),
} satisfies ToolResultContent;
const writeOverwriteDiffResult = {
kind: 'file_diff',
paths: ['.maka/config.json'],
diff: [
'--- a/.maka/config.json',
'+++ b/.maka/config.json',
'@@ -1,5 +1,5 @@',
' {',
' "theme": "dark",',
'- "model": "glm-5",',
'+ "model": "glm-5.1",',
' "telemetry": false',
' }',
].join('\n'),
} satisfies ToolResultContent;
export const editWriteDiffItems = [
toolItem({
toolUseId: 'edit-diff',
toolName: 'Edit',
intent: 'Pass diff stats to the tool row.',
status: 'completed',
args: { path: 'packages/ui/src/tool-activity.tsx' },
result: editDiffResult,
durationMs: 220,
}),
toolItem({
toolUseId: 'write-new-diff',
toolName: 'Write',
intent: 'Document the diff result kind.',
status: 'completed',
args: { path: 'docs/tool-result-diff.md' },
result: writeNewFileDiffResult,
durationMs: 160,
}),
toolItem({
toolUseId: 'write-overwrite-diff',
toolName: 'Write',
intent: 'Bump the configured model version.',
status: 'completed',
args: { path: '.maka/config.json' },
result: writeOverwriteDiffResult,
durationMs: 140,
}),
] satisfies ToolActivityItem[];
export const fileDiffAndWebSearchItems = [
toolItem({
toolUseId: 'file-diff',
toolName: 'apply_patch',
displayName: 'Patch preview',
intent: 'Preview a file diff before committing.',
status: 'completed',
args: { files: fileDiffResult.paths },
result: fileDiffResult,
durationMs: 1_180,
}),
toolItem({
toolUseId: 'web-search',
toolName: 'web_search',
displayName: 'Web search',
intent: 'Find current external documentation for Storybook review flows.',
status: 'completed',
args: { query: webSearchResult.query, provider: webSearchResult.provider },
result: webSearchResult,
durationMs: 3_420,
}),
toolItem({
toolUseId: 'web-search-error',
toolName: 'web_search',
displayName: 'Web search error',
intent: 'Show credential repair guidance.',
status: 'errored',
args: { query: webSearchErrorResult.query, provider: webSearchErrorResult.provider },
result: webSearchErrorResult,
durationMs: 984,
}),
] satisfies ToolActivityItem[];
export const errorsAndPermissionDeniedItems = [
toolItem({
toolUseId: 'terminal-error',
toolName: 'bash',
displayName: 'Failing test',
intent: 'Surface stderr and the error-copy affordance.',
status: 'errored',
args: { cmd: terminalFailureResult.cmd, cwd: terminalFailureResult.cwd },
result: terminalFailureResult,
durationMs: 2_480,
}),
toolItem({
toolUseId: 'permission-denied',
toolName: 'bash',
displayName: 'Denied shell command',
intent: 'This intent is hidden when the permission denial copy is rendered.',
status: 'errored',
args: { cmd: 'rm -rf dist' },
result: { kind: 'text', text: 'User denied permission' },
durationMs: 350,
}),
] satisfies ToolActivityItem[];
export const denseMixedResultItems = [
statusOverviewItems[2],
terminalAndLiveOutputItems[0],
fileDiffAndWebSearchItems[0],
fileDiffAndWebSearchItems[1],
fileDiffAndWebSearchItems[2],
errorsAndPermissionDeniedItems[0],
] satisfies ToolActivityItem[];
@@ -0,0 +1,284 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { useEffect, useRef } from 'react';
import type { Meta, StoryObj } from '@storybook/react-vite';
import { expect, userEvent, within } from 'storybook/test';
import { ToolCallDetail, ToolTrow } from '../src/tool-activity.js';
import type { ToolActivityItem } from '../src/materialize.js';
import {
denseMixedResultItems,
editWriteDiffItems,
errorsAndPermissionDeniedItems,
shellCommandSurfaceItems,
} from './tool-activity.fixtures.js';
// Fidelity convention (#1433): every story below names the real app path
// that reaches it. See apps/desktop/stories/FIDELITY.md.
const meta = {
title: 'Product/Tool Activity',
component: ToolTrow,
parameters: {
layout: 'fullscreen',
},
} satisfies Meta<typeof ToolTrow>;
export default meta;
type Story = StoryObj<typeof meta>;
const requiresBypassItem: ToolActivityItem = {
toolUseId: 'client-capability-boundary',
toolName: 'maka_computer',
displayName: '列出打开的应用',
activityKind: 'computer',
status: 'errored',
args: { action: 'list_apps' },
result: {
kind: 'text',
text: [
'Client Capability tools require the Bypass execution boundary because their',
'client-side effects cannot be sandboxed by the Host. Switch this Session',
'to Bypass and retry.',
].join(' '),
sandboxFailure: {
reason: 'requires_bypass',
source: 'client_capability',
},
},
};
/**
* One row per item. The product groups a contiguous run into a single
* `ToolTrow`, which collapses to its latest row; rendering one trow per item
* is how a state board shows every row at once.
*/
function ToolRowBoard(props: { items: ToolActivityItem[]; width?: number }) {
return (
<Board width={props.width}>
{props.items.map((item) => (
<ToolTrow key={item.toolUseId} items={[item]} />
))}
</Board>
);
}
/** The expanded panels, which Astryx reveals per row on click. */
function ToolDetailBoard(props: { items: ToolActivityItem[]; width?: number; autoCopyLabel?: string }) {
const rootRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!props.autoCopyLabel) return;
const root = rootRef.current;
if (!root) return;
const currentRoot = root;
const originalClipboard = navigator.clipboard;
let clipboardPatched = false;
try {
Object.defineProperty(navigator, 'clipboard', {
configurable: true,
value: { writeText: async () => undefined },
});
clipboardPatched = true;
} catch {
clipboardPatched = false;
}
function clickCopyButton() {
const buttons = Array.from(currentRoot.querySelectorAll<HTMLButtonElement>('button'));
const button = buttons.find((candidate) => {
const label = candidate.getAttribute('aria-label') ?? '';
const text = candidate.textContent ?? '';
return label.includes(props.autoCopyLabel ?? '') || text.includes(props.autoCopyLabel ?? '');
});
button?.click();
}
clickCopyButton();
const interval = window.setInterval(clickCopyButton, 900);
return () => {
window.clearInterval(interval);
if (!clipboardPatched) return;
try {
Object.defineProperty(navigator, 'clipboard', {
configurable: true,
value: originalClipboard,
});
} catch {
// Story-only clipboard mocking is best effort.
}
};
}, [props.autoCopyLabel, props.items]);
return (
<div ref={rootRef}>
<Board width={props.width}>
{props.items.map((item) => (
<ToolCallDetail key={item.toolUseId} item={item} />
))}
</Board>
</div>
);
}
function Board(props: { children: React.ReactNode; width?: number }) {
return (
<div
style={{
display: 'grid',
gap: 16,
margin: '0 auto',
maxWidth: props.width ?? 960,
width: '100%',
}}
>
{props.children}
</div>
);
}
// Real path: a tool call fails, or the user denies it in the permission prompt → the
// failed and denied rows.
export const ErrorsAndPermissionDenied: Story = {
args: { items: errorsAndPermissionDeniedItems },
render: (args) => <ToolRowBoard items={args.items} width={860} />,
};
// Real path: a client capability is invoked from an Ask-mode task. The product
// replaces the model-facing diagnostic with a localized recovery action.
export const RequiresBypassRecovery: Story = {
args: { items: [requiresBypassItem] },
render: (args) => (
<Board width={860}>
<ToolTrow
items={args.items}
onSwitchToBypassAndRetry={async () => undefined}
/>
</Board>
),
};
// Real path: a turn that mixes many tool kinds — the density case reviewers compare
// spacing against.
export const DenseMixedResults: Story = {
args: { items: denseMixedResultItems },
render: (args) => <ToolDetailBoard items={args.items} />,
};
// Real path: expanding a Bash row. Live, foreground-settled (`terminal`),
// background (`shell_run`) and failed all reach the detail panel by different
// branches; this is where to check they still read as one surface. The
// background case has no other story.
export const ShellCommandSurface: Story = {
args: { items: shellCommandSurfaceItems },
render: (args) => <ToolDetailBoard items={args.items} width={860} />,
};
// Real path: an Edit or Write settles in a turn (#2232) — the collapsed row
// carries green +N / red -N counted from the result's diff, and expanding the
// row renders the diff itself in the shared panel.
export const EditWriteDiffRows: Story = {
args: { items: editWriteDiffItems },
render: (args) => <ToolRowBoard items={args.items} width={860} />,
};
// Real path: same settled Edit/Write call, its row expanded — the detail panel
// renders the result's diff with the line-number gutter.
export const EditWriteDiffDetails: Story = {
args: { items: editWriteDiffItems },
render: (args) => <ToolDetailBoard items={args.items} width={860} />,
};
// Real path: a contiguous run of tool calls in one turn — the grouped surface the
// state boards above never show, since they render one row per trow. Astryx's
// collapsed header projects the last call alone, so this is where to look at what a
// mixed-outcome group costs in density.
export const ContiguousGroup: Story = {
args: { items: errorsAndPermissionDeniedItems },
render: (args) => (
<Board width={860}>
<ToolTrow items={args.items} />
</Board>
),
};
// Real path: several edits in one turn, which is the shape a coding turn takes
// most often and the one where the counts used to disappear — the collapsed
// header projected the last call and dropped every per-row `+N`/`-N` with it.
// The header now carries the run's total; expand it to see the rows it sums.
export const ContiguousDiffGroup: Story = {
args: { items: editWriteDiffItems },
render: (args) => (
<Board width={860}>
<ToolTrow items={args.items} />
</Board>
),
};
const longIntentItems: ToolActivityItem[] = [
{
toolUseId: 'grep-long-intent',
toolName: 'Grep',
displayName: 'Search repository',
activityKind: 'tool',
status: 'completed',
intent:
'审计模型选择、切换、持久化、event log、replay/resume 路径:当前模型事实由谁持有,何时切换,是否已有事件或消息可表达',
args: { pattern: 'model|replay|resume', path: 'packages' },
},
{
toolUseId: 'grep-long-intent-2',
toolName: 'Grep',
displayName: 'Search repository',
activityKind: 'tool',
status: 'completed',
intent:
'审计提示词构筑与缓存路径:追踪 durable system prompt、provider-visible messages 与 request shape',
args: { pattern: 'systemPrompt|requestShape', path: 'packages' },
},
];
// Regression path: a narrow conversation contains a grouped tool run whose
// intent summaries are much wider than the reading column. Expanding the group
// must truncate those rows without widening the turn itself.
export const LongIntentGroupNarrow: Story = {
args: { items: longIntentItems },
render: (args) => (
<div className="maka-turn" data-testid="narrow-turn" style={{ margin: '0 auto', width: 320 }}>
<ToolTrow items={args.items} />
</div>
),
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
const turn = canvas.getByTestId('narrow-turn');
const group = turn.querySelector<HTMLElement>('.maka-tool-activity-card');
expect(group).not.toBeNull();
const disclosure = group!.querySelector<HTMLElement>(
':scope > [role="button"][aria-controls]',
);
expect(disclosure).not.toBeNull();
await userEvent.click(disclosure!);
const rows = Array.from(group!.querySelectorAll<HTMLElement>('[role="button"]'));
expect(Math.max(...rows.map((row) => row.getBoundingClientRect().width))).toBeLessThanOrEqual(
turn.clientWidth + 8,
);
},
};