Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(portal): editable CodeMirror viewer for LocalFile + Document highlight (#15298)

Innei9945cecf879d
diff --git a/package.json b/package.json
index 4c88f08564f..55c1c90a338 100644
--- a/package.json
+++ b/package.json
@@ -281,7 +281,7 @@
"@lobehub/analytics": "^1.6.2",
"@lobehub/charts": "^5.0.0",
"@lobehub/desktop-ipc-typings": "workspace:*",
- "@lobehub/editor": "^4.12.0",
+ "@lobehub/editor": "^4.15.0",
"@lobehub/icons": "^5.0.0",
"@lobehub/market-sdk": "0.33.3",
"@lobehub/tts": "^5.1.2",
diff --git a/src/components/CodeEditorPane/index.tsx b/src/components/CodeEditorPane/index.tsx
new file mode 100644
index 00000000000..d1ab8736dc3
--- /dev/null
+++ b/src/components/CodeEditorPane/index.tsx
@@ -0,0 +1,109 @@
+'use client';
+
+import { type ICodeMirrorInstance, loadCodeMirror, lobeTheme } from '@lobehub/editor/codemirror';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { type CSSProperties, memo, useEffect, useRef } from 'react';
+
+const styles = createStaticStyles(
+ ({ css }) => css`
+ overflow: auto;
+ width: 100%;
+ height: 100%;
+ background: ${cssVar.colorFillQuaternary};
+
+ .cm-textarea {
+ height: 0;
+ opacity: 0;
+ }
+ `,
+);
+
+export interface CodeEditorPaneProps {
+ className?: string;
+ language: string;
+ onChange?: (value: string) => void;
+ /** Triggered when the user presses Cmd/Ctrl + S while the editor has focus. */
+ onSave?: () => void | Promise<void>;
+ readOnly?: boolean;
+ style?: CSSProperties;
+ value: string;
+}
+
+const CodeEditorPane = memo<CodeEditorPaneProps>(
+ ({ value, language, style, className, readOnly = false, onChange, onSave }) => {
+ const containerRef = useRef<HTMLDivElement>(null);
+ const textareaRef = useRef<HTMLTextAreaElement>(null);
+ const instanceRef = useRef<ICodeMirrorInstance | null>(null);
+ const onChangeRef = useRef(onChange);
+ const onSaveRef = useRef(onSave);
+ onChangeRef.current = onChange;
+ onSaveRef.current = onSave;
+
+ useEffect(() => {
+ if (!textareaRef.current) return;
+ const dom = textareaRef.current;
+ let disposed = false;
+
+ loadCodeMirror().then((CodeMirror) => {
+ if (disposed || instanceRef.current) return;
+ const instance = CodeMirror.fromTextArea(dom, {
+ lineNumbers: true,
+ lineWrapping: true,
+ mode: language,
+ readOnly,
+ theme: 'default',
+ value,
+ });
+ instance.view.dispatch({
+ effects: instance.optionHelper.theme.reconfigure(
+ instance.view.constructor.theme(lobeTheme, { dark: false }),
+ ),
+ });
+ instance.on('change', () => {
+ onChangeRef.current?.(instance.getValue());
+ });
+ instance.on('keydown', (_inst: ICodeMirrorInstance, e: KeyboardEvent) => {
+ if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 's') {
+ e.preventDefault();
+ e.stopPropagation();
+ onSaveRef.current?.();
+ }
+ });
+ instanceRef.current = instance;
+ });
+
+ return () => {
+ disposed = true;
+ if (instanceRef.current) {
+ instanceRef.current.destroy();
+ instanceRef.current = null;
+ }
+ };
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
+ useEffect(() => {
+ const instance = instanceRef.current;
+ if (!instance) return;
+ if (instance.getValue() !== value) instance.setValue(value);
+ }, [value]);
+
+ useEffect(() => {
+ instanceRef.current?.setOption('mode', language);
+ }, [language]);
+
+ useEffect(() => {
+ instanceRef.current?.setOption('readOnly', readOnly);
+ }, [readOnly]);
+
+ return (
+ <div className={`${styles} ${className ?? ''}`.trim()} ref={containerRef} style={style}>
+ <textarea className={'cm-textarea'} ref={textareaRef} />
+ </div>
+ );
+ },
+);
+
+CodeEditorPane.displayName = 'CodeEditorPane';
+
+export default CodeEditorPane;
diff --git a/src/features/Portal/Document/Body.test.tsx b/src/features/Portal/Document/Body.test.tsx
index 2bec96d2de6..9a1b0319eb3 100644
--- a/src/features/Portal/Document/Body.test.tsx
+++ b/src/features/Portal/Document/Body.test.tsx
@@ -26,13 +26,16 @@ vi.mock('@lobehub/ui', () => ({
ActionIcon: () => null,
Button: ({ children }: { children: ReactNode }) => <button>{children}</button>,
Flexbox: ({ children }: { children: ReactNode }) => <div>{children}</div>,
- Highlighter: ({ children }: { children: ReactNode }) => (
- <pre data-testid="highlighter">{children}</pre>
- ),
Text: ({ children }: { children: ReactNode }) => <span>{children}</span>,
TextArea: () => <textarea />,
}));
+vi.mock('@/components/CodeEditorPane', () => ({
+ default: ({ value }: { value: string }) => (
+ <textarea readOnly data-testid="highlight-editor" value={value} />
+ ),
+}));
+
const mockDocumentMeta = vi.hoisted(() => ({
current: { content: '', filename: 'doc.md' } as {
content?: string;
@@ -138,12 +141,12 @@ describe('DocumentBody', () => {
expect(screen.getByTestId('floating-chat-panel')).toBeDefined();
});
- it('renders Highlighter for non-markdown files', () => {
+ it('renders highlight editor for non-markdown files', () => {
mockDocumentMeta.current = { content: 'raw log content', filename: 'topic_call.txt' };
render(<DocumentBody />);
- expect(screen.getByTestId('highlighter')).toBeDefined();
+ expect(screen.getByTestId('highlight-editor')).toHaveValue('raw log content');
expect(screen.queryByTestId('editor-canvas')).toBeNull();
});
@@ -153,7 +156,7 @@ describe('DocumentBody', () => {
render(<DocumentBody />);
expect(screen.getByTestId('editor-canvas')).toBeDefined();
- expect(screen.queryByTestId('highlighter')).toBeNull();
+ expect(screen.queryByTestId('highlight-editor')).toBeNull();
});
it('renders EditorCanvas for notebook documents that have no filename', () => {
@@ -167,6 +170,6 @@ describe('DocumentBody', () => {
render(<DocumentBody />);
expect(screen.getByTestId('editor-canvas')).toBeDefined();
- expect(screen.queryByTestId('highlighter')).toBeNull();
+ expect(screen.queryByTestId('highlight-editor')).toBeNull();
});
});
diff --git a/src/features/Portal/Document/Body.tsx b/src/features/Portal/Document/Body.tsx
index f0a0aa135f5..29e688a945a 100644
--- a/src/features/Portal/Document/Body.tsx
+++ b/src/features/Portal/Document/Body.tsx
@@ -1,12 +1,13 @@
'use client';
-import { ActionIcon, Button, Flexbox, Highlighter, Text, TextArea } from '@lobehub/ui';
+import { ActionIcon, Button, Flexbox, Text, TextArea } from '@lobehub/ui';
import { createStaticStyles, cssVar } from 'antd-style';
import { CheckIcon, PencilIcon, XIcon } from 'lucide-react';
import type { ChangeEvent } from 'react';
import { memo, useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import CodeEditorPane from '@/components/CodeEditorPane';
import FloatingChatPanel from '@/features/FloatingChatPanel';
import { useClientDataSWR } from '@/libs/swr';
import { documentService } from '@/services/document';
@@ -197,6 +198,55 @@ const SkillFrontmatterBlock = memo<SkillFrontmatterBlockProps>(({ documentId, fr
);
});
+interface HighlightEditorProps {
+ content: string;
+ documentId: string;
+ language: string;
+ onSaved: (newContent: string) => void;
+}
+
+const HighlightEditor = memo<HighlightEditorProps>(({ content, documentId, language, onSaved }) => {
+ const [buffer, setBuffer] = useState<string | undefined>(undefined);
+ const editingValue = buffer ?? content;
+
+ const handleChange = useCallback(
+ (next: string) => {
+ setBuffer(next === content ? undefined : next);
+ },
+ [content],
+ );
+
+ const handleSave = useCallback(async () => {
+ if (buffer === undefined) return;
+ const toWrite = buffer;
+ try {
+ await documentService.updateDocument({
+ content: toWrite,
+ id: documentId,
+ saveSource: 'manual',
+ });
+ // Update SWR cache before clearing the buffer so the editor's value prop
+ // never falls back to stale content, which would otherwise reset the cursor.
+ onSaved(toWrite);
+ setBuffer(undefined);
+ } catch {
+ /* swallow */
+ }
+ }, [buffer, documentId, onSaved]);
+
+ return (
+ <CodeEditorPane
+ language={language}
+ style={{ minHeight: '100%' }}
+ value={editingValue}
+ onChange={handleChange}
+ onSave={handleSave}
+ />
+ );
+});
+
+HighlightEditor.displayName = 'HighlightEditor';
+
const DocumentBody = memo(() => {
const documentId = useChatStore(chatPortalSelectors.portalDocumentId);
const agentDocumentId = useChatStore(chatPortalSelectors.portalAgentDocumentId);
@@ -212,7 +262,7 @@ const DocumentBody = memo(() => {
);
const isSkillMarkdown = contentFormat === 'skillMarkdown';
- const { data: documentMeta } = useClientDataSWR(
+ const { data: documentMeta, mutate: mutateDocumentMeta } = useClientDataSWR(
documentId ? ['portal-document-header', documentId] : null,
() => documentService.getDocumentById(documentId!),
);
@@ -220,16 +270,29 @@ const DocumentBody = memo(() => {
? getDocumentRenderMode(documentMeta)
: { mode: 'editor' as const };
+ const handleHighlightSaved = useCallback(
+ (saved: string) => {
+ mutateDocumentMeta((prev) => (prev ? { ...prev, content: saved } : prev), {
+ revalidate: false,
+ });
+ },
+ [mutateDocumentMeta],
+ );
+
return (
<Flexbox flex={1} height={'100%'} style={{ overflow: 'hidden' }}>
<div className={styles.content}>
{documentId && isSkillMarkdown && (
<SkillFrontmatterBlock documentId={documentId} frontmatter={skillFrontmatter} />
)}
- {renderMode.mode === 'highlight' ? (
- <Highlighter language={renderMode.language} showLanguage={false} variant="borderless">
- {documentMeta?.content ?? ''}
- </Highlighter>
+ {renderMode.mode === 'highlight' && documentId ? (
+ <HighlightEditor
+ content={documentMeta?.content ?? ''}
+ documentId={documentId}
+ key={documentId}
+ language={renderMode.language}
+ onSaved={handleHighlightSaved}
+ />
) : (
<EditorCanvas />
)}
diff --git a/src/features/Portal/LocalFile/Body.tsx b/src/features/Portal/LocalFile/Body.tsx
index 5eacec4936c..e832c676b3e 100644
--- a/src/features/Portal/LocalFile/Body.tsx
+++ b/src/features/Portal/LocalFile/Body.tsx
@@ -1,10 +1,11 @@
import { isDesktop } from '@lobechat/const';
-import { Center, Empty, Flexbox, Highlighter, Icon, Markdown, Segmented, Text } from '@lobehub/ui';
+import { Center, Empty, Flexbox, Icon, Markdown, Segmented, Text } from '@lobehub/ui';
import { createStaticStyles, cssVar } from 'antd-style';
import { CodeIcon, EyeIcon } from 'lucide-react';
-import { memo, useEffect, useMemo, useState } from 'react';
+import { memo, useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import CodeEditorPane from '@/components/CodeEditorPane';
import Loading from '@/components/Loading/CircleLoading';
import { useClientDataSWR } from '@/libs/swr';
import { localFileService } from '@/services/electron/localFileService';
@@ -19,8 +20,6 @@ import {
import { extensionToLanguage, getFileExtension } from './Body.helpers';
-const MAX_PREVIEW_CHARS = 500_000;
-
const TEXT_PREVIEW_MIME_TYPES = new Set([
'application/graphql',
'application/javascript',
@@ -169,91 +168,115 @@ type TextPreviewMode = 'render' | 'raw';
interface TextPreviewPaneProps {
content: string;
ext: string;
- truncated: boolean;
- truncatedLabel: string;
+ filePath: string;
+ onSaved?: (savedContent: string) => void;
}
-const TextPreviewPane = memo<TextPreviewPaneProps>(
- ({ content, ext, truncated, truncatedLabel }) => {
- const { t } = useTranslation('chat');
- const isMarkdown = useMemo(() => MARKDOWN_EXTS.has(ext.toLowerCase()), [ext]);
+const TextPreviewPane = memo<TextPreviewPaneProps>(({ content, ext, filePath, onSaved }) => {
+ const { t } = useTranslation('chat');
+ const isMarkdown = useMemo(() => MARKDOWN_EXTS.has(ext.toLowerCase()), [ext]);
+ const buffer = useChatStore(chatPortalSelectors.localFileBuffer(filePath));
+ const setLocalFileBuffer = useChatStore((s) => s.setLocalFileBuffer);
+ const saveLocalFile = useChatStore((s) => s.saveLocalFile);
+
+ const editingValue = buffer ?? content;
+
+ const handleCodeChange = useCallback(
+ (next: string) => {
+ if (next === content) {
+ setLocalFileBuffer(filePath, undefined);
+ } else {
+ setLocalFileBuffer(filePath, next);
+ }
+ },
+ [content, filePath, setLocalFileBuffer],
+ );
- const { body, frontmatter } = useMemo(
- () => (isMarkdown ? parseSkillMarkdownFrontmatter(content) : { body: content }),
- [isMarkdown, content],
- );
- const frontmatterFields = useMemo(
- () => (frontmatter ? parseSkillMarkdownFrontmatterFields(frontmatter) : {}),
- [frontmatter],
- );
- const frontmatterMetadata = useMemo(
- () => (frontmatter ? parseSkillMarkdownMetadata(frontmatter) : []),
- [frontmatter],
- );
+ const handleSave = useCallback(async () => {
+ try {
+ const saved = await saveLocalFile(filePath);
+ if (saved === undefined) return;
+ // Update SWR cache BEFORE clearing the buffer, otherwise React will
+ // briefly render with buffer cleared but content still stale, causing
+ // CodeMirror to setValue and reset the cursor.
+ onSaved?.(saved);
+ setLocalFileBuffer(filePath, undefined);
+ } catch {
+ /* swallow — surfacing handled elsewhere if needed */
+ }
+ }, [filePath, onSaved, saveLocalFile, setLocalFileBuffer]);
- const [mode, setMode] = useState<TextPreviewMode>(isMarkdown ? 'render' : 'raw');
+ const { body, frontmatter } = useMemo(
+ () => (isMarkdown ? parseSkillMarkdownFrontmatter(editingValue) : { body: editingValue }),
+ [isMarkdown, editingValue],
+ );
+ const frontmatterFields = useMemo(
+ () => (frontmatter ? parseSkillMarkdownFrontmatterFields(frontmatter) : {}),
+ [frontmatter],
+ );
+ const frontmatterMetadata = useMemo(
+ () => (frontmatter ? parseSkillMarkdownMetadata(frontmatter) : []),
+ [frontmatter],
+ );
- useEffect(() => {
- setMode(isMarkdown ? 'render' : 'raw');
- }, [isMarkdown]);
+ const [mode, setMode] = useState<TextPreviewMode>(isMarkdown ? 'render' : 'raw');
- return (
- <Flexbox flex={1} height={'100%'} style={{ minHeight: 0, overflow: 'hidden' }}>
- {isMarkdown && (
- <Flexbox
- horizontal
- align={'center'}
- gap={8}
- paddingBlock={6}
- paddingInline={12}
- style={{ flexShrink: 0 }}
- >
- <Text ellipsis style={{ flex: 1, fontSize: 13, fontWeight: 500, minWidth: 0 }}>
- {frontmatterFields.name ?? ''}
- </Text>
- <Segmented
- size={'small'}
- value={mode}
- options={[
- {
- icon: <Icon icon={EyeIcon} />,
- label: t('workingPanel.localFile.preview.render'),
- value: 'render',
- },
- {
- icon: <Icon icon={CodeIcon} />,
- label: t('workingPanel.localFile.preview.raw'),
- value: 'raw',
- },
- ]}
- onChange={(v) => setMode(v as TextPreviewMode)}
- />
- </Flexbox>
- )}
- {truncated && (
- <Center paddingBlock={4} style={{ flexShrink: 0 }}>
- <span style={{ fontSize: 12, opacity: 0.65 }}>{truncatedLabel}</span>
- </Center>
+ useEffect(() => {
+ setMode(isMarkdown ? 'render' : 'raw');
+ }, [isMarkdown]);
+
+ return (
+ <Flexbox flex={1} height={'100%'} style={{ minHeight: 0, overflow: 'hidden' }}>
+ {isMarkdown && (
+ <Flexbox
+ horizontal
+ align={'center'}
+ gap={8}
+ paddingBlock={6}
+ paddingInline={12}
+ style={{ flexShrink: 0 }}
+ >
+ <Text ellipsis style={{ flex: 1, fontSize: 13, fontWeight: 500, minWidth: 0 }}>
+ {frontmatterFields.name ?? ''}
+ </Text>
+ <Segmented
+ size={'small'}
+ value={mode}
+ options={[
+ {
+ icon: <Icon icon={EyeIcon} />,
+ label: t('workingPanel.localFile.preview.render'),
+ value: 'render',
+ },
+ {
+ icon: <Icon icon={CodeIcon} />,
+ label: t('workingPanel.localFile.preview.raw'),
+ value: 'raw',
+ },
+ ]}
+ onChange={(v) => setMode(v as TextPreviewMode)}
+ />
+ </Flexbox>
+ )}
+ <div style={{ flex: 1, minHeight: 0, overflow: 'auto' }}>
+ {isMarkdown && mode === 'render' ? (
+ <>
+ <SkillFrontmatterPreviewCard metadata={frontmatterMetadata} />
+ <Markdown style={{ paddingBlock: 8, paddingInline: 12 }}>{body}</Markdown>
+ </>
+ ) : (
+ <CodeEditorPane
+ language={extensionToLanguage(ext)}
+ style={{ fontSize: 12, minHeight: '100%' }}
+ value={editingValue}
+ onChange={handleCodeChange}
+ onSave={handleSave}
+ />
)}
- <div style={{ flex: 1, minHeight: 0, overflow: 'auto' }}>
- {isMarkdown && mode === 'render' ? (
- <>
- <SkillFrontmatterPreviewCard metadata={frontmatterMetadata} />
- <Markdown style={{ paddingBlock: 8, paddingInline: 12 }}>{body}</Markdown>
- </>
- ) : (
- <Highlighter
- language={extensionToLanguage(ext)}
- style={{ fontSize: 12, minHeight: '100%' }}
- >
- {content}
- </Highlighter>
- )}
- </div>
- </Flexbox>
- );
- },
-);
+ </div>
+ </Flexbox>
+ );
+});
TextPreviewPane.displayName = 'TextPreviewPane';
@@ -272,7 +295,8 @@ const ActiveFileView = memo<ActiveFileViewProps>(({ filePath, workingDirectory }
data: preview,
error,
isLoading,
- } = useClientDataSWR(
+ mutate,
+ } = useClientDataSWR<LocalFilePreview>(
isDesktop && workingDirectory ? ['local-file-preview', filePath, workingDirectory] : null,
async () => {
const result = await localFileService.getLocalFilePreviewUrl({
@@ -289,6 +313,15 @@ const ActiveFileView = memo<ActiveFileViewProps>(({ filePath, workingDirectory }
{ revalidateOnFocus: false },
);
+ const handleSavedContent = useCallback(
+ (saved: string) => {
+ mutate((prev) => (prev && prev.type === 'text' ? { ...prev, content: saved } : prev), {
+ revalidate: false,
+ });
+ },
+ [mutate],
+ );
+
// Chromium blocks `file://` from a non-file origin. The desktop main process
// mints short-lived `localfile://` preview URLs for approved workspace files.
if (!isDesktop) {
@@ -322,17 +355,13 @@ const ActiveFileView = memo<ActiveFileViewProps>(({ filePath, workingDirectory }
}
const ext = getFileExtension(filename);
- const truncated = preview.content.length > MAX_PREVIEW_CHARS;
- const displayContent = truncated ? preview.content.slice(0, MAX_PREVIEW_CHARS) : preview.content;
return (
<TextPreviewPane
- content={displayContent}
+ content={preview.content}
ext={ext}
- truncated={truncated}
- truncatedLabel={t('workingPanel.localFile.truncated', {
- limit: MAX_PREVIEW_CHARS.toLocaleString(),
- })}
+ filePath={filePath}
+ onSaved={handleSavedContent}
/>
);
});
diff --git a/src/features/Portal/LocalFile/TabStrip.tsx b/src/features/Portal/LocalFile/TabStrip.tsx
index 427526e8d8e..a9a1557d91c 100644
--- a/src/features/Portal/LocalFile/TabStrip.tsx
+++ b/src/features/Portal/LocalFile/TabStrip.tsx
@@ -1,7 +1,7 @@
'use client';
import { ContextMenuTrigger, type GenericItemType, Icon } from '@lobehub/ui';
-import { ScrollArea } from '@lobehub/ui/base-ui';
+import { confirmModal, ScrollArea } from '@lobehub/ui/base-ui';
import { SkillsIcon } from '@lobehub/ui/icons';
import { createStaticStyles } from 'antd-style';
import { FileIcon, XIcon } from 'lucide-react';
@@ -38,9 +38,41 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
opacity: 0.6;
background: transparent;
+ .cm-tab-close-x {
+ display: inline-flex;
+ }
+
+ .cm-tab-close-dot {
+ display: none;
+
+ width: 8px;
+ height: 8px;
+ border-radius: 50%;
+
+ background: ${cssVar.colorPrimary};
+ }
+
+ &[data-dirty='true'] {
+ .cm-tab-close-x {
+ display: none;
+ }
+
+ .cm-tab-close-dot {
+ display: inline-block;
+ }
+ }
+
&:hover {
opacity: 1;
background: ${cssVar.colorFillSecondary};
+
+ .cm-tab-close-x {
+ display: inline-flex;
+ }
+
+ .cm-tab-close-dot {
+ display: none;
+ }
}
`,
tabItem: css`
@@ -108,12 +140,39 @@ const TabStrip = memo(() => {
const { t } = useTranslation('chat');
const openLocalFiles = useChatStore(chatPortalSelectors.openLocalFiles);
const activeLocalFilePath = useChatStore(chatPortalSelectors.activeLocalFilePath);
+ const dirtyContents = useChatStore(chatPortalSelectors.dirtyLocalFileContents);
const setActiveLocalFile = useChatStore((s) => s.setActiveLocalFile);
const closeLocalFileTab = useChatStore((s) => s.closeLocalFileTab);
const closeLeftLocalFileTabs = useChatStore((s) => s.closeLeftLocalFileTabs);
const closeOtherLocalFileTabs = useChatStore((s) => s.closeOtherLocalFileTabs);
const closeRightLocalFileTabs = useChatStore((s) => s.closeRightLocalFileTabs);
+ const confirmClose = useCallback(
+ (filePath: string, perform: () => void) => {
+ if (!(filePath in dirtyContents)) {
+ perform();
+ return;
+ }
+ const filename = filePath.split('/').at(-1) ?? filePath;
+ confirmModal({
+ cancelText: t('cancel', { defaultValue: 'Cancel' }),
+ content: t('workingPanel.localFile.closeDirty.content', {
+ defaultValue: `${filename} has unsaved changes. Close without saving?`,
+ filename,
+ }),
+ okButtonProps: { danger: true },
+ okText: t('workingPanel.localFile.closeDirty.confirm', {
+ defaultValue: 'Close without saving',
+ }),
+ onOk: perform,
+ title: t('workingPanel.localFile.closeDirty.title', {
+ defaultValue: 'Unsaved changes',
+ }),
+ });
+ },
+ [dirtyContents, t],
+ );
+
const getContextMenuItems = useCallback(
(filePath: string, index: number): GenericItemType[] => [
{
@@ -138,7 +197,7 @@ const TabStrip = memo(() => {
{
key: 'close',
label: t('workingPanel.localFile.close'),
- onClick: () => closeLocalFileTab(filePath),
+ onClick: () => confirmClose(filePath, () => closeLocalFileTab(filePath)),
},
],
[
@@ -146,6 +205,7 @@ const TabStrip = memo(() => {
closeLocalFileTab,
closeOtherLocalFileTabs,
closeRightLocalFileTabs,
+ confirmClose,
openLocalFiles.length,
t,
],
@@ -187,13 +247,17 @@ const TabStrip = memo(() => {
<button
aria-label={`Close ${filename}`}
className={styles.tabClose}
+ data-dirty={filePath in dirtyContents ? 'true' : 'false'}
type="button"
onClick={(e) => {
e.stopPropagation();
- closeLocalFileTab(filePath);
+ confirmClose(filePath, () => closeLocalFileTab(filePath));
}}
>
- <XIcon size={12} />
+ <span className={'cm-tab-close-x'}>
+ <XIcon size={12} />
+ </span>
+ <span className={'cm-tab-close-dot'} />
</button>
</div>
</ContextMenuTrigger>
diff --git a/src/store/chat/slices/portal/action.ts b/src/store/chat/slices/portal/action.ts
index 962b01e342e..dc5484f5f90 100644
--- a/src/store/chat/slices/portal/action.ts
+++ b/src/store/chat/slices/portal/action.ts
@@ -1,3 +1,4 @@
+import { localFileService } from '@/services/electron/localFileService';
import { type ChatStore } from '@/store/chat/store';
import { type StoreSetter } from '@/store/types';
import { type PortalArtifact } from '@/types/artifact';
@@ -58,7 +59,7 @@ export class ChatPortalActionImpl {
};
closeLocalFileTab = (filePath: string): void => {
- const { openLocalFiles, activeLocalFilePath } = this.#get();
+ const { openLocalFiles, activeLocalFilePath, dirtyLocalFileContents } = this.#get();
const idx = openLocalFiles.findIndex((f) => f.filePath === filePath);
if (idx === -1) return;
@@ -72,8 +73,18 @@ export class ChatPortalActionImpl {
nextActive = activeLocalFilePath;
}
+ let nextDirty = dirtyLocalFileContents;
+ if (filePath in dirtyLocalFileContents) {
+ const { [filePath]: _, ...rest } = dirtyLocalFileContents;
+ nextDirty = rest;
+ }
+
this.#set(
- { activeLocalFilePath: nextActive, openLocalFiles: nextFiles },
+ {
+ activeLocalFilePath: nextActive,
+ dirtyLocalFileContents: nextDirty,
+ openLocalFiles: nextFiles,
+ },
false,
'closeLocalFileTab',
);
@@ -195,6 +206,31 @@ export class ChatPortalActionImpl {
this.#set({ activeLocalFilePath: filePath }, false, 'setActiveLocalFile');
};
+ setLocalFileBuffer = (filePath: string, content: string | undefined): void => {
+ const { dirtyLocalFileContents } = this.#get();
+ if (content === undefined) {
+ if (!(filePath in dirtyLocalFileContents)) return;
+
+ const { [filePath]: _, ...rest } = dirtyLocalFileContents;
+ this.#set({ dirtyLocalFileContents: rest }, false, 'setLocalFileBuffer/clear');
+ return;
+ }
+ if (dirtyLocalFileContents[filePath] === content) return;
+ this.#set(
+ { dirtyLocalFileContents: { ...dirtyLocalFileContents, [filePath]: content } },
+ false,
+ 'setLocalFileBuffer',
+ );
+ };
+
+ saveLocalFile = async (filePath: string): Promise<string | undefined> => {
+ const { dirtyLocalFileContents } = this.#get();
+ const buffer = dirtyLocalFileContents[filePath];
+ if (buffer === undefined) return undefined;
+ await localFileService.writeFile({ content: buffer, path: filePath });
+ return buffer;
+ };
+
openMessageDetail = (messageId: string): void => {
this.#get().pushPortalView({ messageId, type: PortalViewType.MessageDetail });
};
diff --git a/src/store/chat/slices/portal/initialState.ts b/src/store/chat/slices/portal/initialState.ts
index 15ed370aa4f..d8a27e10a65 100644
--- a/src/store/chat/slices/portal/initialState.ts
+++ b/src/store/chat/slices/portal/initialState.ts
@@ -44,6 +44,9 @@ export interface ChatPortalState {
/** Path of the currently active tab; undefined when no tabs open. */
activeLocalFilePath?: string;
+ /** Unsaved edit buffers keyed by file path. Presence implies the file is dirty. */
+ dirtyLocalFileContents: Record<string, string>;
+
// Legacy fields (kept for backward compatibility during migration)
// TODO: Remove after Phase 3 migration complete
/** Open file tabs in the LocalFile portal. */
@@ -69,6 +72,7 @@ export interface ChatPortalState {
}
export const initialChatPortalState: ChatPortalState = {
+ dirtyLocalFileContents: {},
openLocalFiles: [],
portalArtifactDisplayMode: ArtifactDisplayMode.Preview,
portalStack: [],
diff --git a/src/store/chat/slices/portal/selectors.ts b/src/store/chat/slices/portal/selectors.ts
index 1e411463cc7..9a9ae020c1d 100644
--- a/src/store/chat/slices/portal/selectors.ts
+++ b/src/store/chat/slices/portal/selectors.ts
@@ -148,6 +148,19 @@ const currentLocalFile = (
const localFilePath = (s: ChatStoreState) => currentLocalFile(s)?.filePath;
const localFileWorkingDirectory = (s: ChatStoreState) => currentLocalFile(s)?.workingDirectory;
+const localFileBuffer =
+ (filePath: string | undefined) =>
+ (s: ChatStoreState): string | undefined =>
+ filePath ? s.dirtyLocalFileContents[filePath] : undefined;
+
+const isLocalFileDirty =
+ (filePath: string | undefined) =>
+ (s: ChatStoreState): boolean =>
+ !!filePath && filePath in s.dirtyLocalFileContents;
+
+const dirtyLocalFileContents = (s: ChatStoreState): Record<string, string> =>
+ s.dirtyLocalFileContents;
+
// Message Detail selectors
const messageDetailId = (s: ChatStoreState): string | undefined => {
const view = getViewData(s, PortalViewType.MessageDetail);
@@ -210,6 +223,9 @@ export const chatPortalSelectors = {
// Local file data
activeLocalFilePath,
currentLocalFile,
+ dirtyLocalFileContents,
+ isLocalFileDirty,
+ localFileBuffer,
localFilePath,
localFileWorkingDirectory,
openLocalFiles,