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(gateway): keep input loading on through execAgentTask round-trip (#14503)

Arvin Xu1e2782ece4b7
diff --git a/apps/desktop/src/main/controllers/GitCtr.ts b/apps/desktop/src/main/controllers/GitCtr.ts
index 6158f76e768..f2f098ce239 100644
--- a/apps/desktop/src/main/controllers/GitCtr.ts
+++ b/apps/desktop/src/main/controllers/GitCtr.ts
@@ -4,7 +4,9 @@ import path from 'node:path';
import { promisify } from 'node:util';
import type {
+ GetGitBranchDiffPayload,
GitAheadBehind,
+ GitBranchDiffPatches,
GitBranchInfo,
GitBranchListItem,
GitCheckoutResult,
@@ -12,6 +14,7 @@ import type {
GitLinkedPullRequestResult,
GitPullResult,
GitPushResult,
+ GitRemoteBranchListItem,
GitWorkingTreeFiles,
GitWorkingTreePatch,
GitWorkingTreePatches,
@@ -152,6 +155,21 @@ export const quoteGitPath = (prefix: 'a/' | 'b/', filePath: string): string => {
return out + '"';
};
+/**
+ * Status from a single diff block's preamble: `new file mode` → added,
+ * `deleted file mode` → deleted, otherwise modified. Used by branch-diff mode
+ * where there's no `git status` to consult — the diff itself is the source.
+ */
+const detectDiffBlockStatus = (block: string): GitFileDiffStatus => {
+ // Only scan up to the first hunk / binary marker so huge bodies aren't walked.
+ for (const line of block.split('\n')) {
+ if (line.startsWith('new file mode ')) return 'added';
+ if (line.startsWith('deleted file mode ')) return 'deleted';
+ if (line.startsWith('@@') || line.startsWith('Binary files ')) break;
+ }
+ return 'modified';
+};
+
/** Walk a patch counting `+`/`-` lines while skipping `+++`/`---` headers. */
const countAddDel = (patch: string): { additions: number; deletions: number } => {
let additions = 0;
@@ -556,6 +574,54 @@ export default class GitController extends ControllerModule {
}
}
+ /**
+ * List remote branches under `refs/remotes/origin/*`, ordered by most
+ * recent commit. The `HEAD` symref is filtered out and the resolved
+ * default branch is flagged via `isDefault` so the UI can render it
+ * with a marker. Used by the Review panel's branch-compare picker.
+ */
+ @IpcMethod()
+ async listGitRemoteBranches(dirPath: string): Promise<GitRemoteBranchListItem[]> {
+ const execFileAsync = promisify(execFile);
+ let defaultRef: string | undefined;
+ try {
+ const { stdout } = await execFileAsync(
+ 'git',
+ ['symbolic-ref', '--short', 'refs/remotes/origin/HEAD'],
+ { cwd: dirPath, timeout: 5000 },
+ );
+ defaultRef = stdout.trim() || undefined;
+ } catch {
+ defaultRef = undefined;
+ }
+ try {
+ const { stdout } = await execFileAsync(
+ 'git',
+ [
+ 'for-each-ref',
+ '--sort=-committerdate',
+ '--format=%(refname:short)',
+ 'refs/remotes/origin',
+ ],
+ { cwd: dirPath, timeout: 5000 },
+ );
+ return stdout
+ .replaceAll('\r', '')
+ .split('\n')
+ .map((line) => line.trim())
+ .filter((name) => name.length > 0 && name !== 'origin/HEAD' && !name.endsWith('/HEAD'))
+ .map((name) => ({ isDefault: name === defaultRef, name }));
+ } catch (error: any) {
+ logger.warn('[listGitRemoteBranches] git command failed', {
+ code: error?.code,
+ cwd: dirPath,
+ message: error?.message,
+ stderr: error?.stderr?.toString?.() ?? error?.stderr,
+ });
+ return [];
+ }
+ }
+
/**
* Bucket dirty files into added / modified / deleted via `git status --porcelain -z`.
* Each file is counted once: untracked (`??`) and staged-add (`A`) → added,
@@ -791,6 +857,99 @@ export default class GitController extends ControllerModule {
return { patches: allPatches };
}
+ /**
+ * Diff every changed file between the current HEAD and the remote default
+ * branch (resolved via `refs/remotes/origin/HEAD` — typically `origin/main`
+ * or `origin/canary`). Uses `<base>...HEAD` so the result is "what this
+ * branch added since it forked", ignoring upstream-only commits.
+ *
+ * Best-effort `git fetch` first so the comparison reflects the latest
+ * remote state; fetch failures (offline / no creds / no `origin`) are
+ * swallowed and we fall back to whatever cached refs exist. Returns
+ * `baseRef: undefined` + empty patches when no remote default is set —
+ * the renderer surfaces a "noBaseRef" hint in that case.
+ *
+ * Patch parsing reuses the same bulk-split + size-cap path as the working
+ * tree variant; status comes from each diff block's preamble (no `git
+ * status` cross-reference needed since every block is from history).
+ */
+ @IpcMethod()
+ async getGitBranchDiff(payload: GetGitBranchDiffPayload): Promise<GitBranchDiffPatches> {
+ const { path: dirPath, baseRef: baseRefOverride } = payload;
+ const MAX_PATCH_BYTES = 256 * 1024;
+ const execFileAsync = promisify(execFile);
+
+ // Step 1 — best-effort fetch so origin/<default> reflects remote HEAD.
+ try {
+ await execFileAsync('git', ['fetch', '--no-tags', '--quiet', 'origin'], {
+ cwd: dirPath,
+ timeout: 10_000,
+ });
+ } catch {
+ // swallow — fall through to cached refs
+ }
+
+ // Step 2 — pick the comparison base. When the caller passes an explicit
+ // override (e.g. user picked a non-default branch in the UI) we trust it;
+ // otherwise we resolve `refs/remotes/origin/HEAD`. The default may be
+ // missing on repos cloned with --no-checkout or after a remote rename —
+ // surface a "noBaseRef" empty state in that case so the user can run
+ // `git remote set-head origin --auto` themselves.
+ let baseRef: string | undefined = baseRefOverride;
+ if (!baseRef) {
+ try {
+ const { stdout } = await execFileAsync(
+ 'git',
+ ['symbolic-ref', '--short', 'refs/remotes/origin/HEAD'],
+ { cwd: dirPath, timeout: 5000 },
+ );
+ baseRef = stdout.trim() || undefined;
+ } catch {
+ baseRef = undefined;
+ }
+ }
+
+ // headRef populated even when baseRef is missing so the UI can still
+ // surface "fix/foo ← ?" instead of going completely blank.
+ const headRef = (await this.getGitBranch(dirPath)).branch;
+
+ if (!baseRef) {
+ return { headRef, patches: [] };
+ }
+
+ // Step 3 — single bulk diff against the merge base. Three-dot semantics
+ // (`base...HEAD`) ignore commits added to base after the branch forked,
+ // matching what users expect from "compare branch" UI on GitHub. Stream
+ // capture mirrors the working-tree path so multi-MB diffs land intact.
+ let bulkDiff = '';
+ try {
+ bulkDiff = await runGitCaptureStream(
+ dirPath,
+ ['-c', 'core.quotepath=off', 'diff', '--no-color', `${baseRef}...HEAD`],
+ 30_000,
+ );
+ } catch (error: any) {
+ logger.warn('[getGitBranchDiff] diff failed', {
+ baseRef,
+ cwd: dirPath,
+ stderr: error?.stderr?.toString?.() ?? error?.stderr,
+ });
+ if (typeof error?.partialStdout === 'string') bulkDiff = error.partialStdout;
+ }
+
+ // Step 4 — split + classify per-file from the diff preamble alone.
+ const patches: GitWorkingTreePatch[] = [];
+ for (const block of splitBulkDiff(bulkDiff)) {
+ const status = detectDiffBlockStatus(block.patch);
+ patches.push(buildTrackedPatch({ filePath: block.path, status }, block, MAX_PATCH_BYTES));
+ }
+
+ const order: Record<GitFileDiffStatus, number> = { added: 0, modified: 1, deleted: 2 };
+ patches.sort((a, b) => order[a.status] - order[b.status]);
+
+ return { baseRef, headRef, patches };
+ }
+
/**
* Count commits HEAD is ahead/behind its upstream tracking ref.
* Returns `hasUpstream: false` when the branch has no upstream configured
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index cd33005308e..271a6de91d8 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -857,13 +857,21 @@
"workingPanel.resources.updatedAt": "Updated {{time}}",
"workingPanel.resources.viewMode.list": "List view",
"workingPanel.resources.viewMode.tree": "Tree view",
+ "workingPanel.review.baseRef.default": "default",
+ "workingPanel.review.baseRef.loading": "Loading branches…",
+ "workingPanel.review.baseRef.reset": "Reset to default branch",
+ "workingPanel.review.baseRef.unresolved": "Pick a base branch",
"workingPanel.review.binary": "Binary file — diff not shown",
"workingPanel.review.collapseAll": "Collapse all",
"workingPanel.review.copied": "Path copied",
"workingPanel.review.copyPath": "Copy file path",
"workingPanel.review.empty": "No working tree changes",
+ "workingPanel.review.empty.branch": "No changes vs {{baseRef}}",
+ "workingPanel.review.empty.noBaseRef": "Couldn't determine the remote default branch. Run `git remote set-head origin --auto` in your terminal.",
"workingPanel.review.error": "Couldn't load this file's diff",
"workingPanel.review.expandAll": "Expand all",
+ "workingPanel.review.mode.branch": "Branch",
+ "workingPanel.review.mode.unstaged": "Unstaged",
"workingPanel.review.more": "More options",
"workingPanel.review.refresh": "Refresh",
"workingPanel.review.textDiff.disable": "Disable inline text diff",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index ecbe5b49efc..0dcde83e997 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -857,13 +857,21 @@
"workingPanel.resources.updatedAt": "更新于 {{time}}",
"workingPanel.resources.viewMode.list": "列表视图",
"workingPanel.resources.viewMode.tree": "树状视图",
+ "workingPanel.review.baseRef.default": "默认",
+ "workingPanel.review.baseRef.loading": "正在加载分支…",
+ "workingPanel.review.baseRef.reset": "恢复默认分支",
+ "workingPanel.review.baseRef.unresolved": "选择对比分支",
"workingPanel.review.binary": "二进制文件,无法展示 diff",
"workingPanel.review.collapseAll": "全部折叠",
"workingPanel.review.copied": "路径已复制",
"workingPanel.review.copyPath": "复制文件路径",
"workingPanel.review.empty": "工作区没有未提交的变更",
+ "workingPanel.review.empty.branch": "和 {{baseRef}} 没有差异",
+ "workingPanel.review.empty.noBaseRef": "未找到远端默认分支,请在终端执行 `git remote set-head origin --auto`",
"workingPanel.review.error": "无法加载该文件的 diff",
"workingPanel.review.expandAll": "全部展开",
+ "workingPanel.review.mode.branch": "分支",
+ "workingPanel.review.mode.unstaged": "未暂存",
"workingPanel.review.more": "更多选项",
"workingPanel.review.refresh": "同步",
"workingPanel.review.textDiff.disable": "关闭文字差异",
diff --git a/packages/electron-client-ipc/src/types/git.ts b/packages/electron-client-ipc/src/types/git.ts
index 25780b7f75c..153feca4fd0 100644
--- a/packages/electron-client-ipc/src/types/git.ts
+++ b/packages/electron-client-ipc/src/types/git.ts
@@ -82,6 +82,42 @@ export interface GitWorkingTreePatches {
patches: GitWorkingTreePatch[];
}
+export interface GitRemoteBranchListItem {
+ /** Whether this ref is the resolved default branch (origin/HEAD target). */
+ isDefault: boolean;
+ /** Short ref name, e.g. `origin/canary`. */
+ name: string;
+}
+
+export interface GetGitBranchDiffPayload {
+ /**
+ * Override the comparison base. When omitted, the controller resolves
+ * `refs/remotes/origin/HEAD` and uses that.
+ */
+ baseRef?: string;
+ path: string;
+}
+
+export interface GitBranchDiffPatches {
+ /**
+ * Resolved base ref the diff was taken against (e.g. `origin/canary`).
+ * Undefined when no remote default branch could be resolved — in that case
+ * `patches` is empty and the UI should show a `noBaseRef` empty state.
+ */
+ baseRef?: string;
+ /**
+ * Current branch short name (e.g. `fix/gateway-loading-flicker`), or short
+ * SHA when HEAD is detached. Lets the UI render a GitHub-style
+ * `<headRef> → <baseRef>` compare label without a second IPC round-trip.
+ */
+ headRef?: string;
+ /**
+ * Per-file diff blocks, ordered added → modified → deleted. Same shape as
+ * GitWorkingTreePatch so the renderer can reuse the existing PatchDiff path.
+ */
+ patches: GitWorkingTreePatch[];
+}
+
export interface GitCheckoutResult {
error?: string;
success: boolean;
diff --git a/src/locales/default/chat.ts b/src/locales/default/chat.ts
index afd1245926b..27180aea622 100644
--- a/src/locales/default/chat.ts
+++ b/src/locales/default/chat.ts
@@ -914,13 +914,22 @@ export default {
'workingPanel.resources.updatedAt': 'Updated {{time}}',
'workingPanel.resources.viewMode.list': 'List view',
'workingPanel.resources.viewMode.tree': 'Tree view',
+ 'workingPanel.review.baseRef.default': 'default',
+ 'workingPanel.review.baseRef.loading': 'Loading branches…',
+ 'workingPanel.review.baseRef.reset': 'Reset to default branch',
+ 'workingPanel.review.baseRef.unresolved': 'Pick a base branch',
'workingPanel.review.binary': 'Binary file — diff not shown',
'workingPanel.review.collapseAll': 'Collapse all',
'workingPanel.review.copied': 'Path copied',
'workingPanel.review.copyPath': 'Copy file path',
'workingPanel.review.empty': 'No working tree changes',
+ 'workingPanel.review.empty.branch': 'No changes vs {{baseRef}}',
+ 'workingPanel.review.empty.noBaseRef':
+ "Couldn't determine the remote default branch. Run `git remote set-head origin --auto` in your terminal.",
'workingPanel.review.error': "Couldn't load this file's diff",
'workingPanel.review.expandAll': 'Expand all',
+ 'workingPanel.review.mode.branch': 'Branch',
+ 'workingPanel.review.mode.unstaged': 'Unstaged',
'workingPanel.review.more': 'More options',
'workingPanel.review.refresh': 'Refresh',
'workingPanel.review.textDiff.disable': 'Disable inline text diff',
diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/index.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/index.tsx
index 6cb442a85ca..36e76dd0a0b 100644
--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/index.tsx
+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/index.tsx
@@ -1,9 +1,10 @@
'use client';
import { ActionIcon, Center, Collapse, Empty, Flexbox } from '@lobehub/ui';
-import { Dropdown, type MenuProps, Spin } from 'antd';
+import { Dropdown, type MenuProps } from 'antd';
import { createStaticStyles } from 'antd-style';
import {
+ ArrowLeftIcon,
ChevronDownIcon,
ChevronRightIcon,
Columns2Icon,
@@ -11,6 +12,7 @@ import {
GitCompareIcon,
MoreHorizontalIcon,
RefreshCwIcon,
+ RotateCcwIcon,
Rows2Icon,
UnfoldVerticalIcon,
WholeWordIcon,
@@ -19,14 +21,17 @@ import {
import { memo, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';
import { useLocalStorageState } from '@/hooks/useLocalStorageState';
import FileItemBody, { FileItemHeader } from './FileItem';
-import { useWorkingTreePatches } from './useWorkingTreePatches';
+import { type ReviewMode, useGitRemoteBranches, useReviewPatches } from './useReviewPatches';
const WORD_WRAP_STORAGE_KEY = 'lobechat-review-word-wrap';
const TEXT_DIFF_STORAGE_KEY = 'lobechat-review-text-diff';
const VIEW_MODE_STORAGE_KEY = 'lobechat-review-view-mode';
+const REVIEW_MODE_STORAGE_KEY = 'lobechat-review-mode';
+const BASE_REF_OVERRIDES_STORAGE_KEY = 'lobechat-review-base-overrides';
interface ReviewProps {
workingDirectory: string;
@@ -42,20 +47,9 @@ const itemKey = (entry: { filePath: string; status: string }) =>
const styles = createStaticStyles(({ css, cssVar }) => ({
caret: css`
+ flex-shrink: 0;
color: ${cssVar.colorTextTertiary};
`,
- count: css`
- padding-block: 1px;
- padding-inline: 6px;
- border-radius: 999px;
-
- font-family: ${cssVar.fontFamilyCode};
- font-size: 11px;
- font-variant-numeric: tabular-nums;
- color: ${cssVar.colorTextSecondary};
-
- background: ${cssVar.colorFillTertiary};
- `,
totalAdditions: css`
color: ${cssVar.colorSuccess};
`,
@@ -64,6 +58,7 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
`,
totalStats: css`
display: inline-flex;
+ flex-shrink: 0;
gap: 6px;
align-items: center;
@@ -97,13 +92,86 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
min-width: 0 !important;
}
`,
+ arrow: css`
+ flex-shrink: 0;
+ color: ${cssVar.colorTextTertiary};
+ `,
+ basePicker: css`
+ cursor: pointer;
+ user-select: none;
+
+ overflow: hidden;
+ display: inline-flex;
+ flex: 0 1 auto;
+ gap: 4px;
+ align-items: center;
+
+ min-width: 0;
+ padding-block: 1px;
+ padding-inline: 6px;
+ border-radius: 4px;
+
+ transition: background 0.15s;
+
+ &:hover {
+ background: ${cssVar.colorFillTertiary};
+ }
+ `,
+ compareChip: css`
+ overflow: hidden;
+ display: inline-flex;
+ flex: 0 1 auto;
+ gap: 6px;
+ align-items: center;
+
+ min-width: 0;
+ `,
+ headRefText: css`
+ overflow: hidden;
+ flex: 0 1 auto;
+
+ min-width: 0;
+ padding-inline-end: 4px;
+
+ font-family: ${cssVar.fontFamilyCode};
+ font-size: 12px;
+ color: ${cssVar.colorTextSecondary};
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+ refName: css`
+ overflow: hidden;
+ flex: 0 1 auto;
+
+ min-width: 0;
+
+ font-family: ${cssVar.fontFamilyCode};
+ font-size: 12px;
+ color: ${cssVar.colorText};
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
scopeChip: css`
+ cursor: pointer;
+ user-select: none;
+
display: inline-flex;
+ flex-shrink: 0;
gap: 6px;
align-items: center;
+ padding-block: 2px;
+ padding-inline: 6px;
+ border-radius: 4px;
+
font-size: 12px;
color: ${cssVar.colorTextSecondary};
+
+ transition: background 0.15s;
+
+ &:hover {
+ background: ${cssVar.colorFillTertiary};
+ }
`,
subheader: css`
display: flex;
@@ -119,10 +187,40 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
const Review = memo<ReviewProps>(({ workingDirectory }) => {
const { t } = useTranslation('chat');
- const { data, isLoading, isValidating, mutate } = useWorkingTreePatches(workingDirectory);
+ const [mode, setMode] = useLocalStorageState<ReviewMode>(REVIEW_MODE_STORAGE_KEY, 'unstaged');
+ // Per-repo base-ref override — when set, the branch diff compares against
+ // this ref instead of `origin/HEAD`. Stored as a single keyed object so we
+ // don't proliferate localStorage keys across repos.
+ const [baseOverrides, setBaseOverrides] = useLocalStorageState<Record<string, string>>(
+ BASE_REF_OVERRIDES_STORAGE_KEY,
+ {},
+ );
+ const baseOverride = baseOverrides[workingDirectory];
+ const setBaseOverride = (next: string | undefined) => {
+ setBaseOverrides((prev) => {
+ const updated = { ...prev };
+ if (next === undefined) delete updated[workingDirectory];
+ else updated[workingDirectory] = next;
+ return updated;
+ });
+ };
+
+ const { data, isLoading, isValidating, mutate } = useReviewPatches(
+ workingDirectory,
+ mode,
+ baseOverride,
+ );
+ // Lazy: only fetch remote branches list once the user opens the picker.
+ const [basePickerOpen, setBasePickerOpen] = useState(false);
+ const { data: remoteBranches } = useGitRemoteBranches(
+ workingDirectory,
+ mode === 'branch' && basePickerOpen,
+ );
// Memo-stabilise the fallback so downstream useMemo deps don't flap on
// every render while the SWR result is undefined.
const patches = useMemo(() => data?.patches ?? [], [data]);
+ const baseRef = data?.mode === 'branch' ? data.baseRef : undefined;
+ const headRef = data?.mode === 'branch' ? data.headRef : undefined;
const [viewMode, setViewMode] = useLocalStorageState<'unified' | 'split'>(
VIEW_MODE_STORAGE_KEY,
'unified',
@@ -159,15 +257,7 @@ const Review = memo<ReviewProps>(({ workingDirectory }) => {
if (!data && isLoading) {
return (
<Center flex={1}>
- <Spin />
- </Center>
- );
- }
-
- if (patches.length === 0) {
- return (
- <Center flex={1} gap={8} paddingBlock={24}>
- <Empty description={t('workingPanel.review.empty')} icon={GitCompareIcon} />
+ <NeuralNetworkLoading size={48} />
</Center>
);
}
@@ -248,15 +338,107 @@ const Review = memo<ReviewProps>(({ workingDirectory }) => {
},
];
+ const modeMenuItems: MenuProps['items'] = [
+ {
+ key: 'unstaged',
+ label: t('workingPanel.review.mode.unstaged'),
+ onClick: () => setMode('unstaged'),
+ },
+ {
+ key: 'branch',
+ label: t('workingPanel.review.mode.branch'),
+ onClick: () => setMode('branch'),
+ },
+ ];
+
+ // Branches are only loaded after the user opens the picker (see
+ // `basePickerOpen`). While loading, render a single disabled placeholder
+ // so the menu doesn't pop empty + jump to its final size.
+ const baseRefMenuItems: MenuProps['items'] = remoteBranches
+ ? [
+ ...remoteBranches.map((branch) => ({
+ key: branch.name,
+ label: branch.isDefault
+ ? `${branch.name} · ${t('workingPanel.review.baseRef.default')}`
+ : branch.name,
+ onClick: () =>
+ setBaseOverride(branch.isDefault && !baseOverride ? undefined : branch.name),
+ })),
+ ...(baseOverride
+ ? [
+ { type: 'divider' as const },
+ {
+ icon: <RotateCcwIcon size={14} />,
+ key: 'reset',
+ label: t('workingPanel.review.baseRef.reset'),
+ onClick: () => setBaseOverride(undefined),
+ },
+ ]
+ : []),
+ ]
+ : [
+ {
+ disabled: true,
+ key: 'loading',
+ label: t('workingPanel.review.baseRef.loading'),
+ },
+ ];
+
+ const isEmpty = patches.length === 0;
+ const emptyText =
+ mode === 'branch'
+ ? baseRef
+ ? t('workingPanel.review.empty.branch', { baseRef })
+ : t('workingPanel.review.empty.noBaseRef')
+ : t('workingPanel.review.empty');
+
return (
<Flexbox style={{ overflow: 'hidden' }} width={'100%'}>
<div className={styles.subheader}>
- <Flexbox horizontal align={'center'} gap={8}>
- <span className={styles.scopeChip}>
- {t('workingPanel.review.unstaged')}
- <span className={styles.count}>{patches.length}</span>
- <ChevronDownIcon className={styles.caret} size={12} />
- </span>
+ <Flexbox
+ horizontal
+ align={'center'}
+ gap={8}
+ style={{ flex: '1 1 auto', minWidth: 0, overflow: 'hidden' }}
+ >
+ <Dropdown
+ menu={{ items: modeMenuItems, selectedKeys: [mode] }}
+ placement={'bottomLeft'}
+ trigger={['click']}
+ >
+ <span className={styles.scopeChip} role={'button'} tabIndex={0}>
+ {mode === 'branch'
+ ? t('workingPanel.review.mode.branch')
+ : t('workingPanel.review.mode.unstaged')}
+ <ChevronDownIcon className={styles.caret} size={12} />
+ </span>
+ </Dropdown>
+ {mode === 'branch' && (baseRef || headRef) && (
+ <span className={styles.compareChip}>
+ <Dropdown
+ placement={'bottomLeft'}
+ trigger={['click']}
+ menu={{
+ items: baseRefMenuItems,
+ selectedKeys: baseRef ? [baseRef] : [],
+ }}
+ onOpenChange={setBasePickerOpen}
+ >
+ <span className={styles.basePicker} role={'button'} tabIndex={0}>
+ <span className={styles.refName}>
+ {baseRef ?? t('workingPanel.review.baseRef.unresolved')}
+ </span>
+ <ChevronDownIcon className={styles.caret} size={12} />
+ </span>
+ </Dropdown>
+ {headRef && (
+ <>
+ <ArrowLeftIcon className={styles.arrow} size={12} />
+ <span className={styles.headRefText}>{headRef}</span>
+ </>
+ )}
+ </span>
+ )}
{(totals.additions > 0 || totals.deletions > 0) && (
<span className={styles.totalStats}>
{totals.additions > 0 && (
@@ -269,16 +451,18 @@ const Review = memo<ReviewProps>(({ workingDirectory }) => {
)}
</Flexbox>
<Flexbox horizontal align={'center'} gap={2}>
- <ActionIcon
- icon={allExpanded ? FoldVerticalIcon : UnfoldVerticalIcon}
- size={'small'}
- title={
- allExpanded
- ? t('workingPanel.review.collapseAll')
- : t('workingPanel.review.expandAll')
- }
- onClick={handleToggleAll}
- />
+ {!isEmpty && (
+ <ActionIcon
+ icon={allExpanded ? FoldVerticalIcon : UnfoldVerticalIcon}
+ size={'small'}
+ title={
+ allExpanded
+ ? t('workingPanel.review.collapseAll')
+ : t('workingPanel.review.expandAll')
+ }
+ onClick={handleToggleAll}
+ />
+ )}
<Dropdown menu={{ items: moreMenuItems }} placement={'bottomRight'} trigger={['click']}>
<ActionIcon
icon={MoreHorizontalIcon}
@@ -289,32 +473,38 @@ const Review = memo<ReviewProps>(({ workingDirectory }) => {
</Dropdown>
</Flexbox>
</div>
- <Flexbox
- className={styles.list}
- gap={6}
- paddingInline={8}
- style={{ overflow: 'auto' }}
- width={'100%'}
- >
- <Collapse
- activeKey={activeKeys}
- expandIconPlacement={'end'}
- items={items}
- padding={{ body: 0, header: '6px 12px' }}
- variant={'outlined'}
- expandIcon={({ isActive }) => (
- <ChevronRightIcon
- size={14}
- style={{
- color: 'var(--ant-color-text-tertiary)',
- transform: isActive ? 'rotate(90deg)' : 'rotate(0deg)',
- transition: 'transform 0.2s',
- }}
- />
- )}
- onChange={(next) => setActiveKeys(Array.isArray(next) ? next : [next])}
- />
- </Flexbox>
+ {isEmpty ? (
+ <Center flex={1} gap={8} paddingBlock={24}>
+ <Empty description={emptyText} icon={GitCompareIcon} />
+ </Center>
+ ) : (
+ <Flexbox
+ className={styles.list}
+ gap={6}
+ paddingInline={8}
+ style={{ overflow: 'auto' }}
+ width={'100%'}
+ >
+ <Collapse
+ activeKey={activeKeys}
+ expandIconPlacement={'end'}
+ items={items}
+ padding={{ body: 0, header: '6px 12px' }}
+ variant={'outlined'}
+ expandIcon={({ isActive }) => (
+ <ChevronRightIcon
+ size={14}
+ style={{
+ color: 'var(--ant-color-text-tertiary)',
+ transform: isActive ? 'rotate(90deg)' : 'rotate(0deg)',
+ transition: 'transform 0.2s',
+ }}
+ />
+ )}
+ onChange={(next) => setActiveKeys(Array.isArray(next) ? next : [next])}
+ />
+ </Flexbox>
+ )}
</Flexbox>
);
});
diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/useReviewPatches.ts b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/useReviewPatches.ts
new file mode 100644
index 00000000000..96c921c6a8a
--- /dev/null
+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/useReviewPatches.ts
@@ -0,0 +1,74 @@
+import { isDesktop } from '@lobechat/const';
+import type { GitWorkingTreePatch } from '@lobechat/electron-client-ipc';
+
+import { useClientDataSWR } from '@/libs/swr';
+import { electronGitService } from '@/services/electron/git';
+
+export type ReviewMode = 'unstaged' | 'branch';
+
+export interface ReviewPatchesData {
+ baseRef?: string;
+ headRef?: string;
+ mode: ReviewMode;
+ patches: GitWorkingTreePatch[];
+}
+
+const fetchUnstaged = async (dirPath: string): Promise<ReviewPatchesData> => {
+ const result = await electronGitService.getGitWorkingTreePatches(dirPath);
+ return { mode: 'unstaged', patches: result.patches };
+};
+
+const fetchBranch = async (
+ dirPath: string,
+ baseRef: string | undefined,
+): Promise<ReviewPatchesData> => {
+ const result = await electronGitService.getGitBranchDiff({ baseRef, path: dirPath });
+ return {
+ baseRef: result.baseRef,
+ headRef: result.headRef,
+ mode: 'branch',
+ patches: result.patches,
+ };
+};
+
+/**
+ * Single SWR entry point for the Review panel — `mode` and `baseRef` both
+ * participate in the cache key so switching modes or picking a different
+ * comparison base swaps cleanly without clobbering other tabs' data.
+ *
+ * Branch mode runs `git fetch` inside the controller, so we throttle focus
+ * revalidation more aggressively there to avoid hitting the network on
+ * every window refocus.
+ */
+export const useReviewPatches = (
+ dirPath: string | undefined,
+ mode: ReviewMode,
+ baseRef?: string,
+) => {
+ const enabled = isDesktop && Boolean(dirPath);
+ const key = enabled ? ['git-review-patches', dirPath, mode, baseRef ?? ''] : null;
+
+ return useClientDataSWR<ReviewPatchesData>(
+ key,
+ () => (mode === 'branch' ? fetchBranch(dirPath!, baseRef) : fetchUnstaged(dirPath!)),
+ {
+ focusThrottleInterval: mode === 'branch' ? 30 * 1000 : 5 * 1000,
+ revalidateOnFocus: true,
+ shouldRetryOnError: false,
+ },
+ );
+};
+
+/**
+ * Lazy-loaded list of remote branches under `refs/remotes/origin/*`,
+ * keyed by working directory. Used to populate the base-ref picker in the
+ * Review panel. Stays disabled until `enabled` flips true so we don't fork
+ * a `git for-each-ref` until the user actually opens the dropdown.
+ */
+export const useGitRemoteBranches = (dirPath: string | undefined, enabled: boolean) => {
+ const key = isDesktop && dirPath && enabled ? ['git-remote-branches', dirPath] : null;
+ return useClientDataSWR(key, () => electronGitService.listGitRemoteBranches(dirPath!), {
+ revalidateOnFocus: false,
+ shouldRetryOnError: false,
+ });
+};
diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/useWorkingTreePatches.ts b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/useWorkingTreePatches.ts
deleted file mode 100644
index 21f095dd1e8..00000000000
--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Review/useWorkingTreePatches.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import { isDesktop } from '@lobechat/const';
-
-import { useClientDataSWR } from '@/libs/swr';
-import { electronGitService } from '@/services/electron/git';
-
-/**
- * Single bulk fetch for every dirty file's unified diff patch. Replaces the
- * old N-call-per-file pattern — one IPC, one SWR cache key, the renderer
- * iterates the result. Mirrors the dirty-counts SWR shape (always-on, focus
- * revalidate) so opening the panel doesn't show a loading state when the
- * working tree has already been polled.
- */
-export const useWorkingTreePatches = (dirPath?: string) => {
- const key = isDesktop && dirPath ? ['git-working-tree-patches', dirPath] : null;
-
- return useClientDataSWR(key, () => electronGitService.getGitWorkingTreePatches(dirPath!), {
- focusThrottleInterval: 5 * 1000,
- revalidateOnFocus: true,
- shouldRetryOnError: false,
- });
-};
diff --git a/src/routes/(main)/agent/profile/features/Header/index.tsx b/src/routes/(main)/agent/profile/features/Header/index.tsx
index 73ef9caf0c2..808c2e7a84a 100644
--- a/src/routes/(main)/agent/profile/features/Header/index.tsx
+++ b/src/routes/(main)/agent/profile/features/Header/index.tsx
@@ -33,6 +33,7 @@ const Header = memo(() => {
const meta = useAgentStore(agentSelectors.currentAgentMeta, isEqual);
const systemRole = useAgentStore(agentSelectors.currentAgentSystemRole);
const activeAgentId = useAgentStore((s) => s.activeAgentId);
+ const isHeterogeneous = useAgentStore(agentSelectors.isCurrentAgentHeterogeneous);
const removeAgent = useHomeStore((s) => s.removeAgent);
const { isAuthenticated, isLoading: isAuthLoading, signIn } = useMarketAuth();
const { isUnderReview } = useVersionReviewStatus();
@@ -178,7 +179,9 @@ const Header = memo(() => {
size={DESKTOP_HEADER_ICON_SIZE}
/>
</DropdownMenu>
- <ToggleRightPanelButton icon={BotMessageSquareIcon} showActive={true} />
+ {!isHeterogeneous && (
+ <ToggleRightPanelButton icon={BotMessageSquareIcon} showActive={true} />
+ )}
</Flexbox>
}
/>
diff --git a/src/server/services/taskLifecycle/index.ts b/src/server/services/taskLifecycle/index.ts
index 35d6a5eaa1f..3582a538c6c 100644
--- a/src/server/services/taskLifecycle/index.ts
+++ b/src/server/services/taskLifecycle/index.ts
@@ -172,6 +172,7 @@ export class TaskLifecycleService {
await this.briefModel.create({
actions: DEFAULT_BRIEF_ACTIONS['error'],
+ agentId: currentTask?.assigneeAgentId || undefined,
priority: 'urgent',
summary: `Execution failed: ${errorMessage || 'Unknown error'}`,
taskId,
@@ -476,6 +477,7 @@ export class TaskLifecycleService {
await this.briefModel.create({
actions,
+ agentId: currentTask.assigneeAgentId || undefined,
artifacts,
priority,
summary: generated.summary,
@@ -548,6 +550,7 @@ export class TaskLifecycleService {
// (no actionable buttons in the UI) and the task transitions to 'completed'.
const now = new Date();
await this.briefModel.create({
+ agentId: currentTask?.assigneeAgentId || undefined,
priority: 'info',
resolvedAction: 'auto-judge-pass',
resolvedAt: now,
@@ -565,6 +568,7 @@ export class TaskLifecycleService {
if (reviewConfig.autoRetry && iteration < reviewConfig.maxIterations) {
await this.briefModel.create({
+ agentId: currentTask?.assigneeAgentId || undefined,
priority: 'normal',
summary: `Review failed (score: ${reviewResult.overallScore}%, iteration ${iteration}/${reviewConfig.maxIterations}). Auto-retrying...`,
taskId,
@@ -583,6 +587,7 @@ export class TaskLifecycleService {
// accept signal (force-pass) by BriefService.resolve. Result briefs render
// a fixed single-button UI, so no custom actions are persisted.
await this.briefModel.create({
+ agentId: currentTask?.assigneeAgentId || undefined,
priority: 'urgent',
summary: `Review failed after ${iteration} iteration(s) (score: ${reviewResult.overallScore}%). Suggestions: ${reviewResult.suggestions?.join('; ') || 'none'}`,
taskId,
diff --git a/src/server/services/toolExecution/serverRuntimes/brief.ts b/src/server/services/toolExecution/serverRuntimes/brief.ts
index 50a2dd53634..3172015d807 100644
--- a/src/server/services/toolExecution/serverRuntimes/brief.ts
+++ b/src/server/services/toolExecution/serverRuntimes/brief.ts
@@ -8,10 +8,12 @@ import { TaskModel } from '@/database/models/task';
import { type ServerRuntimeRegistration } from './types';
const createBriefRuntime = ({
+ agentId,
briefModel,
taskId,
taskModel,
}: {
+ agentId?: string;
briefModel: BriefModel;
taskId?: string;
taskModel: TaskModel;
@@ -31,6 +33,7 @@ const createBriefRuntime = ({
const brief = await briefModel.create({
actions,
+ agentId,
priority: args.priority || 'info',
summary: args.summary,
taskId,
@@ -56,6 +59,7 @@ const createBriefRuntime = ({
}
await briefModel.create({
+ agentId,
priority: 'normal',
summary: args.reason,
taskId,
@@ -76,7 +80,12 @@ export const briefRuntime: ServerRuntimeRegistration = {
const briefModel = new BriefModel(context.serverDB, context.userId);
const taskModel = new TaskModel(context.serverDB, context.userId);
- return createBriefRuntime({ briefModel, taskId: context.taskId, taskModel });
+ return createBriefRuntime({
+ agentId: context.agentId,
+ briefModel,
+ taskId: context.taskId,
+ taskModel,
+ });
},
identifier: BriefIdentifier,
};
diff --git a/src/services/aiAgent.ts b/src/services/aiAgent.ts
index 62fcc2c6ca8..da0c3dc1f21 100644
--- a/src/services/aiAgent.ts
+++ b/src/services/aiAgent.ts
@@ -126,8 +126,11 @@ class AiAgentService {
* Execute a single Agent task.
* Returns the operationId needed to connect to the Agent Gateway.
*/
- async execAgentTask(params: ExecAgentTaskParams): Promise<ExecAgentResult> {
- return await lambdaClient.aiAgent.execAgent.mutate(params);
+ async execAgentTask(
+ params: ExecAgentTaskParams,
+ options?: { signal?: AbortSignal },
+ ): Promise<ExecAgentResult> {
+ return await lambdaClient.aiAgent.execAgent.mutate(params, options);
}
/**
diff --git a/src/services/electron/git.ts b/src/services/electron/git.ts
index 098f2a3bc4a..3e578b4ef89 100644
--- a/src/services/electron/git.ts
+++ b/src/services/electron/git.ts
@@ -1,11 +1,14 @@
import {
+ type GetGitBranchDiffPayload,
type GitAheadBehind,
+ type GitBranchDiffPatches,
type GitBranchInfo,
type GitBranchListItem,
type GitCheckoutResult,
type GitLinkedPullRequestResult,
type GitPullResult,
type GitPushResult,
+ type GitRemoteBranchListItem,
type GitWorkingTreeFiles,
type GitWorkingTreePatches,
type GitWorkingTreeStatus,
@@ -42,6 +45,10 @@ class ElectronGitService {
return this.ipc.git.listGitBranches(dirPath);
}
+ async listGitRemoteBranches(dirPath: string): Promise<GitRemoteBranchListItem[]> {
+ return this.ipc.git.listGitRemoteBranches(dirPath);
+ }
+
async getGitWorkingTreeStatus(dirPath: string): Promise<GitWorkingTreeStatus> {
return this.ipc.git.getGitWorkingTreeStatus(dirPath);
}
@@ -54,6 +61,10 @@ class ElectronGitService {
return this.ipc.git.getGitWorkingTreePatches(dirPath);
}
+ async getGitBranchDiff(payload: GetGitBranchDiffPayload): Promise<GitBranchDiffPatches> {
+ return this.ipc.git.getGitBranchDiff(payload);
+ }
+
async getGitAheadBehind(dirPath: string): Promise<GitAheadBehind> {
return this.ipc.git.getGitAheadBehind(dirPath);
}
diff --git a/src/store/chat/slices/aiChat/actions/__tests__/gateway.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/gateway.test.ts
index 3f7c4cf9c47..c04839c3595 100644
--- a/src/store/chat/slices/aiChat/actions/__tests__/gateway.test.ts
+++ b/src/store/chat/slices/aiChat/actions/__tests__/gateway.test.ts
@@ -452,6 +452,7 @@ describe('GatewayActionImpl', () => {
parentMessageId: 'user-msg-123',
prompt: 'Original question',
}),
+ expect.anything(),
);
});
@@ -483,6 +484,7 @@ describe('GatewayActionImpl', () => {
parentMessageId: undefined,
prompt: 'Hello',
}),
+ expect.anything(),
);
});
@@ -523,6 +525,7 @@ describe('GatewayActionImpl', () => {
taskId: 'T-1',
}),
}),
+ expect.anything(),
);
});
@@ -555,9 +558,97 @@ describe('GatewayActionImpl', () => {
parentMessageId: 'assistant-msg-456',
prompt: '',
}),
+ expect.anything(),
);
});
+ it('forwards the parent abort signal to execAgentTask and bails out (with server interrupt) when cancel arrives after the request resolved', async () => {
+ const startOperation = vi.fn(() => ({ operationId: 'gw-op-local' }));
+ const completeOperation = vi.fn();
+ const associateMessageWithOperation = vi.fn();
+ const connectToGateway = vi.fn();
+ const onOperationCancel = vi.fn();
+
+ // Pre-aborted controller simulates the user clicking Stop while
+ // execAgentTask is still in flight: when it resolves the signal is
+ // already `aborted: true`, so executeGatewayAgent must NOT proceed to
+ // start the child op or open a WS connection.
+ const controller = new AbortController();
+ controller.abort('user cancelled');
+
+ const mockClient = createMockClient();
+ const state: Record<string, any> = { gatewayConnections: {} };
+ const set = vi.fn((updater: any) => {
+ if (typeof updater === 'function') Object.assign(state, updater(state));
+ else Object.assign(state, updater);
+ });
+ const get = vi.fn(() => ({
+ ...state,
+ associateMessageWithOperation,
+ completeOperation,
+ connectToGateway,
+ getOperationAbortSignal: vi.fn(() => controller.signal),
+ internal_updateTopicLoading: vi.fn(),
+ onOperationCancel,
+ replaceMessages: vi.fn(),
+ startOperation,
+ switchTopic: vi.fn(),
+ })) as any;
+
+ (globalThis as any).window = {
+ global_serverConfigStore: {
+ getState: () => ({ serverConfig: { agentGatewayUrl: 'https://gateway.test.com' } }),
+ },
+ };
+
+ const action = new GatewayActionImpl(set as any, get, undefined);
+ action.createClient = vi.fn(() => mockClient);
+ const interruptTaskSpy = vi
+ .mocked(aiAgentService.interruptTask)
+ .mockResolvedValue({ operationId: 'server-op-cancel', success: true });
+
+ vi.mocked(aiAgentService.execAgentTask).mockResolvedValue({
+ agentId: 'agent-1',
+ assistantMessageId: 'ast-1',
+ autoStarted: true,
+ createdAt: new Date().toISOString(),
+ message: 'ok',
+ operationId: 'server-op-cancel',
+ status: 'created',
+ success: true,
+ timestamp: new Date().toISOString(),
+ token: 'test-token',
+ topicId: 'topic-1',
+ userMessageId: 'usr-1',
+ });
+
+ await expect(
+ action.executeGatewayAgent({
+ context: { agentId: 'agent-1', topicId: 'topic-1', threadId: null, scope: 'main' },
+ message: 'Hello',
+ parentOperationId: 'parent-send-msg-op',
+ }),
+ ).rejects.toBeDefined();
+
+ // The signal must be forwarded into execAgentTask so the fetch itself
+ // is aborted in-flight when cancel comes during the round-trip.
+ expect(aiAgentService.execAgentTask).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ signal: controller.signal }),
+ );
+
+ // Server task was created before the signal flipped — best-effort
+ // interrupt must fire so the agent run stops server-side.
+ expect(interruptTaskSpy).toHaveBeenCalledWith({ operationId: 'server-op-cancel' });
+
+ // No child op, no message association, no WS connect, no parent complete
+ // — the cancel must short-circuit the whole hand-off.
+ expect(startOperation).not.toHaveBeenCalled();
+ expect(associateMessageWithOperation).not.toHaveBeenCalled();
+ expect(connectToGateway).not.toHaveBeenCalled();
+ expect(completeOperation).not.toHaveBeenCalled();
+ });
+
it('registers a cancel handler that calls aiAgentService.interruptTask with the server operationId', async () => {
const onOperationCancel = vi.fn();
const startOperation = vi.fn(() => ({ operationId: 'gw-op-local' }));
diff --git a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts b/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts
index 4a2b4966f6d..681539c3fbb 100644
--- a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts
+++ b/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts
@@ -644,13 +644,17 @@ export class ConversationLifecycleActionImpl {
// ── Gateway mode: skip sendMessageInServer, let execAgentTask handle everything ──
if (runtimeType === 'gateway') {
- this.#get().completeOperation(operationId);
-
try {
+ // Pass `sendMessage` as `parentOperationId` so executeGatewayAgent
+ // completes it the instant phase-1 init finishes (after the child
+ // `execServerAgentRuntime` op starts). Without this hand-off the
+ // input loading state would drop during the execAgentTask round-trip
+ // and the send button would flicker back to "send".
const result = await this.#get().executeGatewayAgent({
context: operationContext,
fileIds: fileIdList,
message,
+ parentOperationId: operationId,
});
return {
@@ -658,6 +662,12 @@ export class ConversationLifecycleActionImpl {
userMessageId: result.userMessageId,
};
} catch (e) {
+ // User cancelled during phase-1 init — `cancelOperation` already set
+ // the op to 'cancelled' and `executeGatewayAgent` cleaned up the
+ // server task. Don't clobber that with 'failed'.
+ const op = this.#get().operations[operationId];
+ if (op?.status === 'cancelled') return;
+
console.error('[Gateway] Failed to start server-side agent:', e);
this.#get().failOperation(operationId, {
message: e instanceof Error ? e.message : 'Unknown error',
diff --git a/src/store/chat/slices/aiChat/actions/gateway.ts b/src/store/chat/slices/aiChat/actions/gateway.ts
index 39a390aa632..6cf0b6d3970 100644
--- a/src/store/chat/slices/aiChat/actions/gateway.ts
+++ b/src/store/chat/slices/aiChat/actions/gateway.ts
@@ -258,6 +258,15 @@ export class GatewayActionImpl {
onComplete?: () => void;
/** Parent message ID for regeneration/continue (skip user message creation, branch from this message) */
parentMessageId?: string;
+ /**
+ * Caller-owned operation that should be completed once the gateway side
+ * has finished phase-1 init (network round-trip + child
+ * `execServerAgentRuntime` op started). Lets the caller keep its own
+ * loading state running through `execAgentTask` without any gap before
+ * the child op takes over. The relationship is also recorded as
+ * parent/child lineage on the new op.
+ */
+ parentOperationId?: string;
/**
* Resume a paused op waiting on `human_approve_required`. Forwarded to
* `aiAgentService.execAgentTask` so the new server-side op knows to apply
@@ -266,7 +275,15 @@ export class GatewayActionImpl {
*/
resumeApproval?: ResumeApprovalParam;
}): Promise<ExecAgentResult> => {
- const { context, fileIds, message, onComplete, parentMessageId, resumeApproval } = params;
+ const {
+ context,
+ fileIds,
+ message,
+ onComplete,
+ parentMessageId,
+ parentOperationId,
+ resumeApproval,
+ } = params;
const agentGatewayUrl =
window.global_serverConfigStore!.getState().serverConfig.agentGatewayUrl!;
@@ -274,26 +291,48 @@ export class GatewayActionImpl {
const isCreateNewTopic = !context.topicId;
const taskId = context.viewedTask?.type === 'detail' ? context.viewedTask.taskId : undefined;
- const result = await aiAgentService.execAgentTask({
- agentId: context.agentId,
- appContext: {
- defaultTaskAssigneeAgentId: context.defaultTaskAssigneeAgentId,
- documentId: context.documentId,
- groupId: context.groupId,
- scope: context.scope,
- taskId,
- threadId: context.threadId,
- topicId: context.topicId,
+ // Honour user-initiated cancel during phase-1 init: while we await the
+ // execAgentTask round-trip the caller's loading state (e.g. `sendMessage`)
+ // is still running, so the ChatInput stop button is active. Forward the
+ // signal into the request so the fetch aborts in-flight, and re-check
+ // afterwards in case cancel arrived just after the request resolved (the
+ // server task is then already created — best-effort interrupt it before
+ // bailing out, otherwise the agent run continues server-side).
+ const abortSignal = parentOperationId
+ ? this.#get().getOperationAbortSignal(parentOperationId)
+ : undefined;
+
+ const result = await aiAgentService.execAgentTask(
+ {
+ agentId: context.agentId,
+ appContext: {
+ defaultTaskAssigneeAgentId: context.defaultTaskAssigneeAgentId,
+ documentId: context.documentId,
+ groupId: context.groupId,
+ scope: context.scope,
+ taskId,
+ threadId: context.threadId,
+ topicId: context.topicId,
+ },
+ // Tell the server this caller is a desktop Electron client so it can
+ // enable `executor: 'client'` tools (local-system, stdio MCP) and
+ // dispatch them back over the Agent Gateway WS.
+ clientRuntime: isDesktop ? 'desktop' : 'web',
+ fileIds,
+ parentMessageId,
+ prompt: message,
+ resumeApproval,
},
- // Tell the server this caller is a desktop Electron client so it can
- // enable `executor: 'client'` tools (local-system, stdio MCP) and
- // dispatch them back over the Agent Gateway WS.
- clientRuntime: isDesktop ? 'desktop' : 'web',
- fileIds,
- parentMessageId,
- prompt: message,
- resumeApproval,
- });
+ { signal: abortSignal },
+ );
+
+ if (abortSignal?.aborted) {
+ // Cancel arrived after execAgentTask resolved — server task exists.
+ aiAgentService
+ .interruptTask({ operationId: result.operationId })
+ .catch((err) => console.error('[Gateway] interruptTask after cancel failed:', err));
+ throw abortSignal.reason ?? new DOMException('Aborted', 'AbortError');
+ }
// If server created a new topic, fetch messages first then switch topic
// (same pattern as client mode: replaceMessages before switchTopic to avoid skeleton flash)
@@ -310,6 +349,13 @@ export class GatewayActionImpl {
clearNewKey: true,
skipRefreshMessage: true,
});
+
+ if (abortSignal?.aborted) {
+ aiAgentService
+ .interruptTask({ operationId: result.operationId })
+ .catch((err) => console.error('[Gateway] interruptTask after cancel failed:', err));
+ throw abortSignal.reason ?? new DOMException('Aborted', 'AbortError');
+ }
}
// Use the server-created topicId for the execution context
@@ -326,12 +372,17 @@ export class GatewayActionImpl {
const { operationId: gatewayOpId } = this.#get().startOperation({
context: execContext,
metadata: { serverOperationId: result.operationId },
+ parentOperationId,
type: 'execServerAgentRuntime',
});
// Associate the server-created assistant message with the gateway operation
this.#get().associateMessageWithOperation(result.assistantMessageId, gatewayOpId);
+ // Phase-1 init done: child op is running. Hand off loading state from
+ // the caller's op (e.g. `sendMessage`) to the child without a gap.
+ if (parentOperationId) this.#get().completeOperation(parentOperationId);
+
// When the local operation is cancelled (e.g. user clicks stop), forward
// the interrupt directly to the server via the existing tRPC endpoint.
// Closure captures `result.operationId` (the server-side id) so we don't