Compare commits

..
40 changed files with 421 additions and 486 deletions
@@ -1,4 +1,4 @@
import { test, expect } from "../support/fixtures";
import { test, expect, type Page } from "../support/fixtures";
import { openWorkspaceWithAgents } from "../support/helpers/archive-tab";
import {
composerLocator,
@@ -311,3 +311,86 @@ test.describe("Composer trailing disc on a new chat", () => {
}
});
});
const SHORTCUT_MOD = process.platform === "darwin" ? "Meta" : "Control";
async function toggleModelPickerFromComposer(page: Page) {
await composerLocator(page).focus();
await page.keyboard.press(`${SHORTCUT_MOD}+Slash`);
}
async function expectModelPickerClosesFromSearch(page: Page) {
const search = page.getByPlaceholder(/Search (all )?models/);
await expect(search).toBeVisible();
await search.focus();
await page.keyboard.press(`${SHORTCUT_MOD}+Slash`);
await expect(search).toBeHidden();
}
async function cycleComposerEffort(page: Page) {
await composerLocator(page).focus();
await page.keyboard.press(`${SHORTCUT_MOD}+Shift+Slash`);
}
function modelControl(page: Page) {
return page.getByRole("button", { name: "Select model (Ten second stream)", exact: true });
}
function thinkingControl(page: Page, effort: string) {
return page.getByRole("button", { name: `Select thinking option (${effort})`, exact: true });
}
async function expectShortcutHint(
page: Page,
control: ReturnType<typeof modelControl>,
label: string,
) {
await control.hover();
const tooltip = page.getByRole("tooltip").filter({ hasText: label });
await expect(tooltip).toContainText("/");
}
test.describe("Composer model and effort shortcuts", () => {
test("opens and closes the model picker and wraps effort in toolbar order", async ({ page }) => {
const agent = await seedMockAgentWorkspace({
repoPrefix: "composer-shortcuts-",
title: "Composer shortcuts",
model: "ten-second-stream",
thinkingOptionId: "high",
});
try {
await openAgentRoute(page, agent);
await expectComposerVisible(page);
await expect(thinkingControl(page, "High")).toBeVisible();
await test.step("Show both shortcuts in the toolbar tooltips", async () => {
await expectShortcutHint(page, modelControl(page), "Change model");
await expectShortcutHint(page, thinkingControl(page, "High"), "Thinking mode");
});
await test.step("Toggle the picker with its search field focused", async () => {
await toggleModelPickerFromComposer(page);
await expectModelPickerClosesFromSearch(page);
});
await test.step("Wrap from High to Low and advance to Medium", async () => {
await cycleComposerEffort(page);
await expect(thinkingControl(page, "Low")).toBeVisible();
await cycleComposerEffort(page);
await expect(thinkingControl(page, "Medium")).toBeVisible();
});
await test.step("Toggle the folded picker and cycle effort in a compact window", async () => {
await page.setViewportSize({ width: 480, height: 844 });
const effortLabel = page.getByTestId("combined-model-selector-thinking-label");
await expect(effortLabel).toHaveText("Medium");
await toggleModelPickerFromComposer(page);
await expectModelPickerClosesFromSearch(page);
await cycleComposerEffort(page);
await expect(effortLabel).toHaveText("High");
});
} finally {
await agent.cleanup();
}
});
});
@@ -513,3 +513,37 @@ test("compact file sheets cover Explorer and return to its retained file list",
await workspace.cleanup();
}
});
async function toggleCommentInMainEditor(page: Parameters<typeof ensureExplorerSidebar>[0]) {
const editor = page.getByLabel("Source editor for comment.cs").getByRole("textbox");
await expect(editor).toBeVisible();
await editor.press(process.platform === "darwin" ? "Meta+Slash" : "Control+Slash");
await expect(editor).toHaveText("// public class Example {}");
}
test("keeps the comment shortcut in the editor beside an Explorer agent", async ({ page }) => {
const workspace = await seedMockAgentWorkspace({
repoPrefix: "explorer-comment-shortcut-",
title: "Chat beside the editor",
model: "ten-second-stream",
});
try {
await writeFile(`${workspace.cwd}/comment.cs`, "public class Example {}");
await openAgentRoute(page, workspace);
await expect(
page.getByRole("button", { name: "Select model (Ten second stream)" }),
).toBeVisible();
await ensureExplorerSidebar(page);
await dragTabIntoExplorer(page, `agent_${workspace.agentId}`);
await expect(
explorerSidebar(page).getByRole("button", { name: "Select model (Ten second stream)" }),
).toBeVisible();
await openFilesPanel(page);
await openFileFromExplorer(page, "comment.cs");
await explorerSidebar(page).getByTestId(`workspace-tab-agent_${workspace.agentId}`).click();
await toggleCommentInMainEditor(page);
await expect(page.getByPlaceholder(/Search (all )?models/)).toBeHidden();
} finally {
await workspace.cleanup();
}
});
@@ -56,20 +56,11 @@ function inFlightTurn(page: Page) {
return page.getByTestId("turn-working-indicator");
}
/**
* Presses a fork trigger until its menu shows.
*
* The in-flight turn's trigger sits below text that is still streaming in. While the chat is
* shorter than the viewport, each new line moves the trigger down. A line that arrives between
* the press and the release moves the trigger away from the pointer, so the press opens nothing,
* and the next press lands on the trigger where it is now.
*/
async function openForkMenu(page: Page, trigger: ReturnType<Page["getByRole"]>): Promise<void> {
const forkInNewTab = page.getByRole("menuitem", { name: "Fork in a new tab" });
await expect(async () => {
await trigger.click({ timeout: 5_000 });
await expect(forkInNewTab).toBeVisible({ timeout: 5_000 });
}).toPass({ timeout: 30_000 });
await trigger.click();
await expect(page.getByRole("menuitem", { name: "Fork in a new tab" })).toBeVisible({
timeout: 10_000,
});
}
export async function openMostRecentAssistantForkMenu(page: Page): Promise<void> {
@@ -19,6 +19,8 @@ import {
type ToolbarGlyph,
} from "@/components/ui/control-geometry";
import { useKeyboardToggle, type KeyboardToggleAction } from "@/hooks/use-keyboard-toggle";
const EMPTY_COMBOBOX_OPTIONS: ComboboxOption[] = [];
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
@@ -47,6 +49,7 @@ interface CombinedModelSelectorProps {
hovered: boolean;
pressed: boolean;
}) => React.ReactNode;
toggleAction?: KeyboardToggleAction;
onOpen?: () => void;
onClose?: () => void;
onRetryProvider?: (provider: AgentProvider) => void;
@@ -82,6 +85,7 @@ export function CombinedModelSelector({
onCreateProfile,
onEditProfile,
renderTrigger,
toggleAction,
onOpen,
onClose,
onRetryProvider,
@@ -147,6 +151,14 @@ export function CombinedModelSelector({
handleOpenChange(!isOpen);
}, [handleOpenChange, isOpen]);
useKeyboardToggle({
action: toggleAction,
disabled,
open: isOpen,
searchFocused: browser.isSearchFocused,
onToggle: handleTriggerPress,
});
const triggerStyle = useCallback(
({ pressed, hovered }: PressableStateCallbackType & { hovered?: boolean }) => {
if (triggerFill) {
File diff suppressed because one or more lines are too long
@@ -215,32 +215,6 @@ describe("Mermaid sandbox runtime", () => {
expect(widths).toEqual([240, 350, 900]);
});
/**
* Agents often write a label that starts with a mention or holds an email address. Mermaid 11
* read the text up to the "@" as an edge id, so these diagrams failed to parse.
*/
it.each([
"flowchart LR\n F[@mention in any workspace] --> G[Look up token]",
"flowchart LR\n A[ops@example.com] --> B",
"flowchart LR\n A -->|@user approves| B",
"graph TD\n A(@x) --> B{@x?}",
])("renders a flowchart whose label contains an @: %s", async (source) => {
const frame = await mountRuntime();
const result = await render(frame, { revision: 1, source });
expect(result).toMatchObject({ type: "rendered", revision: 1, source });
});
it("still renders a flowchart edge id", async () => {
const frame = await mountRuntime();
const source = "flowchart LR\n A[Start] e1@--> B[End]";
const result = await render(frame, { revision: 1, source });
expect(result).toMatchObject({ type: "rendered", revision: 1, source });
});
it("coalesces queued input and never reports an obsolete result", async () => {
const frame = await mountRuntime();
const obsoleteSource = `flowchart TD\n${Array.from({ length: 250 }, (_, index) => `A${index} --> A${index + 1}`).join("\n")}`;
@@ -1,103 +0,0 @@
// @vitest-environment jsdom
import type { ReactNode } from "react";
import { cleanup, renderHook, waitFor } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { afterEach, beforeEach, expect, it } from "vitest";
import type { FileReadResult } from "@getpaseo/client/internal/daemon-client";
import { __setAttachmentStoreForTests } from "@/attachments/store";
import type { AttachmentStore } from "@/attachments/types";
import { useMarkdownSource, type MarkdownImageContext } from "./images";
import { PENDING_MARKDOWN_IMAGE } from "./source";
const memoryStore: AttachmentStore = {
storageType: "web-indexeddb",
async save(input) {
return {
id: input.id ?? "att_chart",
mimeType: input.mimeType ?? "image/png",
storageType: "web-indexeddb",
storageKey: input.id ?? "att_chart",
fileName: input.fileName,
createdAt: 1,
};
},
async encodeBase64() {
return "";
},
async resolvePreviewUrl() {
return "blob:chart";
},
async releasePreviewUrl() {},
async delete() {},
async garbageCollect() {},
};
function createHostFiles() {
const reads: { cwd: string; path: string }[] = [];
return {
reads,
async readFile(cwd: string, path: string): Promise<FileReadResult> {
reads.push({ cwd, path });
return {
kind: "image",
path,
mime: "image/png",
size: 4,
modifiedAt: "2026-11-18T00:00:00.000Z",
bytes: new Uint8Array([1, 2, 3, 4]),
};
},
};
}
beforeEach(() => {
__setAttachmentStoreForTests(memoryStore);
});
afterEach(() => {
cleanup();
__setAttachmentStoreForTests(null);
});
function renderMarkdownSource(text: string, initialProps: MarkdownImageContext) {
// No retries: a failed read settles at once. For a host's Markdown this is the state once the
// retries have run out on a host that is slow to connect.
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
const wrapper = ({ children }: { children: ReactNode }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
);
const rendered = renderHook((props: MarkdownImageContext) => useMarkdownSource(text, props), {
wrapper,
initialProps,
});
return { ...rendered, queryClient };
}
it("waits for the host's client before reading a workspace image", async () => {
const context = { serverId: "srv_test", workspaceRoot: "/repo" };
const { result, rerender, queryClient } = renderMarkdownSource("![Chart](chart.png)", {
...context,
client: null,
});
await waitFor(() => {
expect(queryClient.isFetching()).toBe(0);
expect(result.current.markdown.replace(PENDING_MARKDOWN_IMAGE, "pending")).toBe(
"![Chart](<pending>)",
);
});
const files = createHostFiles();
rerender({ ...context, client: files });
await waitFor(() => expect(result.current.imageSources).toEqual({ "blob:chart": "chart.png" }));
expect(files.reads).toEqual([{ cwd: "/repo", path: "chart.png" }]);
});
it("shows the alt text of a file image in Markdown that belongs to no host", async () => {
const { result } = renderMarkdownSource("![Chart](/tmp/chart.png)", {});
await waitFor(() =>
expect(result.current.markdown.replace(PENDING_MARKDOWN_IMAGE, "pending")).toBe("Chart"),
);
});
@@ -81,10 +81,7 @@ export function useMarkdownSource(
const results = useFetchQueries(
acquisitions.map((acquisition, index) => ({
queryKey: ["markdownImage", acquisition?.key ?? sources[index]],
// A host that hasn't connected yet has no client. Its images stay pending until it does: the
// key doesn't change when the client arrives, so a read that already failed would not run
// again. Markdown with no host has no client to wait for and falls back to its alt text.
enabled: acquisition !== null && (context.client != null || !context.serverId),
enabled: acquisition !== null,
immutableWhen: () => true,
dataShape: "value",
gcTime: 0,
@@ -21,6 +21,8 @@ import { ICON_SIZE } from "@/styles/theme";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { AgentControlTrigger } from "@/composer/agent-controls/control";
import { useToast } from "@/contexts/toast-api-context";
import { Shortcut } from "@/components/ui/shortcut";
import type { ShortcutKey } from "@/utils/format-shortcut";
import { toErrorMessage } from "@/utils/error-messages";
interface ComposerControlBase {
@@ -106,6 +108,7 @@ interface ComposerControlProps {
disabled?: boolean;
open: boolean;
onOpenChange: (open: boolean) => void;
shortcutKeys?: ShortcutKey[][] | null;
/** Runs after a toolbar toggle or action, so the composer can take focus back. */
onActionComplete?: () => void;
}
@@ -217,6 +220,7 @@ export function ComposerControl({
open,
onOpenChange,
onActionComplete,
shortcutKeys,
}: ComposerControlProps) {
const { t } = useTranslation();
const anchorRef = useRef<View>(null);
@@ -279,7 +283,7 @@ export function ComposerControl({
{trigger}
</TooltipTrigger>
<TooltipContent side="top" align="center" offset={8}>
<Text style={styles.tooltipText}>{view.tooltip}</Text>
<ControlTooltipHint label={view.tooltip} shortcutKeys={shortcutKeys} />
</TooltipContent>
</Tooltip>
)}
@@ -349,6 +353,7 @@ interface ComposerControlsProps {
items: readonly ComposerControlItem[];
surface: ComposerControlSurface;
disabled?: boolean;
shortcutKeys?: ShortcutKey[][] | null;
/** The id of the item whose list is open. */
openId: string | null;
onOpenIdChange: (id: string | null) => void;
@@ -390,7 +395,27 @@ function ComposerControlSlot({
return <ComposerControl item={item} open={open} onOpenChange={handleOpenChange} {...rest} />;
}
export function ControlTooltipHint({
label,
shortcutKeys,
}: {
label: string;
shortcutKeys?: ShortcutKey[][] | null;
}) {
return (
<View style={styles.tooltipRow}>
<Text style={styles.tooltipText}>{label}</Text>
{shortcutKeys ? <Shortcut chord={shortcutKeys} /> : null}
</View>
);
}
const styles = StyleSheet.create((theme) => ({
tooltipRow: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
},
fieldIcon: { color: theme.colors.foregroundMuted },
blue: { color: theme.colors.palette.blue[400] },
green: { color: theme.colors.palette.green[400] },
@@ -1,4 +1,4 @@
import { useMemo } from "react";
import { useId, useMemo } from "react";
import type { TFunction } from "i18next";
import { useTranslation } from "react-i18next";
import { DensityIcon } from "@/components/ui/density-icon";
@@ -19,6 +19,12 @@ import {
import type { ComposerControlPresentation } from "@/composer/agent-controls/layout";
import { getAgentControlHintKey, getFeatureHighlightColor } from "@/composer/agent-controls/utils";
import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler";
import { useShortcutKeys } from "@/hooks/use-shortcut-keys";
import { useComposerInput } from "@/composer/session";
import { useComposerKeyboardScope } from "@/composer/keyboard-scope";
import { resolveNextChoiceId } from "./mode";
const SEARCH_THRESHOLD = 6;
function getFeatureHighlight(
@@ -71,6 +77,41 @@ interface ThinkingControl {
displayLabel: string;
}
export function useModelPickerShortcut(disabled: boolean) {
const { isActiveComposer } = useComposerKeyboardScope();
const input = useComposerInput();
const action =
isActiveComposer && !disabled && input
? {
id: "message-input.model-toggle" as const,
canOpen: input.isFocused,
}
: undefined;
const keys = useShortcutKeys(action ? "toggle-model-picker" : null);
return { action, keys };
}
export function useEffortCycleShortcut(thinking: ThinkingControl | null, disabled: boolean) {
const { isActiveComposer } = useComposerKeyboardScope();
const input = useComposerInput();
const effortHandlerId = useId();
const nextEffortId = resolveNextChoiceId(thinking?.options ?? [], thinking?.selectedId);
const canCycleEffort = isActiveComposer && !disabled && nextEffortId !== null && input !== null;
useKeyboardActionHandler({
handlerId: effortHandlerId,
actions: ["message-input.effort-cycle"],
enabled: canCycleEffort,
isActive: input?.isFocused,
priority: 200,
handle: () => {
if (!thinking || nextEffortId === null) return false;
thinking.onSelect(nextEffortId);
return true;
},
});
return useShortcutKeys(canCycleEffort ? "cycle-effort" : null);
}
/** The thinking select and the option controls, as the data `ComposerControl` draws. */
export function useAgentControlItems({
surface,
@@ -3,7 +3,6 @@ import { useTranslation } from "react-i18next";
import { router } from "expo-router";
import {
View,
Text,
Pressable,
Keyboard,
useWindowDimensions,
@@ -62,6 +61,7 @@ import {
useAgentControlCommandCenterActions,
type AgentControlCommandCenterSource,
} from "@/command-center/agent-control-registration";
import { useShortcutKeys } from "@/hooks/use-shortcut-keys";
import { useComposerKeyboardScope } from "@/composer/keyboard-scope";
import {
composerToolbarGeometry,
@@ -74,9 +74,14 @@ import { ComposerControlLayoutProvider } from "@/composer/agent-controls/layout-
import { ComposerToolbarGlyph } from "@/composer/agent-controls/glyph";
import {
ComposerControls,
ControlTooltipHint,
type ComposerControlItem,
} from "@/composer/agent-controls/composer-control";
import { useAgentControlItems } from "@/composer/agent-controls/control-items";
import {
useAgentControlItems,
useEffortCycleShortcut,
useModelPickerShortcut,
} from "@/composer/agent-controls/control-items";
import { CompactModelSheet } from "@/composer/agent-controls/model-sheet";
import { useComposerSheetBridge } from "@/composer/agent-controls/sheet-bridge";
import { draftComposerAgent } from "@/composer/draft/composer-agent";
@@ -583,6 +588,7 @@ function ControlledAgentControls({
selectedThinkingOptionId,
],
);
const effortKeys = useEffortCycleShortcut(thinking, disabled);
const items = useAgentControlItems({
surface: presentation.foldControls ? "sheet" : "toolbar",
presentation,
@@ -645,6 +651,7 @@ function ControlledAgentControls({
provider={provider}
selectedModelId={selectedModelId}
thinkingItems={items.thinking}
effortKeys={effortKeys}
featureItems={items.features}
onApplyAgentProfile={onApplyAgentProfile}
onEditAgentProfiles={onEditAgentProfiles}
@@ -677,6 +684,7 @@ function ControlledAgentControls({
provider={provider}
selectedModelId={selectedModelId}
thinkingItems={items.thinking}
effortKeys={effortKeys}
featureItems={items.features}
onApplyAgentProfile={onApplyAgentProfile}
onEditAgentProfiles={onEditAgentProfiles}
@@ -719,6 +727,7 @@ interface AgentControlsContentProps {
provider: string;
selectedModelId?: string;
thinkingItems: ComposerControlItem[];
effortKeys: ReturnType<typeof useShortcutKeys>;
featureItems: ComposerControlItem[];
onApplyAgentProfile?: (profileId: string) => void;
onEditAgentProfiles?: () => void;
@@ -758,6 +767,7 @@ function DesktopAgentControlsContent(props: DesktopAgentControlsContentProps) {
provider,
selectedModelId,
thinkingItems,
effortKeys,
featureItems,
onApplyAgentProfile,
onEditAgentProfiles,
@@ -785,6 +795,7 @@ function DesktopAgentControlsContent(props: DesktopAgentControlsContentProps) {
handleCloseSheet,
modelSelectorServerId,
} = props;
const { action: toggleAction, keys: modelKeys } = useModelPickerShortcut(disabled);
const modelToolbar = useMemo(
() => ({ glyph: glyphs.label, showCaret: presentation.showCarets }),
[glyphs, presentation.showCarets],
@@ -813,6 +824,7 @@ function DesktopAgentControlsContent(props: DesktopAgentControlsContentProps) {
onEditProfile={onEditAgentProfile}
isLoading={isModelLoading}
disabled={disabled}
toggleAction={toggleAction}
onOpen={onModelSelectorOpen}
onClose={onDropdownClose}
onRetryProvider={onRetryModelProvider}
@@ -825,13 +837,17 @@ function DesktopAgentControlsContent(props: DesktopAgentControlsContentProps) {
</View>
</TooltipTrigger>
<TooltipContent side="top" align="center" offset={8}>
<Text style={styles.tooltipText}>{t(getAgentControlHintKey("model"))}</Text>
<ControlTooltipHint
label={t(getAgentControlHintKey("model"))}
shortcutKeys={modelKeys}
/>
</TooltipContent>
</Tooltip>
) : null}
<ComposerControls
items={thinkingItems}
shortcutKeys={effortKeys}
surface="toolbar"
disabled={disabled}
openId={openSelector}
@@ -902,6 +918,7 @@ function SheetAgentControlsContent(props: SheetAgentControlsContentProps) {
provider,
selectedModelId,
thinkingItems,
effortKeys,
featureItems,
onApplyAgentProfile,
onEditAgentProfiles,
@@ -956,6 +973,7 @@ function SheetAgentControlsContent(props: SheetAgentControlsContentProps) {
selectedProvider={provider}
selectedModel={selectedModelId ?? ""}
thinkingLabel={displayThinking}
effortKeys={effortKeys}
onSelect={handleSheetModelSelect}
profiles={agentProfiles}
onApplyProfile={onApplyAgentProfile}
@@ -1479,11 +1497,6 @@ const styles = StyleSheet.create((theme) => ({
backgroundColor: "transparent",
borderRadius: theme.borderRadius.full,
},
tooltipText: {
color: theme.colors.foreground,
fontSize: theme.fontSize.base,
lineHeight: theme.fontSize.base * 1.4,
},
combinedSheetControls: {
gap: theme.spacing[1],
},
@@ -8,12 +8,18 @@ export function resolveNextAgentModeId({
modeOptions: readonly AgentMode[];
selectedMode: string | null | undefined;
}): string | null {
if (modeOptions.length < 2) return null;
return resolveNextChoiceId(modeOptions, selectedMode);
}
const selectedIndex = modeOptions.findIndex((mode) => mode.id === selectedMode);
export function resolveNextChoiceId(
options: readonly { id: string }[],
selectedId: string | null | undefined,
): string | null {
if (options.length < 2) return null;
const selectedIndex = options.findIndex((option) => option.id === selectedId);
const currentIndex = selectedIndex >= 0 ? selectedIndex : 0;
const nextIndex = (currentIndex + 1) % modeOptions.length;
return modeOptions[nextIndex]?.id ?? null;
return options[(currentIndex + 1) % options.length].id;
}
export function resolveAgentControlsMode(agentControls?: DraftAgentControlsProps) {
@@ -31,7 +31,12 @@ import {
toolbarSlot,
type ToolbarGlyphs,
} from "@/components/ui/control-geometry";
import { shortModelLabel } from "./utils";
import { getAgentControlHintKey, shortModelLabel } from "./utils";
import { useShortcutKeys } from "@/hooks/use-shortcut-keys";
import { useKeyboardToggle } from "@/hooks/use-keyboard-toggle";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { ControlTooltipHint } from "./composer-control";
import { useModelPickerShortcut } from "./control-items";
const SNAP_POINTS = ["80%", "90%"];
const MODEL_LIST_TOP_INSET = 4;
@@ -45,6 +50,7 @@ interface CompactModelSheetProps {
selectedProvider: string;
selectedModel: string;
thinkingLabel: string | null;
effortKeys: ReturnType<typeof useShortcutKeys>;
onSelect: (provider: string, modelId: string) => void;
isLoading: boolean;
profiles?: AgentProfilePicker | null;
@@ -133,6 +139,7 @@ export function CompactModelSheet({
selectedProvider,
selectedModel,
thinkingLabel,
effortKeys,
onSelect,
isLoading,
profiles = null,
@@ -316,11 +323,13 @@ export function CompactModelSheet({
glyphs={glyphs}
iconOnly={!showLabels && hasSelectedProvider}
isOpen={isOpen}
searchFocused={rootBrowser.isSearchFocused || modelBrowser.isSearchFocused}
disabled={disabled}
onPress={toggle}
accessibilityLabel={t("modelSelector.selectedModel", {
model: rootBrowser.selectedModelLabel,
})}
effortKeys={effortKeys}
/>
<AdaptiveModalSheet
@@ -409,17 +418,7 @@ export function CompactModelSheet({
* The folded model control in the toolbar: the provider glyph, then the model and thinking
* labels for as long as they fit.
*/
function ModelSheetTrigger({
ModelIcon,
modelLabel,
thinkingLabel,
glyphs,
iconOnly,
isOpen,
disabled,
onPress,
accessibilityLabel,
}: {
interface ModelSheetTriggerProps {
/** The selected provider's glyph, or null before a provider is selected. */
ModelIcon: ReturnType<typeof useProviderIcon> | null;
modelLabel: string;
@@ -427,10 +426,36 @@ function ModelSheetTrigger({
glyphs: ToolbarGlyphs;
iconOnly: boolean;
isOpen: boolean;
searchFocused: boolean;
disabled: boolean;
onPress: () => void;
accessibilityLabel: string;
}) {
effortKeys: ReturnType<typeof useShortcutKeys>;
}
function ModelSheetTrigger({
ModelIcon,
modelLabel,
thinkingLabel,
glyphs,
iconOnly,
isOpen,
searchFocused,
disabled,
onPress,
accessibilityLabel,
effortKeys,
}: ModelSheetTriggerProps) {
const { t } = useTranslation();
const { action: toggleAction, keys: modelKeys } = useModelPickerShortcut(disabled);
useKeyboardToggle({
action: toggleAction,
disabled,
open: isOpen,
searchFocused,
onToggle: onPress,
});
const glyphRole = iconOnly ? "icon" : "label";
const glyph = glyphs[glyphRole];
const triggerLabels = useModelTriggerLabels({
@@ -451,7 +476,7 @@ function ModelSheetTrigger({
[disabled, iconOnly, isOpen],
);
return (
const trigger = (
<View style={styles.triggerFrame} onLayout={triggerLabels.onFrameLayout}>
<ComboboxTrigger
collapsable={false}
@@ -521,6 +546,23 @@ function ModelSheetTrigger({
) : null}
</View>
);
return (
<Tooltip delayDuration={0} enabledOnDesktop enabledOnMobile={false}>
<TooltipTrigger asChild triggerRefProp="ref">
{trigger}
</TooltipTrigger>
<TooltipContent side="top" align="center" offset={8}>
<ControlTooltipHint label={t(getAgentControlHintKey("model"))} shortcutKeys={modelKeys} />
{effortKeys ? (
<ControlTooltipHint
label={t("settings.shortcuts.help.cycleEffort")}
shortcutKeys={effortKeys}
/>
) : null}
</TooltipContent>
</Tooltip>
);
}
const styles = StyleSheet.create((theme) => ({
+1
View File
@@ -1514,6 +1514,7 @@ function ComposerContentImpl({
isLive: isInputLive,
revealed: inputRevealed,
isRevealed: isInputRevealed,
isFocused: () => messageInputRef.current?.isFocused() ?? false,
focus: takeInputFocus,
textSource,
setText: replaceUserInput,
+1
View File
@@ -25,6 +25,7 @@ export interface ComposerInput {
*/
revealed: boolean;
isRevealed: () => boolean;
isFocused: () => boolean;
focus: (options?: ComposerFocusOptions) => Promise<void>;
textSource: ComposerTextSource;
setText: (text: string) => void;
@@ -0,0 +1,38 @@
import { useId } from "react";
import { hasFocusedTextInput } from "@/keyboard";
import type { KeyboardActionId } from "@/keyboard/keyboard-action-dispatcher";
import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler";
export interface KeyboardToggleAction {
id: KeyboardActionId;
canOpen: () => boolean;
}
/** Lets a trigger share its toggle with a keyboard action. */
export function useKeyboardToggle({
action,
disabled,
open,
searchFocused,
onToggle,
}: {
action: KeyboardToggleAction | undefined;
disabled: boolean;
open: boolean;
searchFocused: boolean;
onToggle: () => void;
}) {
const handlerId = useId();
useKeyboardActionHandler({
handlerId,
actions: action ? [action.id] : [],
enabled: action !== undefined && !disabled,
priority: 200,
isActive: () =>
action?.canOpen() === true || (open && (searchFocused || !hasFocusedTextInput())),
handle: () => {
onToggle();
return true;
},
});
}
+2
View File
@@ -2750,6 +2750,8 @@ export const ar: TranslationResources = {
toggleFocusMode: "تبديل وضع التركيز",
cycleTheme: "موضوع الدورة",
focusMessageInput: "التركيز على إدخال الرسالة",
toggleModelPicker: "فتح منتقي النموذج أو إغلاقه",
cycleEffort: "التنقل بين مستويات الجهد",
cycleAgentMode: "تبديل وضع الوكيل",
toggleVoiceMode: "تبديل الوضع الصوتي",
startStopDictation: "بدء إملاء /stop",
+2
View File
@@ -2844,6 +2844,8 @@ export const en = {
toggleFocusMode: "Toggle focus mode",
cycleTheme: "Cycle theme",
focusMessageInput: "Focus message input",
toggleModelPicker: "Toggle model picker",
cycleEffort: "Cycle effort",
cycleAgentMode: "Cycle agent mode",
toggleVoiceMode: "Toggle voice mode",
startStopDictation: "Start/stop dictation",
+2
View File
@@ -2773,6 +2773,8 @@ export const es: TranslationResources = {
toggleFocusMode: "Alternar modo de enfoque",
cycleTheme: "Tema del ciclo",
focusMessageInput: "Entrada de mensaje de enfoque",
toggleModelPicker: "Abrir o cerrar el selector de modelos",
cycleEffort: "Alternar el nivel de esfuerzo",
cycleAgentMode: "Alternar modo del agente",
toggleVoiceMode: "Alternar modo de voz",
startStopDictation: "Iniciar dictado/stop",
+2
View File
@@ -2775,6 +2775,8 @@ export const fr: TranslationResources = {
toggleFocusMode: "Activer/désactiver le mode focus",
cycleTheme: "Parcourir les thèmes",
focusMessageInput: "Aller à la zone de saisie",
toggleModelPicker: "Ouvrir ou fermer le sélecteur de modèle",
cycleEffort: "Parcourir les niveaux d’effort",
cycleAgentMode: "Parcourir les modes de l’agent",
toggleVoiceMode: "Activer/désactiver le mode vocal",
startStopDictation: "Démarrer/arrêter la dictée",
+2
View File
@@ -2739,6 +2739,8 @@ export const ja: TranslationResources = {
toggleFocusMode: "フォーカスモードを切り替え",
cycleTheme: "テーマを順に切り替え",
focusMessageInput: "メッセージ入力にフォーカス",
toggleModelPicker: "モデル選択を開く/閉じる",
cycleEffort: "推論の強度を順に切り替え",
cycleAgentMode: "エージェントモードを順に切り替え",
toggleVoiceMode: "音声モードを切り替え",
startStopDictation: "音声入力を開始/停止",
+2
View File
@@ -2728,6 +2728,8 @@ export const ko: TranslationResources = {
toggleFocusMode: "집중 모드 토글",
cycleTheme: "테마 순환",
focusMessageInput: "메시지 입력란에 포커스",
toggleModelPicker: "모델 선택기 열기 또는 닫기",
cycleEffort: "추론 강도 순환",
cycleAgentMode: "에이전트 모드 전환",
toggleVoiceMode: "음성 모드 토글",
startStopDictation: "받아쓰기 시작/중지",
+2
View File
@@ -2753,6 +2753,8 @@ export const ptBR: TranslationResources = {
toggleFocusMode: "Alternar modo de foco",
cycleTheme: "Alternar tema",
focusMessageInput: "Focar entrada de mensagem",
toggleModelPicker: "Abrir ou fechar o seletor de modelos",
cycleEffort: "Alternar o nível de esforço",
cycleAgentMode: "Alternar modo do agente",
toggleVoiceMode: "Alternar modo de voz",
startStopDictation: "Iniciar/parar ditado",
+2
View File
@@ -2761,6 +2761,8 @@ export const ru: TranslationResources = {
toggleFocusMode: "Переключить режим фокусировки",
cycleTheme: "Переключить тему",
focusMessageInput: "Перейти к полю ввода сообщения",
toggleModelPicker: "Открыть или закрыть выбор модели",
cycleEffort: "Переключить уровень усилий",
cycleAgentMode: "Переключить режим агента",
toggleVoiceMode: "Переключить голосовой режим",
startStopDictation: "Начать/остановить диктовку",
+2
View File
@@ -2684,6 +2684,8 @@ export const zhCN: TranslationResources = {
toggleFocusMode: "切换专注模式",
cycleTheme: "循环切换主题",
focusMessageInput: "聚焦消息输入框",
toggleModelPicker: "打开或关闭模型选择器",
cycleEffort: "循环切换推理强度",
cycleAgentMode: "循环切换代理模式",
toggleVoiceMode: "切换语音模式",
startStopDictation: "开始/停止听写",
+3 -1
View File
@@ -14,7 +14,9 @@ export type MessageInputKeyboardActionKind =
| "dictation-confirm"
| "voice-toggle"
| "voice-mute-toggle"
| "mode-cycle";
| "mode-cycle"
| "model-toggle"
| "effort-cycle";
export type KeyboardActionId =
| "agent.interrupt"
+1
View File
@@ -7,6 +7,7 @@ export {
getTopOverlayLayer,
subscribeOverlays,
} from "./internal/overlay-dispatch";
export { hasFocusedTextInput } from "./internal/focused-text-input";
export { useKeyboardFocusSurface } from "./internal/use-focus-surface";
export { subscribeHardwareKeyboard } from "./internal/sources/hardware";
export type { HardwareKeyboardEvent } from "./internal/sources/hardware";
@@ -1,3 +1,6 @@
import { resolveKeyboardFocusScope } from "../focus-scope";
export function hasFocusedTextInput(): boolean {
return false;
const scope = resolveKeyboardFocusScope({ target: null, commandCenterOpen: false });
return scope === "editable" || scope === "message-input";
}
@@ -13,6 +13,8 @@ export type KeyboardActionId =
| "message-input.voice-toggle"
| "message-input.voice-mute-toggle"
| "message-input.mode-cycle"
| "message-input.model-toggle"
| "message-input.effort-cycle"
| "workspace.agent.new"
| "workspace.tab.menu.open"
| "workspace.tab.target.agent"
@@ -67,6 +69,8 @@ export type KeyboardActionDefinition =
| { id: "message-input.voice-toggle"; scope: KeyboardActionScope }
| { id: "message-input.voice-mute-toggle"; scope: KeyboardActionScope }
| { id: "message-input.mode-cycle"; scope: KeyboardActionScope }
| { id: "message-input.model-toggle"; scope: KeyboardActionScope }
| { id: "message-input.effort-cycle"; scope: KeyboardActionScope }
| { id: "workspace.agent.new"; scope: KeyboardActionScope }
| { id: "workspace.tab.menu.open"; scope: KeyboardActionScope }
| { id: "workspace.tab.target.agent"; scope: KeyboardActionScope }
@@ -337,6 +337,27 @@ describe("keyboard-shortcuts", () => {
action: "message-input.action",
payload: { kind: "dictation-toggle" },
},
{
name: "toggles the model picker from the composer",
event: { key: "/", code: "Slash", metaKey: true },
context: { isMac: true, focusScope: "message-input" },
action: "message-input.action",
payload: { kind: "model-toggle" },
},
{
name: "toggles the model picker while its search field has focus",
event: { key: "/", code: "Slash", metaKey: true },
context: { isMac: true, focusScope: "editable" },
action: "message-input.action",
payload: { kind: "model-toggle" },
},
{
name: "cycles effort with the shifted slash character",
event: { key: "?", code: "Slash", metaKey: true, shiftKey: true },
context: { isMac: true, focusScope: "message-input" },
action: "message-input.action",
payload: { kind: "effort-cycle" },
},
{
name: "routes Shift+Tab to cycle agent mode from the message input",
event: { key: "Tab", code: "Tab", shiftKey: true },
@@ -751,6 +772,8 @@ describe("keyboard-shortcut help sections", () => {
"workspace-pane-split-right": ["mod", "\\"],
"workspace-pane-close": ["mod", "shift", "W"],
"cycle-agent-mode": ["shift", "Tab"],
"toggle-model-picker": ["mod", "/"],
"cycle-effort": ["mod", "shift", "/"],
},
},
{
@@ -197,6 +197,8 @@ export const SHORTCUT_HELP_ROW_ORDER: Record<ShortcutSectionId, readonly string[
layout: ["toggle-left-sidebar", "toggle-right-sidebar", "toggle-both-sidebars", "toggle-focus"],
"agent-input": [
"focus-message-input",
"toggle-model-picker",
"cycle-effort",
"cycle-agent-mode",
"voice-toggle",
"dictation-toggle",
@@ -244,6 +246,8 @@ const SHORTCUT_HELP_LABEL_KEYS: Record<string, string> = {
"toggle-focus": "settings.shortcuts.help.toggleFocusMode",
"cycle-theme": "settings.shortcuts.help.cycleTheme",
"focus-message-input": "settings.shortcuts.help.focusMessageInput",
"toggle-model-picker": "settings.shortcuts.help.toggleModelPicker",
"cycle-effort": "settings.shortcuts.help.cycleEffort",
"cycle-agent-mode": "settings.shortcuts.help.cycleAgentMode",
"voice-toggle": "settings.shortcuts.help.toggleVoiceMode",
"dictation-toggle": "settings.shortcuts.help.startStopDictation",
@@ -1149,6 +1153,33 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
label: "Focus message input",
},
},
{
id: "message-input-model-toggle-mod-slash",
action: "message-input.action",
combo: "Mod+/",
repeat: false,
// The handler checks that its composer or its own picker has focus.
when: { commandCenter: false, focusScope: ["message-input", "editable", "other"] },
payload: { type: "message-input", kind: "model-toggle" },
help: {
id: "toggle-model-picker",
section: "agent-input",
label: "Toggle model picker",
},
},
{
id: "message-input-effort-cycle-mod-shift-slash",
action: "message-input.action",
combo: "Mod+Shift+/",
repeat: false,
when: { commandCenter: false, focusScope: "message-input" },
payload: { type: "message-input", kind: "effort-cycle" },
help: {
id: "cycle-effort",
section: "agent-input",
label: "Cycle effort",
},
},
{
id: "message-input-mode-cycle-shift-tab",
action: "message-input.action",
@@ -304,6 +304,8 @@ describe("routeKeyboardShortcut — message-input.action", () => {
["dictation-confirm", "message-input.dictation-confirm"],
["voice-toggle", "message-input.voice-toggle"],
["voice-mute-toggle", "message-input.voice-mute-toggle"],
["model-toggle", "message-input.model-toggle"],
["effort-cycle", "message-input.effort-cycle"],
["mode-cycle", "message-input.mode-cycle"],
] as const)("kind=%s → dispatch %s", (kind, id) => {
expect(
@@ -85,6 +85,8 @@ const MESSAGE_INPUT_DISPATCH: Record<
"dictation-confirm": { id: "message-input.dictation-confirm", scope: "message-input" },
"voice-toggle": { id: "message-input.voice-toggle", scope: "message-input" },
"voice-mute-toggle": { id: "message-input.voice-mute-toggle", scope: "message-input" },
"model-toggle": { id: "message-input.model-toggle", scope: "message-input" },
"effort-cycle": { id: "message-input.effort-cycle", scope: "message-input" },
"mode-cycle": { id: "message-input.mode-cycle", scope: "message-input" },
};
@@ -106,6 +106,7 @@ function fakeInput(initial: UserComposerAttachment[] = [], locked = false) {
isLive: () => true,
revealed: true,
isRevealed: () => view.revealed,
isFocused: () => false,
focus: async (options) => {
view.focused.push(options);
},
@@ -605,8 +605,6 @@ class ProviderRuntimeSession {
>();
private readonly activeTurnIds = new Set<string>();
private terminal = false;
// The provider ended this session with session.closed, so it has nothing left to close.
private closedByProvider = false;
private closePromise: Promise<void> | null = null;
config: ProviderConfigState = { models: [], modes: [], thinkingOptions: [] };
commands: Array<{ name: string; description: string; argumentHint?: string }> = [];
@@ -725,7 +723,7 @@ class ProviderRuntimeSession {
async close(): Promise<void> {
this.history.length = 0;
if (this.restoration === "parent" || this.closedByProvider) {
if (this.restoration === "parent") {
this.runtime.removeSession(this.id, this.providerSessionId);
return;
}
@@ -790,7 +788,6 @@ class ProviderRuntimeSession {
return;
}
if (event.type === "session.runtime_failed" || event.type === "session.closed") {
if (event.type === "session.closed") this.closedByProvider = true;
if (this.terminal) return;
this.terminal = true;
this.publish(event);
@@ -1,193 +0,0 @@
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { expect, onTestFinished, test } from "vitest";
import { DaemonClient } from "../test-utils/daemon-client.js";
import { createTestPaseoDaemon } from "../test-utils/paseo-daemon.js";
import { resolveDaemonVersion } from "../daemon-version.js";
const PROVIDER_ID = "closing-provider";
const PLUGIN_ID = "closing-provider-plugin";
// How the provider ends the session that ran the first turn.
type CloseMode =
// The first turn completes, then the provider closes the session on its own.
| "after-turn"
// The first turn fails and the provider closes the session with the failure.
| "after-failed-turn"
// The provider answers the second prompt by closing the session.
| "on-next-prompt";
async function createClosingProviderPlugin(root: string, mode: CloseMode): Promise<string> {
const directory = path.join(root, "plugin");
await mkdir(directory, { recursive: true });
await writeFile(
path.join(directory, "paseo-plugin.json"),
JSON.stringify({
id: PLUGIN_ID,
requirements: { paseo: `>=${resolveDaemonVersion(import.meta.url)}` },
}),
);
await writeFile(
path.join(directory, "index.server.ts"),
`import type {
ProviderEvent,
ProviderInput,
ProviderRegistration,
} from "@getpaseo/plugin/server/provider";
const CAPABILITIES = ["prompt.message", "session.persistence"];
const MODE = ${JSON.stringify(mode)};
const provider: ProviderRegistration = {
id: ${JSON.stringify(PROVIDER_ID)},
label: "Closing provider",
async connect() {
let listener: ((event: ProviderEvent) => void) | null = null;
const emit = (event: ProviderEvent) => listener?.(event);
let turn = 0;
const closed = new Set<string>();
return {
version: 1,
capabilities: CAPABILITIES,
async send(input: ProviderInput) {
if (input.type === "catalog") {
emit({
type: "catalog",
requestId: input.requestId,
catalog: {
models: [{ id: "closing-model", label: "Closing model" }],
modes: [],
thinkingOptions: [],
defaultModel: "closing-model",
},
});
return;
}
if (input.type === "session.open") {
emit({
type: "session.opened",
requestId: input.requestId,
sessionId: input.sessionId,
capabilities: CAPABILITIES,
restoration: "core",
persistence: { version: 1, data: { token: "root" } },
cwd: input.config.cwd,
});
emit({ type: "session.ready", requestId: input.requestId, sessionId: input.sessionId });
return;
}
if (input.type === "session.prompt") {
turn += 1;
if (MODE === "on-next-prompt" && turn === 2) {
closed.add(input.sessionId);
emit({ type: "session.closed", sessionId: input.sessionId });
return;
}
const turnId = "turn-" + turn;
emit({
type: "session.prompt_result",
sessionId: input.sessionId,
clientMessageId: input.prompt.clientMessageId,
result: { type: "turn", turnId },
});
emit({ type: "session.turn", sessionId: input.sessionId, turnId, state: "started" });
if (MODE === "after-failed-turn" && turn === 1) {
emit({ type: "session.turn", sessionId: input.sessionId, turnId, state: "failed", error: { message: "Provider turn failed" } });
emit({ type: "session.closed", sessionId: input.sessionId, error: { message: "Provider turn failed" } });
return;
}
emit({
type: "timeline.item",
sessionId: input.sessionId,
item: { type: "assistant_message", id: "answer-" + turn, text: "Done " + turn },
});
emit({ type: "session.turn", sessionId: input.sessionId, turnId, state: "completed" });
if (MODE === "after-turn" && turn === 1) {
emit({ type: "session.closed", sessionId: input.sessionId });
}
return;
}
if (input.type === "session.close") {
if (!closed.has(input.sessionId)) emit({ type: "session.closed", sessionId: input.sessionId });
}
if ("requestId" in input) {
emit({ type: "request.completed", requestId: input.requestId });
}
},
onEvent(next: (event: ProviderEvent) => void) {
listener = next;
return () => {
if (listener === next) listener = null;
};
},
async close() {},
};
},
};
export default function contribute(server: { registerProvider(p: ProviderRegistration): void }) {
server.registerProvider(provider);
return () => undefined;
}`,
);
return directory;
}
test.each<CloseMode>(["after-turn", "after-failed-turn", "on-next-prompt"])(
"an agent whose provider session closed (%s) runs its next prompt",
async (mode) => {
const root = await mkdtemp(path.join(tmpdir(), "plugin-provider-closed-session-"));
onTestFinished(() =>
rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }),
);
const pluginDirectory = await createClosingProviderPlugin(root, mode);
const workspace = path.join(root, "workspace");
await mkdir(workspace, { recursive: true });
const daemon = await createTestPaseoDaemon({
paseoHomeRoot: path.join(root, "daemon"),
staticDir: path.join(root, "static"),
pluginsEnabled: true,
plugins: {
[PLUGIN_ID]: { source: "directory", path: pluginDirectory, enabled: true },
},
});
const client = new DaemonClient({
url: `ws://127.0.0.1:${daemon.port}/ws`,
appVersion: "0.9.1",
});
onTestFinished(async () => {
await client.close();
await daemon.close();
});
await client.connect();
await client.fetchAgents({ subscribe: {} });
const agent = await client.createAgent({
provider: PROVIDER_ID,
model: "closing-model",
cwd: workspace,
title: "Closing provider agent",
});
await client.sendMessage(agent.id, "first");
await client.waitForFinish(agent.id, 30_000);
// Before the fix, reopening tried to close the session the provider had already
// closed, failed, and rejected this send with "Provider session <id> is stale".
await client.sendMessage(agent.id, "second");
expect((await client.waitForFinish(agent.id, 30_000)).status).toBe("idle");
const timeline = await client.fetchAgentTimeline(agent.id, {
direction: "tail",
limit: 0,
projection: "canonical",
});
const text = JSON.stringify(timeline.entries);
// In on-next-prompt the provider closed the session on prompt 2, so the reopened
// session answers the retried prompt as its third.
expect(text).toContain(mode === "on-next-prompt" ? "Done 3" : "Done 2");
expect(text).not.toMatch(/Provider session \S+ (closed|is stale)/);
},
60_000,
);
@@ -587,29 +587,6 @@ describe("WorkspaceGitServiceImpl", () => {
await service.dispose();
});
test("a client reconnecting within the release grace reuses the warm target", async () => {
const getCheckoutStatus = vi.fn(buildDefaultTestServiceDeps().getCheckoutStatus);
const service = createService({ getCheckoutStatus });
try {
const first = service.registerWorkspace({ cwd: REPO_CWD }, () => {});
const snapshot = await service.getSnapshot(REPO_CWD);
await waitForObservationToSettle(service, 1);
first.unsubscribe();
expect(service.getMetrics().workspaceTargetCount).toBe(1);
const reads = getCheckoutStatus.mock.calls.length;
const second = service.registerWorkspace({ cwd: REPO_CWD }, () => {});
await expect(service.getSnapshot(REPO_CWD)).resolves.toEqual(snapshot);
expect(getCheckoutStatus).toHaveBeenCalledTimes(reads);
second.unsubscribe();
await vi.advanceTimersByTimeAsync(90_000);
expect(service.getMetrics().workspaceTargetCount).toBe(0);
} finally {
await service.dispose();
}
});
test("onSnapshotUpdated delivers without workspace subscribers and can unsubscribe", async () => {
const service = createService();
const snapshots: WorkspaceGitRuntimeSnapshot[] = [];
@@ -646,7 +623,6 @@ describe("WorkspaceGitServiceImpl", () => {
const service = new WorkspaceGitServiceImpl({
logger: createLogger() as unknown as pino.Logger,
paseoHome: "/tmp/paseo-test",
releaseGraceMs: 0,
deps: {
...buildDefaultTestServiceDeps(),
getPullRequestStatus: async () => {
@@ -81,9 +81,6 @@ import { checkoutLiteFromGitSnapshot } from "./workspace-registry-model.js";
import { createWatcherLivenessCanary } from "./watcher-liveness-canary.js";
const WORKSPACE_GIT_WATCH_DEBOUNCE_MS = 1_000;
// A target outlives its last listener this long, so a reconnecting client reuses its snapshot
// and watchers instead of re-reading every checkout.
const WORKSPACE_GIT_RELEASE_GRACE_MS = 90_000;
export const BACKGROUND_GIT_FETCH_INTERVAL_MS = 180_000;
const FETCH_METADATA_ECHO_TTL_MS = 5_000;
export const WORKSPACE_GIT_OBSERVATION_REENSURE_INTERVAL_MS = 60_000;
@@ -444,8 +441,6 @@ interface WorkspaceGitServiceOptions {
worktreesRoot?: string;
fileObserver?: FileObserver;
deps?: Partial<WorkspaceGitServiceDependencies>;
/** How long a workspace target outlives its last listener; 0 releases it immediately. */
releaseGraceMs?: number;
}
class WorkspaceGitServiceDisposedError extends Error {
@@ -468,7 +463,6 @@ interface WorkspaceGitTarget {
gitDirPaths: GitObservationPaths | null;
cwd: string;
listeners: Set<WorkspaceGitListener>;
releaseTimer: NodeJS.Timeout | null;
workingTreeWatchTarget: WorkingTreeWatchTarget | null;
debounceTimer: NodeJS.Timeout | null;
pendingDebounceRequest: WorkspaceGitRefreshRequest | null;
@@ -663,7 +657,6 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
private readonly logger: pino.Logger;
private readonly paseoHome: string;
private readonly worktreesRoot: string | undefined;
private readonly releaseGraceMs: number;
private readonly fileObserver: FileObserver;
private readonly deps: WorkspaceGitServiceDependencies;
private readonly forgeResolver: ForgeResolver;
@@ -717,7 +710,6 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
this.logger = options.logger.child({ module: "workspace-git-service" });
this.paseoHome = options.paseoHome;
this.worktreesRoot = options.worktreesRoot;
this.releaseGraceMs = options.releaseGraceMs ?? WORKSPACE_GIT_RELEASE_GRACE_MS;
this.fileObserver = options.fileObserver ?? createFileObserver();
this.deps = resolveWorkspaceGitServiceDeps(
this.fileObserver.subscribe.bind(this.fileObserver),
@@ -741,7 +733,6 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
this.assertNotDisposed();
const cwd = resolve(params.cwd);
const target = this.ensureWorkspaceTarget(cwd);
this.cancelWorkspaceRelease(target);
target.listeners.add(listener);
if (target.folderMissing) {
void this.resumeWorkspaceIfFolderRestored(target);
@@ -1327,7 +1318,6 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
gitDirPaths: null,
cwd,
listeners: new Set(),
releaseTimer: null,
workingTreeWatchTarget: null,
debounceTimer: null,
pendingDebounceRequest: null,
@@ -3075,9 +3065,6 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
if (!target || target.closed || this.workspaceTargets.get(target.cwd) !== target) {
return;
}
if (options.origin === "observation" && this.releaseChangedWarmTarget(target)) {
return;
}
const request = this.buildScheduledRefreshRequest(options);
target.pendingDebounceRequest = this.mergeRefreshRequests(
@@ -3364,9 +3351,6 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
if (target.closed || this.workspaceTargets.get(target.cwd) !== target) {
return;
}
if (request.origin === "observation" && this.releaseChangedWarmTarget(target)) {
return;
}
try {
await this.requestWorkspaceSnapshot(target, request);
} catch (error) {
@@ -4120,52 +4104,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
return;
}
if (this.releaseGraceMs <= 0 || !this.isWorkspaceObservationEstablished(target)) {
this.removeWorkspaceTarget(target);
return;
}
// Keep the snapshot and watchers warm for a reconnecting client; stop forge polling now.
this.stopForgePrStatusPollForTarget(target);
this.cancelWorkspaceRelease(target);
target.releaseTimer = setTimeout(() => {
target.releaseTimer = null;
if (
!target.closed &&
target.listeners.size === 0 &&
this.workspaceTargets.get(target.cwd) === target
) {
this.removeWorkspaceTarget(target);
}
}, this.releaseGraceMs);
target.releaseTimer.unref?.();
}
/** Only a fully watched target stays warm; one still recovering a watcher is released now. */
private isWorkspaceObservationEstablished(target: WorkspaceGitTarget): boolean {
const repoTarget = target.repoGitRoot ? this.repoTargets.get(target.repoGitRoot) : undefined;
return Boolean(
target.latestSnapshot &&
!target.folderMissing &&
target.workingTreeWatchTarget?.subscription &&
repoTarget?.subscription,
);
}
/** A change seen while nobody listens ends the grace: the next consumer re-reads, nobody pays now. */
private releaseChangedWarmTarget(target: WorkspaceGitTarget): boolean {
if (target.listeners.size > 0 || !target.releaseTimer) {
return false;
}
this.cancelWorkspaceRelease(target);
this.removeWorkspaceTarget(target);
return true;
}
private cancelWorkspaceRelease(target: WorkspaceGitTarget): void {
if (target.releaseTimer) {
clearTimeout(target.releaseTimer);
target.releaseTimer = null;
}
}
private removeWorkspaceTarget(target: WorkspaceGitTarget): void {
@@ -4232,7 +4171,6 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
private closeWorkspaceTarget(target: WorkspaceGitTarget): void {
target.closed = true;
this.cancelWorkspaceRelease(target);
this.stopWorkspaceObservation(target);
target.listeners.clear();
}
File diff suppressed because one or more lines are too long
-6
View File
@@ -86,12 +86,6 @@ const patchedPackages = [
nodeModulesPath: "node_modules/@mattermost/react-native-paste-input",
patchPrefix: "@mattermost+react-native-paste-input+",
},
// Backport of https://github.com/mermaid-js/mermaid/pull/8459 (lexer half): a flowchart label
// with an "@" parses. The patch header has the details. Remove when the app uses mermaid 12.
{
nodeModulesPath: "node_modules/mermaid",
patchPrefix: "mermaid+",
},
{
nodeModulesPath: "packages/server/node_modules/@opencode-ai/sdk",
patchPrefix: "@opencode-ai+sdk+",