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.

💄 style(chat-input): make worktree removal non-blocking (#16725)

Arvin Xu7a2e0431d8de
diff --git a/.agents/skills/ux/SKILL.md b/.agents/skills/ux/SKILL.md
index 35cac5fab23..b83fef354ed 100644
--- a/.agents/skills/ux/SKILL.md
+++ b/.agents/skills/ux/SKILL.md
@@ -125,7 +125,7 @@ The one-screen scan. Each line links back to a module above for the full rule +
- [ ] Terminal status screen (success / error `Result`) carries an action: error → escape hatch (retry / back), success → close / go-to-result; no bare `Result` without `extra`, and "auto-closing in Ns" copy only when the close can actually fire.
- [ ] A result that changes the next step lands in a persistent state (screen / inline), not just a transient toast; "link sent" names the destination + offers resend, failures keep context + offer retry.
- [ ] Bulk action has a single-item entry (and vice versa).
-- [ ] Async/bulk/irreversible action: confirm → in-progress (locked) → done/error.
+- [ ] Async/bulk/irreversible action: confirm → in-progress (locked) → done/error. But a **slow but atomic** confirm-gated op (device/file delete, git op, seconds-long call) closes the confirm **immediately** (non-blocking `onOk`) and shows progress on the **originating surface** (optimistic removal / row spinner), not a confirm dialog held spinning on the round-trip — the modal is not the progress surface.
- [ ] A long-running / costly async op (generation / export / large upload) offers **Cancel while it runs** (aborts the work, not just delete-after-the-fact) and keeps an in-place **Retry** on error — named as a generation-class norm so an absent Cancel is caught.
- [ ] Optimistic create / rename / duplicate surfaces failure (caller catches + toasts); never a silent rollback.
- [ ] Job-control (run / pause / stop / retry) surfaces start/stop failure — a `catch` that only `console.error`s + optimistic-status rollback reads as a dead button; toast at the store-action boundary so every trigger inherits it.
diff --git a/.agents/skills/ux/references/act.md b/.agents/skills/ux/references/act.md
index 3c70d9fd74a..b9a1a7d1598 100644
--- a/.agents/skills/ux/references/act.md
+++ b/.agents/skills/ux/references/act.md
@@ -18,6 +18,26 @@ a confirm step stating exactly what happens → an in-progress view with **dismi
locked** → a done (or error) view in the same modal. Never fire-and-forget with only a
toast; never leave a dead spinner.
+But **the confirm modal is not the progress surface**. That state-machine is for ops that
+_earn_ a modal — multi-step, or where watching progress is the point. A **single
+slow-but-atomic** op behind an _already-shown_ confirm — a `git worktree remove`, a file
+delete that round-trips a device, any \~seconds-long backend call — is the opposite trap:
+holding the confirm dialog open and **blocking on the round-trip**, its OK button spinning
+for the whole call, freezes a dialog that should have closed the instant the user
+committed. "In-progress (locked)" means the user can't dismiss a surface that's _showing
+them progress_ — it does not license a confirm box held hostage to a 30s call it isn't even
+narrating. Close the confirm the moment the user commits (a base-ui `confirmModal` `onOk`
+that returns **synchronously**, not an `async` thenable the modal awaits) and move the
+in-progress signal onto the **originating surface**: an optimistic removal of the row, or a
+per-row "removing…" spinner that also guards a duplicate trigger, reconciled on settle via
+the list revalidate. This is **not** the "fire-and-forget with only a toast" the rule above
+forbids — failure still surfaces (an error toast carrying the real reason: a
+`git worktree remove` _refuses_ a dirty worktree), so the shape is confirm → (dialog closes)
+→ surface shows in-progress → done/**error**. One inversion of the usual "a delete's success
+toast is redundant, the row vanishing is the confirmation": when the affected list lives
+behind an **already-dismissed** surface (the dropdown that hosted the row closed on confirm),
+a **success** toast _is_ warranted — it's the only signal the backgrounded op finished.
+
A **long-running or costly** async op — an AI generation (image / video), an export, a
large upload, a batch job that runs for seconds-to-minutes and often bills tokens — owes one
more affordance: a **Cancel / Stop while it runs**. "In-progress (locked)" means the user
@@ -106,6 +126,16 @@ triggers is a lie the user waits on.
> old value — visible when list + detail are mounted together (Chat portal) or on cached
> back-navigation (`revalidateOnFocus:false`). ✅ Share one normalized map, or invalidate the list
> on every successful field write (not a gated subset).
+> ❌ **Confirm dialog held hostage to a slow op**: the worktree switcher's remove holds the
+> danger `confirmModal` open and blocks on `await gitService.removeGitWorktree()` — a
+> `git worktree remove` with a 30s timeout **plus** a device round-trip — so after the user
+> already confirmed, the dialog sits with its OK button spinning for seconds
+> (`ChatInput/ControlBar/WorktreeSwitcher.tsx`). ✅ `onOk` returns **synchronously** and runs
+> the removal detached: the dialog closes instantly, the originating row shows a "removing…"
+> spinner (which also guards a duplicate delete), success + failure surface as bottom-left
+> toasts (`toast.error` carries the real git reason — e.g. a dirty worktree), and the list
+> reconciles on the `onWorktreesChange` revalidate. The success toast stays because the
+> dropdown that hosted the row is already closed — it's the only "it finished" signal.
**Checklist**
@@ -118,6 +148,7 @@ triggers is a lie the user waits on.
- [ ] "Auto-closing / redirecting in Ns" copy only when the close / redirect can actually fire (e.g. `window.opener` present); otherwise show a manual action. _(Certainty)_
- [ ] Bulk ⇄ single-item parity (toolbar action also on the item, and vice versa). _(Certainty)_
- [ ] Bulk / irreversible / async: confirm → in-progress (locked) → done/error, one surface. _(Certainty・Meaningful)_
+- [ ] A **slow but atomic** confirm-gated op (device/file delete, git op, seconds-long call) closes the confirm **immediately** (non-blocking `onOk` that returns synchronously) and shows in-progress on the **originating surface** (optimistic removal / row spinner) — never a confirm dialog held spinning on the round-trip; done/error still surface (a success toast is warranted when the affected list is already dismissed). _(Natural・Certainty)_
- [ ] A long-running / costly async op (generation / export / large upload) offers **Cancel while it runs** (abort the work), not just delete-after-the-fact, and keeps an **in-place Retry** on the error state — named as a generation-class norm so an absent Cancel is caught. _(Meaningful・Certainty)_
## 3.2 One primary button, and it's the visually dominant one・Certainty
diff --git a/locales/en-US/device.json b/locales/en-US/device.json
index fb891820b12..0a374fd7808 100644
--- a/locales/en-US/device.json
+++ b/locales/en-US/device.json
@@ -79,9 +79,9 @@
"workingDirectory.uncommittedChanges_one": "Uncommitted changes: {{count}} file",
"workingDirectory.uncommittedChanges_other": "Uncommitted changes: {{count}} files",
"workingDirectory.undo": "Undo",
- "workingDirectory.worktreeCount": "{{count}} worktrees",
- "workingDirectory.worktreeSwitchDescription": "Switch the current conversation working directory",
+ "workingDirectory.worktreeSearchPlaceholder": "Search worktrees",
"workingDirectory.worktreeUnavailable": "unavailable",
"workingDirectory.worktreesEmpty": "No worktrees found",
- "workingDirectory.worktreesHeading": "Worktrees"
+ "workingDirectory.worktreesHeading": "Worktrees",
+ "workingDirectory.worktreesNoMatch": "No matching worktrees"
}
diff --git a/locales/zh-CN/device.json b/locales/zh-CN/device.json
index e22de011021..6dcc05511f0 100644
--- a/locales/zh-CN/device.json
+++ b/locales/zh-CN/device.json
@@ -79,9 +79,9 @@
"workingDirectory.uncommittedChanges_one": "未提交的更改:{{count}} 个文件",
"workingDirectory.uncommittedChanges_other": "未提交的更改:{{count}} 个文件",
"workingDirectory.undo": "撤销",
- "workingDirectory.worktreeCount": "{{count}} 个 worktree",
- "workingDirectory.worktreeSwitchDescription": "切换当前对话的 working directory",
+ "workingDirectory.worktreeSearchPlaceholder": "搜索 worktree",
"workingDirectory.worktreeUnavailable": "不可用",
"workingDirectory.worktreesEmpty": "未发现 worktree",
- "workingDirectory.worktreesHeading": "选择 Worktree"
+ "workingDirectory.worktreesHeading": "Worktree",
+ "workingDirectory.worktreesNoMatch": "无匹配的 worktree"
}
diff --git a/packages/locales/src/default/device.ts b/packages/locales/src/default/device.ts
index 2dd0c752123..f5299d3696a 100644
--- a/packages/locales/src/default/device.ts
+++ b/packages/locales/src/default/device.ts
@@ -85,9 +85,9 @@ export default {
'workingDirectory.removeWorktreeFailed': 'Delete worktree failed',
'workingDirectory.removeWorktreeSuccess': 'Worktree deleted',
'workingDirectory.removeWorktreeTitle': 'Delete worktree',
- 'workingDirectory.worktreeCount': '{{count}} worktrees',
- 'workingDirectory.worktreeSwitchDescription': 'Switch the current conversation working directory',
+ 'workingDirectory.worktreeSearchPlaceholder': 'Search worktrees',
'workingDirectory.worktreeUnavailable': 'unavailable',
'workingDirectory.worktreesEmpty': 'No worktrees found',
'workingDirectory.worktreesHeading': 'Worktrees',
+ 'workingDirectory.worktreesNoMatch': 'No matching worktrees',
};
diff --git a/src/features/ChatInput/ControlBar/WorktreeSwitcher.tsx b/src/features/ChatInput/ControlBar/WorktreeSwitcher.tsx
index 3adc64035a0..989dd3c9115 100644
--- a/src/features/ChatInput/ControlBar/WorktreeSwitcher.tsx
+++ b/src/features/ChatInput/ControlBar/WorktreeSwitcher.tsx
@@ -1,5 +1,5 @@
import type { DeviceGitWorktreeListItem, WorkingDirEntry } from '@lobechat/types';
-import { Icon, Tooltip } from '@lobehub/ui';
+import { Icon, Input, Tooltip } from '@lobehub/ui';
import {
confirmModal,
DropdownMenuItem,
@@ -10,8 +10,15 @@ import {
DropdownMenuTrigger,
toast,
} from '@lobehub/ui/base-ui';
-import { createStaticStyles, cssVar } from 'antd-style';
-import { CheckIcon, GitForkIcon, Trash2Icon } from 'lucide-react';
+import { createStaticStyles, cssVar, cx } from 'antd-style';
+import {
+ CheckIcon,
+ GitForkIcon,
+ LoaderCircleIcon,
+ RefreshCwIcon,
+ SearchIcon,
+ Trash2Icon,
+} from 'lucide-react';
import { memo, type MouseEvent, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -78,8 +85,11 @@ const styles = createStaticStyles(({ css }) => ({
display: flex;
flex-direction: column;
- width: 520px;
+ width: 460px;
max-width: calc(100vw - 48px);
+ height: 380px;
+
+ /* Cancel DropdownMenuPopup's default 4px padding so our sections align edge-to-edge */
margin: -4px;
`,
count: css`
@@ -118,27 +128,61 @@ const styles = createStaticStyles(({ css }) => ({
color: ${cssVar.colorTextTertiary};
text-align: center;
`,
- header: css`
- display: flex;
- gap: 12px;
- align-items: center;
- justify-content: space-between;
-
- padding-block: 8px;
+ searchBar: css`
+ padding-block: 4px;
padding-inline: 12px;
border-block-end: 1px solid ${cssVar.colorSplit};
+
+ .ant-input-affix-wrapper {
+ padding-inline: 0;
+ }
+
+ .ant-input-prefix {
+ margin-inline-end: 8px;
+ }
`,
- headerMeta: css`
- flex: none;
+ section: css`
+ flex: 1;
+ font-size: 11px;
+ font-weight: 500;
color: ${cssVar.colorTextTertiary};
`,
- headerSubtitle: css`
- margin-block-start: 1px;
+ sectionRow: css`
+ display: flex;
+ gap: 4px;
+ align-items: center;
+
+ padding-block: 4px 2px;
+ padding-inline: 8px;
+ `,
+ refreshButton: css`
+ cursor: pointer;
+
+ display: flex;
+ align-items: center;
+ justify-content: center;
+
+ width: 20px;
+ height: 20px;
+ border-radius: 4px;
+
color: ${cssVar.colorTextTertiary};
+
+ transition: all 0.2s;
+
+ &:hover {
+ color: ${cssVar.colorText};
+ background: ${cssVar.colorFillTertiary};
+ }
`,
- headerTitle: css`
- font-weight: 600;
- color: ${cssVar.colorText};
+ spinning: css`
+ animation: worktree-switcher-spin 0.8s linear infinite;
+
+ @keyframes worktree-switcher-spin {
+ to {
+ transform: rotate(360deg);
+ }
+ }
`,
item: css`
cursor: pointer;
@@ -187,7 +231,7 @@ const styles = createStaticStyles(({ css }) => ({
`,
list: css`
overflow-y: auto;
- max-height: 360px;
+ flex: 1;
padding: 6px;
`,
name: css`
@@ -391,9 +435,45 @@ const WorktreeSwitcher = memo<WorktreeSwitcherProps>(
const { t } = useTranslation('device');
const { t: tCommon } = useTranslation('common');
const [open, setOpen] = useState(false);
+ const [search, setSearch] = useState('');
+ const [isRefreshing, setIsRefreshing] = useState(false);
+ // Paths currently being removed in the background. `git worktree remove` is
+ // slow (up to a 30s timeout + device round-trip), so removal runs detached
+ // from the confirm dialog — this tracks in-flight rows to guard against a
+ // duplicate delete if the dropdown is reopened mid-removal.
+ const [removingPaths, setRemovingPaths] = useState<Set<string>>(new Set());
const currentRowRef = useRef<HTMLDivElement>(null);
const { commit } = useCommitWorkingDirectory(agentId);
+ // Clear the query each time the dropdown closes so it reopens unfiltered.
+ useEffect(() => {
+ if (!open) setSearch('');
+ }, [open]);
+
+ const handleRefresh = useCallback(async () => {
+ if (isRefreshing) return;
+ setIsRefreshing(true);
+ try {
+ await onWorktreesChange?.();
+ } finally {
+ setIsRefreshing(false);
+ }
+ }, [isRefreshing, onWorktreesChange]);
+
+ // Filter by worktree folder name, path, or branch.
+ const filtered = useMemo(() => {
+ const query = search.trim().toLowerCase();
+ if (!query) return worktrees;
+ return worktrees.filter((worktree) => {
+ const branch = getWorktreeBranch(worktree, currentBranch, () => '');
+ return (
+ getPathName(worktree.path).toLowerCase().includes(query) ||
+ worktree.path.toLowerCase().includes(query) ||
+ branch.toLowerCase().includes(query)
+ );
+ });
+ }, [worktrees, search, currentBranch]);
+
const currentWorktree = useMemo(
() =>
worktrees.find((worktree) => worktree.current) ?? worktrees.find((w) => w.path === path),
@@ -437,18 +517,33 @@ const WorktreeSwitcher = memo<WorktreeSwitcherProps>(
}),
okButtonProps: { danger: true },
okText: tCommon('delete'),
- onOk: async () => {
- const result = await gitService.removeGitWorktree({
- deviceId,
- path,
- worktreePath: worktree.path,
- });
- if (result.success) {
- toast.success(t('workingDirectory.removeWorktreeSuccess'));
- await onWorktreesChange?.();
- return;
- }
- toast.error(result.error || t('workingDirectory.removeWorktreeFailed'));
+ // Return synchronously (no promise) so the dialog closes instantly
+ // instead of holding the user on a spinning modal for the duration of
+ // a slow `git worktree remove`. The removal runs in the background;
+ // completion and failure surface via bottom-left toasts, and the row
+ // reconciles on the next `onWorktreesChange` revalidate.
+ onOk: () => {
+ setRemovingPaths((prev) => new Set(prev).add(worktree.path));
+ void (async () => {
+ const result = await gitService.removeGitWorktree({
+ deviceId,
+ path,
+ worktreePath: worktree.path,
+ });
+ if (result.success) {
+ // The list is hidden behind the closed dropdown, so this toast
+ // is the only signal that the background removal finished.
+ toast.success(t('workingDirectory.removeWorktreeSuccess'));
+ await onWorktreesChange?.();
+ } else {
+ toast.error(result.error || t('workingDirectory.removeWorktreeFailed'));
+ }
+ setRemovingPaths((prev) => {
+ const next = new Set(prev);
+ next.delete(worktree.path);
+ return next;
+ });
+ })();
},
title: t('workingDirectory.removeWorktreeTitle'),
});
@@ -465,7 +560,7 @@ const WorktreeSwitcher = memo<WorktreeSwitcherProps>(
currentRowRef.current?.scrollIntoView({ block: 'nearest' });
});
return () => cancelAnimationFrame(raf);
- }, [open, worktrees.length, currentPath]);
+ }, [open, filtered.length, currentPath]);
const triggerTitle = detached
? t('workingDirectory.detachedHead', { sha: currentBranch })
@@ -489,31 +584,46 @@ const WorktreeSwitcher = memo<WorktreeSwitcherProps>(
<DropdownMenuPositioner placement="topLeft" sideOffset={8}>
<DropdownMenuPopup>
<div className={styles.container}>
- <div className={styles.header}>
- <div>
- <div className={styles.headerTitle}>
- {t('workingDirectory.worktreesHeading')}
- </div>
- <div className={styles.headerSubtitle}>
- {t('workingDirectory.worktreeSwitchDescription')}
- </div>
- </div>
- <div className={styles.headerMeta}>
- {t('workingDirectory.worktreeCount', { count: worktrees.length })}
- </div>
+ <div className={styles.searchBar}>
+ <Input
+ autoFocus
+ placeholder={t('workingDirectory.worktreeSearchPlaceholder')}
+ prefix={<Icon icon={SearchIcon} size={14} />}
+ size="small"
+ value={search}
+ variant="borderless"
+ onChange={(e) => setSearch(e.target.value)}
+ onKeyDown={(e) => e.stopPropagation()}
+ />
</div>
<div className={styles.list}>
- {worktrees.length === 0 ? (
- <div className={styles.emptyState}>{t('workingDirectory.worktreesEmpty')}</div>
+ <div className={styles.sectionRow}>
+ <div className={styles.section}>{t('workingDirectory.worktreesHeading')}</div>
+ <div className={styles.refreshButton} role="button" onClick={handleRefresh}>
+ <Icon
+ className={cx(isRefreshing && styles.spinning)}
+ icon={RefreshCwIcon}
+ size={12}
+ />
+ </div>
+ </div>
+
+ {filtered.length === 0 ? (
+ <div className={styles.emptyState}>
+ {search.trim()
+ ? t('workingDirectory.worktreesNoMatch')
+ : t('workingDirectory.worktreesEmpty')}
+ </div>
) : (
- worktrees.map((worktree) => {
+ filtered.map((worktree) => {
const branch = getWorktreeBranch(worktree, currentBranch, (sha) =>
t('workingDirectory.detachedHeadShort', { sha }),
);
const displayPath = getRelativeDisplayPath(worktree.path, sourcePath);
const disabled = isDisabled(worktree);
- const removable = canRemoveWorktree(worktree, sourcePath);
+ const removing = removingPaths.has(worktree.path);
+ const removable = canRemoveWorktree(worktree, sourcePath) && !removing;
return (
<DropdownMenuItem
@@ -563,7 +673,9 @@ const WorktreeSwitcher = memo<WorktreeSwitcherProps>(
<DirtyStat status={worktree.status} />
</div>
<div className={styles.actionCell}>
- {worktree.current ? (
+ {removing ? (
+ <Icon spin icon={LoaderCircleIcon} size={13} />
+ ) : worktree.current ? (
<Icon className={styles.check} icon={CheckIcon} size={14} />
) : (
removable && (
diff --git a/src/features/ChatInput/ControlBar/__tests__/WorktreeSwitcher.test.tsx b/src/features/ChatInput/ControlBar/__tests__/WorktreeSwitcher.test.tsx
index 7772ee303cf..ebd0f1dc55a 100644
--- a/src/features/ChatInput/ControlBar/__tests__/WorktreeSwitcher.test.tsx
+++ b/src/features/ChatInput/ControlBar/__tests__/WorktreeSwitcher.test.tsx
@@ -1,4 +1,4 @@
-import { fireEvent, render, screen, within } from '@testing-library/react';
+import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import type { ReactNode } from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -29,6 +29,9 @@ vi.mock('@/services/git', () => ({
vi.mock('@lobehub/ui', () => ({
Icon: () => <span data-testid="icon" />,
+ Input: ({ value, onChange, placeholder }: any) => (
+ <input placeholder={placeholder} value={value} onChange={onChange} />
+ ),
Tooltip: ({ children }: { children: ReactNode }) => (
<span data-testid="worktree-tooltip">{children}</span>
),
@@ -219,18 +222,67 @@ describe('WorktreeSwitcher', () => {
expect(commitMock).not.toHaveBeenCalled();
expect(confirmModalMock).toHaveBeenCalledTimes(1);
- await confirmModalMock.mock.calls[0][0].onOk();
+ // onOk returns synchronously (non-blocking) — the removal runs in the
+ // background, so assert against the eventual side effects rather than the
+ // resolved value.
+ confirmModalMock.mock.calls[0][0].onOk();
expect(removeGitWorktreeMock).toHaveBeenCalledWith({
deviceId: 'device-1',
path: '/repo',
worktreePath: '/repo-detached',
});
- expect(onWorktreesChange).toHaveBeenCalled();
+ await waitFor(() => {
+ expect(onWorktreesChange).toHaveBeenCalled();
+ });
expect(messageSuccessMock).toHaveBeenCalledWith('workingDirectory.removeWorktreeSuccess');
expect(messageErrorMock).not.toHaveBeenCalled();
});
+ it('surfaces an error toast without rolling into success when removal fails', async () => {
+ removeGitWorktreeMock.mockResolvedValue({
+ error: 'fatal: worktree contains modified or untracked files',
+ success: false,
+ });
+ const onWorktreesChange = vi.fn();
+ render(
+ <WorktreeSwitcher
+ isGithub
+ agentId="agent-1"
+ currentBranch="feat/current"
+ deviceId="device-1"
+ path="/repo"
+ sourcePath="/repo"
+ worktrees={[
+ {
+ branch: 'feat/current',
+ current: true,
+ path: '/repo',
+ status: { added: 0, clean: true, deleted: 0, modified: 0, total: 0 },
+ },
+ {
+ branch: 'canary',
+ current: false,
+ path: '/repo-canary',
+ status: { added: 0, clean: true, deleted: 0, modified: 0, total: 0 },
+ },
+ ]}
+ onWorktreesChange={onWorktreesChange}
+ />,
+ );
+
+ fireEvent.click(screen.getByLabelText('workingDirectory.removeWorktreeAction'));
+ confirmModalMock.mock.calls[0][0].onOk();
+
+ await waitFor(() => {
+ expect(messageErrorMock).toHaveBeenCalledWith(
+ 'fatal: worktree contains modified or untracked files',
+ );
+ });
+ expect(messageSuccessMock).not.toHaveBeenCalled();
+ expect(onWorktreesChange).not.toHaveBeenCalled();
+ });
+
it('never offers to remove the source worktree even when it is not current', () => {
render(
<WorktreeSwitcher