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.

🐛 fix: open active-workspace links in panel, edited-file card clicks (#21308)

Lobehub Coder78b6424a23a0
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index b17a6542e00..46edca7113b 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -403,6 +403,7 @@
"duplicateSession.title": "{{title}} Copy",
"duplicateTitle": "{{title}} Copy",
"editedFiles.hideChanges": "Hide changes",
+ "editedFiles.previewUnavailable": "Preview unavailable",
"editedFiles.showLess": "Show fewer files",
"editedFiles.showMore_one": "Show {{count}} more file",
"editedFiles.showMore_other": "Show {{count}} more files",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 82fa040e617..fff7506fcb7 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -403,6 +403,7 @@
"duplicateSession.title": "{{title}} 副本",
"duplicateTitle": "{{title}} 副本",
"editedFiles.hideChanges": "收起更改",
+ "editedFiles.previewUnavailable": "无法预览",
"editedFiles.showLess": "收起文件",
"editedFiles.showMore_one": "展开另外 {{count}} 个文件",
"editedFiles.showMore_other": "展开另外 {{count}} 个文件",
diff --git a/packages/builtin-tools/src/fileEditScan/index.test.ts b/packages/builtin-tools/src/fileEditScan/index.test.ts
index 07ff854ef03..f9b6414b4f2 100644
--- a/packages/builtin-tools/src/fileEditScan/index.test.ts
+++ b/packages/builtin-tools/src/fileEditScan/index.test.ts
@@ -305,6 +305,83 @@ describe('scanOperationFileEdits', () => {
});
});
+ describe('claude code content snapshots', () => {
+ const ccCall = (
+ toolCallId: string,
+ apiName: 'Edit' | 'MultiEdit' | 'Write',
+ args: Record<string, unknown>,
+ ): FileEditToolCallRecord => ({
+ apiName,
+ arguments: JSON.stringify(args),
+ identifier: 'claude-code',
+ toolCallId,
+ });
+
+ it('turns Write content into a previewable added-lines patch', () => {
+ const [entry] = scanOperationFileEdits([
+ ccCall('t1', 'Write', { content: '# Spec\n\nbody\n', file_path: '/tmp/spec/spec.md' }),
+ ]);
+ expect(entry).toMatchObject({ kind: 'added', linesAdded: 3, linesDeleted: 0 });
+ expect(entry.diffTexts).toEqual([
+ '--- a/tmp/spec/spec.md\n+++ b/tmp/spec/spec.md\n@@ -0,0 +1,3 @@\n+# Spec\n+\n+body',
+ ]);
+ });
+
+ it('turns Edit and MultiEdit replacements into hunks', () => {
+ const result = scanOperationFileEdits([
+ ccCall('t1', 'Edit', { file_path: '/a.md', new_string: 'new', old_string: 'old' }),
+ ccCall('t2', 'MultiEdit', {
+ edits: [
+ { new_string: 'x2', old_string: 'x1' },
+ { new_string: 'y2\ny3', old_string: 'y1' },
+ ],
+ file_path: '/b.md',
+ }),
+ ]);
+ expect(result.map((r) => [r.path, r.linesAdded, r.linesDeleted])).toEqual([
+ ['/a.md', 1, 1],
+ ['/b.md', 3, 2],
+ ]);
+ expect(result[0].diffTexts[0]).toContain('@@ -1,1 +1,1 @@\n-old\n+new');
+ });
+
+ it('counts content lines that look like patch headers', () => {
+ const result = scanOperationFileEdits([
+ ccCall('t1', 'Write', { content: '++counter\n', file_path: '/a.c' }),
+ ccCall('t2', 'Edit', { file_path: '/b.c', new_string: 'x', old_string: '--old' }),
+ ]);
+ expect(result.map((r) => [r.linesAdded, r.linesDeleted])).toEqual([
+ [1, 0],
+ [1, 1],
+ ]);
+ });
+
+ it('leaves replace_all deltas unknown but keeps the snapshot', () => {
+ const [entry] = scanOperationFileEdits([
+ ccCall('t1', 'Edit', {
+ file_path: '/a.ts',
+ new_string: 'next',
+ old_string: 'prev',
+ replace_all: true,
+ }),
+ ]);
+ expect(entry).toMatchObject({ linesAdded: 0, linesDeleted: 0 });
+ expect(entry.diffTexts[0]).toContain('-prev\n+next');
+ });
+
+ it('keeps lines shared by old_string and new_string as context', () => {
+ const [entry] = scanOperationFileEdits([
+ ccCall('t1', 'Edit', {
+ file_path: '/a.md',
+ new_string: 'a\nnew\nb',
+ old_string: 'a\nold\nb',
+ }),
+ ]);
+ expect(entry).toMatchObject({ linesAdded: 1, linesDeleted: 1 });
+ expect(entry.diffTexts[0]).toContain('@@ -1,3 +1,3 @@\n a\n-old\n+new\n b');
+ });
+ });
+
describe('terminal-state folding', () => {
it('folds write + edit + edit on one file (kind added, deltas summed)', () => {
const result = scanOperationFileEdits([
diff --git a/packages/builtin-tools/src/fileEditScan/index.ts b/packages/builtin-tools/src/fileEditScan/index.ts
index 13d3e920639..89f51dcf2e7 100644
--- a/packages/builtin-tools/src/fileEditScan/index.ts
+++ b/packages/builtin-tools/src/fileEditScan/index.ts
@@ -351,20 +351,135 @@ const extractCodexOps = (record: FileEditToolCallRecord): EditOp[] => {
});
};
+const toPatchLines = (text: string) => {
+ const lines = text.split('\n');
+ if (lines.at(-1) === '') lines.pop();
+ return lines;
+};
+
+/** Above this LCS table size an edit is shown as a whole-snippet replacement. */
+const MAX_LCS_CELLS = 1_000_000;
+
+/**
+ * Line diff of an edit's old/new snippets as unified-patch body lines: shared
+ * lines become context (` `) so only real changes count as added/deleted.
+ */
+const diffSnippetLines = (oldLines: string[], newLines: string[]): string[] => {
+ const m = oldLines.length;
+ const n = newLines.length;
+ if (m * n > MAX_LCS_CELLS) {
+ return [...oldLines.map((line) => `-${line}`), ...newLines.map((line) => `+${line}`)];
+ }
+
+ // lcs[i][j] = LCS length of oldLines[i..] and newLines[j..]
+ const lcs = Array.from({ length: m + 1 }, () => Array.from<number>({ length: n + 1 }).fill(0));
+ for (let i = m - 1; i >= 0; i--) {
+ for (let j = n - 1; j >= 0; j--) {
+ lcs[i][j] =
+ oldLines[i] === newLines[j]
+ ? lcs[i + 1][j + 1] + 1
+ : Math.max(lcs[i + 1][j], lcs[i][j + 1]);
+ }
+ }
+
+ const lines: string[] = [];
+ let i = 0;
+ let j = 0;
+ while (i < m || j < n) {
+ if (i < m && j < n && oldLines[i] === newLines[j]) {
+ lines.push(` ${oldLines[i]}`);
+ i += 1;
+ j += 1;
+ } else if (i < m && (j === n || lcs[i + 1][j] >= lcs[i][j + 1])) {
+ lines.push(`-${oldLines[i]}`);
+ i += 1;
+ } else {
+ lines.push(`+${newLines[j]}`);
+ j += 1;
+ }
+ }
+ return lines;
+};
+
+/**
+ * Build a display-only unified patch from Claude Code's own tool arguments
+ * (`Write.content`, `Edit.old_string/new_string`, `MultiEdit.edits[]`). CC
+ * reports no diff of its own, and the file usually lives on the agent's host
+ * (often outside the working directory, e.g. `/tmp/…`) where nothing can read
+ * it back — so this snapshot is the only preview the edited-files card has.
+ * Hunk positions are unknown for edits, so they are numbered from line 1.
+ */
+const buildClaudeCodePatch = (
+ apiName: FileEditToolCallRecord['apiName'],
+ path: string,
+ args: Record<string, unknown>,
+): Pick<EditOpBase, 'diffText' | 'linesAdded' | 'linesDeleted'> | undefined => {
+ const hunks: string[] = [];
+ const edits: unknown[] =
+ apiName === 'Write'
+ ? []
+ : apiName === 'MultiEdit' && Array.isArray(args.edits)
+ ? args.edits
+ : [args];
+
+ if (apiName === 'Write') {
+ const content = typeof args.content === 'string' ? toPatchLines(args.content) : [];
+ if (content.length === 0) return undefined;
+ hunks.push(`@@ -0,0 +1,${content.length} @@`, ...content.map((line) => `+${line}`));
+ } else {
+ for (const edit of edits) {
+ if (!isRecord(edit)) continue;
+ const oldLines = typeof edit.old_string === 'string' ? toPatchLines(edit.old_string) : [];
+ const newLines = typeof edit.new_string === 'string' ? toPatchLines(edit.new_string) : [];
+ if (oldLines.length === 0 && newLines.length === 0) continue;
+ hunks.push(
+ `@@ -1,${oldLines.length} +1,${newLines.length} @@`,
+ ...diffSnippetLines(oldLines, newLines),
+ );
+ }
+ }
+
+ if (hunks.length === 0) return undefined;
+ // Count from the hunk bodies: a content line like `++x` would read as a
+ // `+++` file header once the patch is assembled.
+ let linesAdded = 0;
+ let linesDeleted = 0;
+ for (const line of hunks) {
+ if (line.startsWith('@@')) continue;
+ if (line.startsWith('+')) linesAdded += 1;
+ else if (line.startsWith('-')) linesDeleted += 1;
+ }
+ // `replace_all` applies the hunk at every occurrence, and the arguments do
+ // not say how many there were — leave the counts unknown rather than wrong.
+ const replacesAll = edits.some((edit) => isRecord(edit) && edit.replace_all === true);
+ if (replacesAll) {
+ linesAdded = 0;
+ linesDeleted = 0;
+ }
+ const headerPath = path.replace(/^\/+/, '');
+ return {
+ diffText: [`--- a/${headerPath}`, `+++ b/${headerPath}`, ...hunks].join('\n'),
+ linesAdded,
+ linesDeleted,
+ };
+};
+
const extractClaudeCodeOps = (record: FileEditToolCallRecord): EditOp[] => {
const args = parseArguments(record.arguments);
const path = normalizePath(args?.file_path);
if (!path) return [];
- // CC edit tools surface no line/diff data — record the touch with 0 deltas.
+ const deltas = buildClaudeCodePatch(record.apiName, path, args!) ?? {
+ linesAdded: 0,
+ linesDeleted: 0,
+ };
// Write is create-or-overwrite (ambiguous), Edit/MultiEdit always modify.
if (record.apiName === 'Write') {
- return [{ linesAdded: 0, linesDeleted: 0, path, toolCallId: record.toolCallId, type: 'write' }];
+ return [{ ...deltas, path, toolCallId: record.toolCallId, type: 'write' }];
}
return [
{
+ ...deltas,
kind: 'modified',
- linesAdded: 0,
- linesDeleted: 0,
path,
toolCallId: record.toolCallId,
type: 'change',
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 4fa66a0c32a..4e73f563b09 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -508,6 +508,7 @@ export default {
'editedFiles.title_one': 'Edited {{count}} file',
'editedFiles.title_other': 'Edited {{count}} files',
'editedFiles.hideChanges': 'Hide changes',
+ 'editedFiles.previewUnavailable': 'Preview unavailable',
'editedFiles.showLess': 'Show fewer files',
'editedFiles.showMore_one': 'Show {{count}} more file',
'editedFiles.showMore_other': 'Show {{count}} more files',
diff --git a/src/features/Conversation/Messages/EditedFilesCard/index.test.ts b/src/features/Conversation/Messages/EditedFilesCard/index.test.ts
index cd3b360dafc..4ef6b2739a5 100644
--- a/src/features/Conversation/Messages/EditedFilesCard/index.test.ts
+++ b/src/features/Conversation/Messages/EditedFilesCard/index.test.ts
@@ -125,12 +125,28 @@ describe('EditedFilesCard open action', () => {
// Regression: the share visitor page's portal hosts no LocalFile
// view, so the header click used to push an invisible view and do nothing.
- it('keeps the header inert on the agent-share visitor page, leaving the diff action', () => {
+ // Without a preview it falls back to the diff snapshot instead.
+ it('expands the diff from the header on the agent-share visitor page', () => {
conversationState.context.agentShareId = 'share_1';
useChatStore.setState({ activeTopicId: 'tpc_1' });
render(createElement(EditedFilesCard, { entries: [sandboxEntry] }));
- expect(screen.getByText(singleTitle).closest('[role="button"]')).toBeNull();
- expect(screen.getByRole('button', { name: 'editedFiles.viewChanges' })).toBeInTheDocument();
+ const header = screen.getByText(singleTitle).closest('[role="button"]')!;
+ expect(header).toHaveAttribute('aria-expanded', 'false');
+ fireEvent.click(header);
+ expect(header).toHaveAttribute('aria-expanded', 'true');
+ });
+
+ // Regression (T-965): a Claude Code edit outside the working directory had
+ // neither a preview nor a diff, so its card silently ignored clicks.
+ it('states that a file with no preview and no diff cannot be opened', () => {
+ render(
+ createElement(EditedFilesCard, {
+ entries: [{ ...singleEntry, diffTexts: [], path: '/tmp/spec-20322/spec.md' }],
+ }),
+ );
+
+ expect(screen.queryByRole('button')).toBeNull();
+ expect(screen.getByText('editedFiles.previewUnavailable')).toBeInTheDocument();
});
});
diff --git a/src/features/Conversation/Messages/EditedFilesCard/index.tsx b/src/features/Conversation/Messages/EditedFilesCard/index.tsx
index 68725ade977..e1ce09c8142 100644
--- a/src/features/Conversation/Messages/EditedFilesCard/index.tsx
+++ b/src/features/Conversation/Messages/EditedFilesCard/index.tsx
@@ -299,18 +299,23 @@ const SingleEditedFileCard = memo<{ entry: EditedFileEntry; onOpen?: () => void
const fileName = getFileName(entry.path);
const { displayPath } = getFilePathDisplayInfo(entry.path);
const language = getFileLanguage(entry.path);
+ // Same fallback as a list row: a file nothing can read back (e.g. written
+ // outside the working directory) still opens its diff snapshot, and one
+ // with neither says so instead of swallowing the click.
+ const handleClick = onOpen ?? (hasDiff ? () => setShowDiff((prev) => !prev) : undefined);
return (
<Flexbox className={styles.card}>
<Flexbox
horizontal
align={'center'}
- className={cx(styles.singleHeader, onOpen && styles.singleHeaderClickable)}
+ aria-expanded={onOpen ? undefined : hasDiff ? showDiff : undefined}
+ className={cx(styles.singleHeader, handleClick && styles.singleHeaderClickable)}
gap={10}
- role={onOpen ? 'button' : undefined}
- tabIndex={onOpen ? 0 : undefined}
- onClick={onOpen}
- onKeyDown={onOpen ? toggleOnKey(onOpen) : undefined}
+ role={handleClick ? 'button' : undefined}
+ tabIndex={handleClick ? 0 : undefined}
+ onClick={handleClick}
+ onKeyDown={handleClick ? toggleOnKey(handleClick) : undefined}
>
<FileIcon
fileName={getEditedFileIconName(entry.path)}
@@ -327,6 +332,11 @@ const SingleEditedFileCard = memo<{ entry: EditedFileEntry; onOpen?: () => void
linesDeleted={entry.linesDeleted}
/>
</Flexbox>
+ {!handleClick && (
+ <Text fontSize={12} type={'secondary'}>
+ {t('editedFiles.previewUnavailable')}
+ </Text>
+ )}
{hasDiff && (
<div
data-view-changes
diff --git a/src/features/EntityLink/Render/InternalEntityLink.tsx b/src/features/EntityLink/Render/InternalEntityLink.tsx
index 70b59b9e9c8..710f4590d2f 100644
--- a/src/features/EntityLink/Render/InternalEntityLink.tsx
+++ b/src/features/EntityLink/Render/InternalEntityLink.tsx
@@ -15,7 +15,9 @@ import type { MouseEvent } from 'react';
import { memo, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
+import { getActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';
import { shouldHardNavigateToWorkbench } from '@/libs/next/workbenchNavigation';
import { useClientDataSWR } from '@/libs/swr';
import { useAgentStore } from '@/store/agent';
@@ -155,7 +157,13 @@ export const InternalEntityLink = memo<InternalEntityLinkProps>(({ href, label,
reference.type === 'verify') &&
shouldHardNavigateToWorkbench(reference.pathname)
) {
- window.location.assign(reference.pathname);
+ // A workspace-prefixed path is already scoped; an unprefixed one (or one
+ // whose active slug was normalized away) is scoped like `navigate` does.
+ window.location.assign(
+ reference.workspaceSlug
+ ? reference.pathname
+ : buildWorkspaceAwarePath(reference.pathname, getActiveWorkspaceSlug()),
+ );
return;
}
diff --git a/src/features/EntityLink/Render/index.tsx b/src/features/EntityLink/Render/index.tsx
index 3f8a7d472d3..b2139978794 100644
--- a/src/features/EntityLink/Render/index.tsx
+++ b/src/features/EntityLink/Render/index.tsx
@@ -4,6 +4,7 @@ import { Github } from '@lobehub/icons';
import { Mail } from 'lucide-react';
import { memo } from 'react';
+import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
import { useWorkspaces } from '@/business/client/hooks/useWorkspaces';
import { useUserStore } from '@/store/user';
import { userGeneralSettingsSelectors } from '@/store/user/selectors';
@@ -22,12 +23,14 @@ const Render = memo<EntityLinkElementProps>(({ node }) => {
const { linkHref, linkKind, linkLabel, linkDomain } = properties;
const showIcon = useUserStore(userGeneralSettingsSelectors.enableMessageLinkIcon);
const workspaces = useWorkspaces();
+ const activeWorkspaceSlug = useActiveWorkspaceSlug();
const label = linkLabel || linkHref || '';
const internalReference = parseInternalLink(
linkHref,
typeof window === 'undefined' ? undefined : window.location.origin,
workspaces.map((workspace) => workspace.slug),
+ activeWorkspaceSlug,
);
if (linkHref && internalReference) {
diff --git a/src/features/EntityLink/internalLink.test.ts b/src/features/EntityLink/internalLink.test.ts
index 4779956fc0f..ebfbcbcea2d 100644
--- a/src/features/EntityLink/internalLink.test.ts
+++ b/src/features/EntityLink/internalLink.test.ts
@@ -121,6 +121,32 @@ describe('parseInternalLink', () => {
});
});
+ it('normalizes away the active workspace slug so the link opens in-context', () => {
+ expect(
+ parseInternalLink(
+ 'https://app.lobehub.com/lobehub/page/docs_LgOiA6TLUUKQro6L',
+ 'app://renderer',
+ ['lobehub'],
+ 'lobehub',
+ ),
+ ).toEqual({
+ documentId: 'docs_LgOiA6TLUUKQro6L',
+ pathname: '/page/docs_LgOiA6TLUUKQro6L',
+ type: 'document',
+ });
+ });
+
+ it('keeps the slug of a workspace other than the active one', () => {
+ expect(
+ parseInternalLink(
+ '/lobe-team/page/docs_document',
+ undefined,
+ ['lobe-team', 'lobehub'],
+ 'lobehub',
+ ),
+ ).toMatchObject({ pathname: '/lobe-team/page/docs_document', workspaceSlug: 'lobe-team' });
+ });
+
it('accepts the current self-hosted origin', () => {
expect(
parseInternalLink('https://chat.example.com/task/T-200', 'https://chat.example.com'),
diff --git a/src/features/EntityLink/internalLink.ts b/src/features/EntityLink/internalLink.ts
index 978a7116897..78b6bfedef3 100644
--- a/src/features/EntityLink/internalLink.ts
+++ b/src/features/EntityLink/internalLink.ts
@@ -96,11 +96,38 @@ export const isBareLinkLabel = (label: string, href: string) => label === href;
export const isEntityIdLabel = (label: string, reference: InternalLinkReference) =>
reference.type === 'goal' && label === reference.goalId;
-/** Parse a LobeHub route into a semantic entity reference. */
+/**
+ * Parse a LobeHub route into a semantic entity reference.
+ *
+ * A link scoped to the active workspace (`/lobehub/page/...` while `lobehub`
+ * is active) addresses the same scope as an unprefixed one, so its slug is
+ * normalized away: it then opens in-context like any same-scope entity instead
+ * of escaping to a full-page navigation.
+ */
export const parseInternalLink = (
href: string | undefined,
currentOrigin?: string,
workspaceSlugs: readonly string[] = [],
+ activeWorkspaceSlug?: string | null,
+): InternalLinkReference | null => {
+ const reference = parseInternalLinkReference(href, currentOrigin, workspaceSlugs);
+ if (!reference?.workspaceSlug || reference.workspaceSlug !== activeWorkspaceSlug) {
+ return reference;
+ }
+
+ const { workspaceSlug, ...rest } = reference;
+ const prefix = `/${workspaceSlug}`;
+ const pathname = rest.pathname.startsWith(`${prefix}/`)
+ ? rest.pathname.slice(prefix.length)
+ : rest.pathname;
+
+ return { ...rest, pathname } as InternalLinkReference;
+};
+
+const parseInternalLinkReference = (
+ href: string | undefined,
+ currentOrigin: string | undefined,
+ workspaceSlugs: readonly string[],
): InternalLinkReference | null => {
if (!href) return null;