mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-04 15:34:39 +00:00
feat(plugins): New workspace items set the branch and workspace metadata
addNewWorkspaceItem mounts a plugin field on the New workspace screen, and useNewWorkspace() exposes host, project, isolation, base ref, branch and metadata with commands that follow the composer item rules: they act on the screen's state when they run, resolve once applied, reject while the screen is locked, and take JSON payloads. Host and project are read-only because a command that switched them would unmount the item that called it. The screen's pickable state (base selection, manual isolation, branch, metadata) moves into one plain store so pickers and plugin commands write to the same place; the screen reports derived facts to it on each render. The branch is sent as source.branchName only for a branch-off worktree, and metadata on workspace.create. Items render through ComposerControl with a new "field" surface (badge on desktop, full-width field when compact). Combobox ships here: Paseo owns the loading and error states, keeps previous results, and drops superseded searches.
This commit is contained in:
@@ -0,0 +1,20 @@
|
||||
import { expect, test } from "../support/fixtures";
|
||||
import { withNewWorkspaceIssuesExample } from "../support/helpers/plugin-new-workspace-items";
|
||||
|
||||
for (const layout of [
|
||||
{ name: "desktop", compact: false },
|
||||
{ name: "compact", compact: true },
|
||||
]) {
|
||||
test(`a plugin's New workspace item sets the branch and metadata on ${layout.name}`, async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(180_000);
|
||||
await withNewWorkspaceIssuesExample(page, { compact: layout.compact }, async (screen) => {
|
||||
await screen.chooseWorktree();
|
||||
await screen.chooseIssue("PAS-102 Crash on resume");
|
||||
const created = await screen.createWorkspace();
|
||||
expect(created.branch).toBe("pas-102-crash-on-resume");
|
||||
expect(created.metadata).toEqual({ "new-workspace-issues.issue": "PAS-102" });
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import { expect, test, type Page } from "@playwright/test";
|
||||
import { gotoAppShell } from "./app";
|
||||
import {
|
||||
archiveWorkspaceFromDaemon,
|
||||
assertNewWorkspaceSidebarAndHeader,
|
||||
connectNewWorkspaceDaemonClient,
|
||||
openNewWorkspaceComposer,
|
||||
openProjectViaDaemon,
|
||||
submitNewWorkspacePrompt,
|
||||
} from "./new-workspace";
|
||||
import { copyPluginExample } from "./plugin-fixture";
|
||||
import { getServerId } from "./server-id";
|
||||
import { createTempGitRepo } from "./workspace";
|
||||
import { waitForSidebarHydration } from "./workspace-ui";
|
||||
|
||||
const PLUGIN_ID = "new-workspace-issues-example";
|
||||
const COMPACT = { width: 500, height: 800 };
|
||||
|
||||
/** Runs `run` on the New workspace screen with the new-workspace-issues example installed. */
|
||||
export async function withNewWorkspaceIssuesExample(
|
||||
page: Page,
|
||||
options: { compact: boolean },
|
||||
run: (screen: {
|
||||
chooseWorktree(): Promise<void>;
|
||||
chooseIssue(label: string): Promise<void>;
|
||||
createWorkspace(): Promise<{ branch: string | null; metadata: unknown }>;
|
||||
}) => Promise<void>,
|
||||
) {
|
||||
const client = await connectNewWorkspaceDaemonClient();
|
||||
const previous = await client.getDaemonConfig();
|
||||
const example = await copyPluginExample("new-workspace-issues");
|
||||
const repo = await createTempGitRepo("new-workspace-issues-", { branches: ["main"] });
|
||||
let createdDirectory: string | null = null;
|
||||
try {
|
||||
await client.patchDaemonConfig({ pluginsEnabled: true });
|
||||
await client.installDirectoryPlugin(example.directory);
|
||||
const project = await openProjectViaDaemon(client, repo.path);
|
||||
await gotoAppShell(page);
|
||||
await waitForSidebarHydration(page);
|
||||
await openNewWorkspaceComposer(page, project);
|
||||
// The sidebar rows used to reach the screen exist only at desktop width.
|
||||
if (options.compact) await page.setViewportSize(COMPACT);
|
||||
await run({
|
||||
chooseWorktree: () =>
|
||||
test.step("choose a new worktree", async () => {
|
||||
await page.getByTestId("workspace-create-isolation-trigger").click();
|
||||
await page.getByTestId("workspace-create-isolation-worktree").click();
|
||||
}),
|
||||
chooseIssue: (label) =>
|
||||
test.step(`choose the issue "${label}"`, async () => {
|
||||
await page.getByRole("button", { name: "Issue", exact: true }).click();
|
||||
await page.getByText(label, { exact: true }).click();
|
||||
}),
|
||||
createWorkspace: () =>
|
||||
test.step("create the workspace and read what it carries", async () => {
|
||||
await submitNewWorkspacePrompt(page);
|
||||
const created = await assertNewWorkspaceSidebarAndHeader(page, {
|
||||
serverId: getServerId(),
|
||||
client,
|
||||
previousWorkspaceId: project.workspaceId,
|
||||
projectDisplayName: project.projectDisplayName,
|
||||
// The sidebar is closed at compact width.
|
||||
assertSidebarRow: !options.compact,
|
||||
});
|
||||
createdDirectory = created.workspaceDirectory;
|
||||
const { entries } = await client.fetchWorkspaces();
|
||||
const workspace = entries.find((entry) => entry.id === created.workspaceId);
|
||||
expect(workspace).toBeDefined();
|
||||
return {
|
||||
branch: workspace?.gitRuntime?.currentBranch ?? null,
|
||||
metadata: workspace?.metadata,
|
||||
};
|
||||
}),
|
||||
});
|
||||
} finally {
|
||||
if (createdDirectory) {
|
||||
await archiveWorkspaceFromDaemon(client, createdDirectory).catch(() => undefined);
|
||||
}
|
||||
await client.removePlugin(PLUGIN_ID).catch(() => undefined);
|
||||
await client.patchDaemonConfig({ pluginsEnabled: previous.config.pluginsEnabled });
|
||||
await client.close();
|
||||
await example.cleanup();
|
||||
await repo.cleanup();
|
||||
}
|
||||
}
|
||||
@@ -85,6 +85,8 @@ export interface ComboboxProps {
|
||||
}) => ReactElement;
|
||||
onSearchQueryChange?: (query: string) => void;
|
||||
searchable?: boolean;
|
||||
/** The caller answers the search query itself, so the options are shown as given. */
|
||||
remoteSearch?: boolean;
|
||||
placeholder?: string;
|
||||
searchPlaceholder?: string;
|
||||
emptyText?: string;
|
||||
@@ -1280,6 +1282,10 @@ function DesktopComboboxBody(props: DesktopBodyProps): ReactElement | null {
|
||||
);
|
||||
}
|
||||
|
||||
function filtersLocally(input: { searchable: boolean; remoteSearch?: boolean }): boolean {
|
||||
return input.searchable && !input.remoteSearch;
|
||||
}
|
||||
|
||||
export function Combobox({
|
||||
options,
|
||||
value,
|
||||
@@ -1287,6 +1293,7 @@ export function Combobox({
|
||||
renderOption,
|
||||
onSearchQueryChange,
|
||||
searchable = true,
|
||||
remoteSearch,
|
||||
placeholder,
|
||||
searchPlaceholder,
|
||||
emptyText,
|
||||
@@ -1446,7 +1453,7 @@ export function Combobox({
|
||||
buildVisibleComboboxOptions({
|
||||
options,
|
||||
searchQuery,
|
||||
searchable,
|
||||
searchable: filtersLocally({ searchable, remoteSearch }),
|
||||
allowCustomValue,
|
||||
customValuePrefix,
|
||||
customValueDescription,
|
||||
@@ -1458,6 +1465,7 @@ export function Combobox({
|
||||
customValueKind,
|
||||
customValuePrefix,
|
||||
options,
|
||||
remoteSearch,
|
||||
searchQuery,
|
||||
searchable,
|
||||
],
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import {
|
||||
createContext,
|
||||
forwardRef,
|
||||
useCallback,
|
||||
useContext,
|
||||
useMemo,
|
||||
@@ -14,6 +15,9 @@ import { StyleSheet } from "react-native-unistyles";
|
||||
import type { AgentControlIcon } from "@/agent-controls/icons";
|
||||
import type { SheetHeader } from "@/components/adaptive-modal-sheet";
|
||||
import { Combobox, type ComboboxOption } from "@/components/ui/combobox";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { FieldTrigger } from "@/screens/new-workspace/form/field-trigger";
|
||||
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";
|
||||
@@ -39,8 +43,9 @@ export interface ComposerControlChoice {
|
||||
}
|
||||
|
||||
/**
|
||||
* One control in the composer's toolbar, drawn from data. Provider option controls, thinking and
|
||||
* plugin controls all come through here, so each is an icon in the toolbar and a row in the sheet.
|
||||
* One control, drawn from data. Provider option controls, thinking and plugin controls all come
|
||||
* through here, so each is an icon in the composer toolbar, a row in its sheet, or, in a New
|
||||
* workspace item, a field. The name stays from when the composer was the only place it drew.
|
||||
*/
|
||||
export type ComposerControlItem =
|
||||
| (ComposerControlBase & {
|
||||
@@ -52,11 +57,17 @@ export type ComposerControlItem =
|
||||
type: "select";
|
||||
value: string | null;
|
||||
choices: readonly ComposerControlChoice[];
|
||||
/** Names a value the choices do not list, such as a pick that a search no longer returns. */
|
||||
valueLabel?: string;
|
||||
onChange: (value: string) => void | Promise<void>;
|
||||
/** The toolbar trigger shows only the icon. */
|
||||
iconOnly?: boolean;
|
||||
showCaret?: boolean;
|
||||
searchable?: boolean;
|
||||
/** The list answers `onSearchQueryChange` itself, so it is not filtered again. */
|
||||
remoteSearch?: boolean;
|
||||
onSearchQueryChange?: (query: string) => void;
|
||||
emptyText?: string;
|
||||
desktopMinWidth?: number;
|
||||
renderOption?: (args: {
|
||||
option: ComboboxOption;
|
||||
@@ -70,12 +81,21 @@ export type ComposerControlItem =
|
||||
onPress: () => void | Promise<void>;
|
||||
});
|
||||
|
||||
export type ComposerControlSurface = "toolbar" | "sheet";
|
||||
/** `field`: a New workspace setup field, a badge on desktop and a full-width field when compact. */
|
||||
export type ComposerControlSurface = "toolbar" | "sheet" | "field";
|
||||
|
||||
const ComposerControlSurfaceContext = createContext<ComposerControlSurface>("toolbar");
|
||||
export const ComposerControlSurfaceProvider = ComposerControlSurfaceContext.Provider;
|
||||
|
||||
/** Where the control being drawn sits: the toolbar, or a row in the overflow sheet. */
|
||||
const ComposerControlLockContext = createContext(false);
|
||||
/** Disables every control below it, for a surface that is not a composer and has its own lock. */
|
||||
export const ComposerControlLockProvider = ComposerControlLockContext.Provider;
|
||||
|
||||
export function useComposerControlLocked(): boolean {
|
||||
return useContext(ComposerControlLockContext);
|
||||
}
|
||||
|
||||
/** Where the control being drawn sits: the toolbar, a row in the overflow sheet, or a field. */
|
||||
export function useComposerControlSurface(): ComposerControlSurface {
|
||||
return useContext(ComposerControlSurfaceContext);
|
||||
}
|
||||
@@ -133,7 +153,9 @@ function describeControl(
|
||||
};
|
||||
}
|
||||
const choiceLabel =
|
||||
item.choices.find((choice) => choice.value === item.value)?.label ?? item.title;
|
||||
item.choices.find((choice) => choice.value === item.value)?.label ??
|
||||
item.valueLabel ??
|
||||
item.title;
|
||||
const iconOnly = item.iconOnly === true;
|
||||
return {
|
||||
options: item.choices.map((choice) => ({
|
||||
@@ -150,22 +172,24 @@ function describeControl(
|
||||
};
|
||||
}
|
||||
|
||||
export function ComposerControl({
|
||||
item,
|
||||
surface,
|
||||
disabled = false,
|
||||
open,
|
||||
onOpenChange,
|
||||
onActionComplete,
|
||||
}: ComposerControlProps) {
|
||||
const { t } = useTranslation();
|
||||
const anchorRef = useRef<View>(null);
|
||||
const isSheet = surface === "sheet";
|
||||
const sheetHeader = useMemo<SheetHeader>(() => ({ title: item.title }), [item.title]);
|
||||
const view = useMemo(() => describeControl(item, surface, t), [item, surface, t]);
|
||||
type SelectItem = Extract<ComposerControlItem, { type: "select" }>;
|
||||
|
||||
// A command that returns a promise keeps the control pending until it settles, and a failure
|
||||
// reaches the user the way a built-in live control's does.
|
||||
/** The list options only a select carries; a toggle's two-choice list has none of them. */
|
||||
function listProps(select: SelectItem | null) {
|
||||
if (!select) return { searchable: false };
|
||||
return {
|
||||
desktopMinWidth: select.desktopMinWidth,
|
||||
searchable: select.searchable,
|
||||
remoteSearch: select.remoteSearch,
|
||||
onSearchQueryChange: select.onSearchQueryChange,
|
||||
emptyText: select.emptyText,
|
||||
renderOption: select.renderOption,
|
||||
};
|
||||
}
|
||||
|
||||
// A command that returns a promise keeps the control pending until it settles, and a failure
|
||||
// reaches the user the way a built-in live control's does.
|
||||
function usePendingRun() {
|
||||
const toast = useToast();
|
||||
const [pending, setPending] = useState(false);
|
||||
const run = useCallback(
|
||||
@@ -183,6 +207,25 @@ export function ComposerControl({
|
||||
},
|
||||
[toast],
|
||||
);
|
||||
return { pending, run };
|
||||
}
|
||||
|
||||
export function ComposerControl({
|
||||
item,
|
||||
surface,
|
||||
disabled = false,
|
||||
open,
|
||||
onOpenChange,
|
||||
onActionComplete,
|
||||
}: ComposerControlProps) {
|
||||
const { t } = useTranslation();
|
||||
const anchorRef = useRef<View>(null);
|
||||
const isSheet = surface === "sheet";
|
||||
const isField = surface === "field";
|
||||
const sheetHeader = useMemo<SheetHeader>(() => ({ title: item.title }), [item.title]);
|
||||
const view = useMemo(() => describeControl(item, surface, t), [item, surface, t]);
|
||||
|
||||
const { pending, run } = usePendingRun();
|
||||
const handlePress = useCallback(() => {
|
||||
if (item.type === "toggle") run(() => item.onChange(!item.value));
|
||||
else if (item.type === "action") run(item.onPress);
|
||||
@@ -198,7 +241,17 @@ export function ComposerControl({
|
||||
);
|
||||
|
||||
const select = item.type === "select" ? item : null;
|
||||
const trigger = (
|
||||
const accessibilityLabel = item.accessibilityLabel ?? view.tooltip;
|
||||
const trigger = isField ? (
|
||||
<FieldControlTrigger
|
||||
ref={anchorRef}
|
||||
item={item}
|
||||
view={view}
|
||||
accessibilityLabel={accessibilityLabel}
|
||||
disabled={disabled || pending}
|
||||
onPress={view.opensList ? handleOpenPress : handlePress}
|
||||
/>
|
||||
) : (
|
||||
<AgentControlTrigger
|
||||
ref={anchorRef}
|
||||
icon={item.icon}
|
||||
@@ -211,14 +264,14 @@ export function ComposerControl({
|
||||
open={view.opensList && open}
|
||||
disabled={disabled || pending}
|
||||
onPress={view.opensList ? handleOpenPress : handlePress}
|
||||
accessibilityLabel={item.accessibilityLabel ?? view.tooltip}
|
||||
accessibilityLabel={accessibilityLabel}
|
||||
testID={item.testID}
|
||||
/>
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
{isSheet ? (
|
||||
{isSheet || isField ? (
|
||||
trigger
|
||||
) : (
|
||||
<Tooltip delayDuration={0} enabledOnDesktop enabledOnMobile={false}>
|
||||
@@ -239,10 +292,8 @@ export function ComposerControl({
|
||||
onOpenChange={onOpenChange}
|
||||
anchorRef={anchorRef}
|
||||
presentation={isSheet ? "push" : undefined}
|
||||
desktopPlacement={isSheet ? undefined : "top-start"}
|
||||
desktopMinWidth={select?.desktopMinWidth}
|
||||
searchable={select ? select.searchable : false}
|
||||
renderOption={select?.renderOption}
|
||||
desktopPlacement={DESKTOP_PLACEMENT[surface]}
|
||||
{...listProps(select)}
|
||||
header={isSheet ? sheetHeader : undefined}
|
||||
/>
|
||||
) : null}
|
||||
@@ -250,6 +301,50 @@ export function ComposerControl({
|
||||
);
|
||||
}
|
||||
|
||||
/** Where a list opens on desktop; the sheet has its own presentation. */
|
||||
const DESKTOP_PLACEMENT = {
|
||||
toolbar: "top-start",
|
||||
sheet: undefined,
|
||||
field: "bottom-start",
|
||||
} as const;
|
||||
|
||||
/** What a field shows: a badge has no label, so a toggle names itself beside its state. */
|
||||
function fieldValue(item: ComposerControlItem, view: ControlView, compact: boolean): string {
|
||||
if (item.type === "action") return item.title;
|
||||
if (item.type === "toggle" && !compact) return `${item.title}: ${view.value}`;
|
||||
return view.value;
|
||||
}
|
||||
|
||||
const FieldControlTrigger = forwardRef<
|
||||
View,
|
||||
{
|
||||
item: ComposerControlItem;
|
||||
view: ControlView;
|
||||
accessibilityLabel: string;
|
||||
disabled: boolean;
|
||||
onPress: () => void;
|
||||
}
|
||||
>(function FieldControlTrigger({ item, view, accessibilityLabel, disabled, onPress }, ref) {
|
||||
const compact = useIsCompactFormFactor();
|
||||
const Icon = item.icon;
|
||||
const iconColor = item.highlight ? styles[item.highlight].color : styles.fieldIcon.color;
|
||||
const icon = useMemo(() => <Icon size={ICON_SIZE.sm} color={iconColor} />, [Icon, iconColor]);
|
||||
return (
|
||||
<FieldTrigger
|
||||
ref={ref}
|
||||
variant={compact ? "field" : "badge"}
|
||||
label={item.title}
|
||||
icon={icon}
|
||||
value={fieldValue(item, view, compact)}
|
||||
tooltip={view.tooltip}
|
||||
accessibilityLabel={accessibilityLabel}
|
||||
disabled={disabled}
|
||||
onPress={onPress}
|
||||
testID={item.testID}
|
||||
/>
|
||||
);
|
||||
});
|
||||
|
||||
interface ComposerControlsProps {
|
||||
items: readonly ComposerControlItem[];
|
||||
surface: ComposerControlSurface;
|
||||
@@ -296,6 +391,7 @@ function ComposerControlSlot({
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
fieldIcon: { color: theme.colors.foregroundMuted },
|
||||
blue: { color: theme.colors.palette.blue[400] },
|
||||
green: { color: theme.colors.palette.green[400] },
|
||||
yellow: { color: theme.colors.palette.yellow[400] },
|
||||
|
||||
@@ -2,6 +2,11 @@ import { en, type TranslationResources } from "./en";
|
||||
import { pluginSettings } from "./plugin-settings";
|
||||
|
||||
export const ar: TranslationResources = {
|
||||
pluginCombobox: {
|
||||
searching: "جارٍ البحث…",
|
||||
empty: "لا توجد نتائج",
|
||||
failed: "فشل البحث: {{message}}",
|
||||
},
|
||||
paneFind: {
|
||||
connectionFailure: "تعذر البحث في هذه المحادثة. تحقق من الاتصال بالمضيف وأعد المحاولة.",
|
||||
historyChangedFailure: "تغيّرت المحادثة أثناء البحث. أعد البحث.",
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
export const en = {
|
||||
pluginCombobox: {
|
||||
searching: "Searching…",
|
||||
empty: "No results",
|
||||
failed: "Search failed: {{message}}",
|
||||
},
|
||||
paneFind: {
|
||||
connectionFailure: "Could not search this chat. Check the host connection and retry.",
|
||||
historyChangedFailure: "The chat changed while searching. Search again.",
|
||||
|
||||
@@ -2,6 +2,11 @@ import { en, type TranslationResources } from "./en";
|
||||
import { pluginSettings } from "./plugin-settings";
|
||||
|
||||
export const es: TranslationResources = {
|
||||
pluginCombobox: {
|
||||
searching: "Buscando…",
|
||||
empty: "Sin resultados",
|
||||
failed: "La búsqueda falló: {{message}}",
|
||||
},
|
||||
paneFind: {
|
||||
connectionFailure:
|
||||
"No se pudo buscar en este chat. Comprueba la conexión con el host y vuelve a intentarlo.",
|
||||
|
||||
@@ -2,6 +2,11 @@ import { en, type TranslationResources } from "./en";
|
||||
import { pluginSettings } from "./plugin-settings";
|
||||
|
||||
export const fr: TranslationResources = {
|
||||
pluginCombobox: {
|
||||
searching: "Recherche…",
|
||||
empty: "Aucun résultat",
|
||||
failed: "Échec de la recherche : {{message}}",
|
||||
},
|
||||
paneFind: {
|
||||
connectionFailure:
|
||||
"Impossible de rechercher dans cette conversation. Vérifiez la connexion à l’hôte et réessayez.",
|
||||
|
||||
@@ -2,6 +2,11 @@ import { en, type TranslationResources } from "./en";
|
||||
import { pluginSettings } from "./plugin-settings";
|
||||
|
||||
export const ja: TranslationResources = {
|
||||
pluginCombobox: {
|
||||
searching: "検索中…",
|
||||
empty: "結果がありません",
|
||||
failed: "検索に失敗しました: {{message}}",
|
||||
},
|
||||
paneFind: {
|
||||
connectionFailure:
|
||||
"このチャットを検索できませんでした。ホストへの接続を確認して再試行してください。",
|
||||
|
||||
@@ -2,6 +2,11 @@ import { en, type TranslationResources } from "./en";
|
||||
import { pluginSettings } from "./plugin-settings";
|
||||
|
||||
export const ko: TranslationResources = {
|
||||
pluginCombobox: {
|
||||
searching: "검색 중…",
|
||||
empty: "결과 없음",
|
||||
failed: "검색 실패: {{message}}",
|
||||
},
|
||||
paneFind: {
|
||||
connectionFailure: "이 채팅을 검색할 수 없습니다. 호스트 연결을 확인하고 다시 시도하세요.",
|
||||
historyChangedFailure: "검색 중에 채팅이 변경되었습니다. 다시 검색하세요.",
|
||||
|
||||
@@ -2,6 +2,11 @@ import { en, type TranslationResources } from "./en";
|
||||
import { pluginSettings } from "./plugin-settings";
|
||||
|
||||
export const ptBR: TranslationResources = {
|
||||
pluginCombobox: {
|
||||
searching: "Pesquisando…",
|
||||
empty: "Nenhum resultado",
|
||||
failed: "Falha na pesquisa: {{message}}",
|
||||
},
|
||||
paneFind: {
|
||||
connectionFailure:
|
||||
"Não foi possível pesquisar nesta conversa. Verifique a conexão com o host e tente novamente.",
|
||||
|
||||
@@ -2,6 +2,11 @@ import { en, type TranslationResources } from "./en";
|
||||
import { pluginSettings } from "./plugin-settings";
|
||||
|
||||
export const ru: TranslationResources = {
|
||||
pluginCombobox: {
|
||||
searching: "Поиск…",
|
||||
empty: "Нет результатов",
|
||||
failed: "Не удалось выполнить поиск: {{message}}",
|
||||
},
|
||||
paneFind: {
|
||||
connectionFailure:
|
||||
"Не удалось выполнить поиск в чате. Проверьте подключение к хосту и повторите попытку.",
|
||||
|
||||
@@ -2,6 +2,11 @@ import { en, type TranslationResources } from "./en";
|
||||
import { pluginSettings } from "./plugin-settings";
|
||||
|
||||
export const zhCN: TranslationResources = {
|
||||
pluginCombobox: {
|
||||
searching: "搜索中…",
|
||||
empty: "无结果",
|
||||
failed: "搜索失败:{{message}}",
|
||||
},
|
||||
paneFind: {
|
||||
connectionFailure: "无法搜索此聊天。请检查主机连接后重试。",
|
||||
historyChangedFailure: "搜索期间聊天已更改。请重新搜索。",
|
||||
|
||||
@@ -27,6 +27,7 @@ function installation(): InstalledPlugin {
|
||||
legacySidebarItems: [],
|
||||
filePanels: [],
|
||||
composerItems: [],
|
||||
newWorkspaceItems: [],
|
||||
workspacePanels: [],
|
||||
commandCenterItems: [],
|
||||
clientSlashCommands: [],
|
||||
|
||||
@@ -87,6 +87,7 @@ function plugin(onAgentSelect: AgentCommandItem["onSelect"]): InstalledPlugin {
|
||||
legacySidebarItems: [],
|
||||
filePanels: [],
|
||||
composerItems: [],
|
||||
newWorkspaceItems: [],
|
||||
workspacePanels: [
|
||||
{
|
||||
id: "details",
|
||||
|
||||
@@ -7,25 +7,12 @@ import {
|
||||
type ComposerControlSurface,
|
||||
} from "@/composer/agent-controls/composer-control";
|
||||
import { useComposerAgent, useComposerInput } from "@/composer/session";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { useToast } from "@/contexts/toast-api-context";
|
||||
import { useHosts } from "@/runtime/host-runtime";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
import { createPluginClientStateSource } from "../client-state/source";
|
||||
import { resolvePluginPlatform } from "../platform";
|
||||
import { PluginEnvironmentProvider, type PluginEnvironment } from "../popover";
|
||||
import { PluginItemList, pluginThemeMapping, usePluginItemHost } from "../item-host";
|
||||
import { PluginEnvironmentProvider } from "../popover";
|
||||
import { useInstalledPlugins } from "../registry";
|
||||
import { SurfaceErrorBoundary } from "../surface-error-boundary";
|
||||
import { toPluginTheme } from "../theme";
|
||||
import type { InstalledPlugin } from "../types";
|
||||
import { toPluginComposer } from "./model";
|
||||
|
||||
const pluginThemeMapping = (theme: Theme) => ({ theme: toPluginTheme(theme) });
|
||||
|
||||
function renderNothing() {
|
||||
return null;
|
||||
}
|
||||
|
||||
function useServerPlugins(serverId: string | null): InstalledPlugin[] {
|
||||
const installed = useInstalledPlugins();
|
||||
return useMemo(
|
||||
@@ -76,52 +63,23 @@ function PluginComposerItemsHost({
|
||||
}) {
|
||||
const agent = useComposerAgent();
|
||||
const composerInput = useComposerInput();
|
||||
const toast = useToast();
|
||||
const compact = useIsCompactFormFactor();
|
||||
const hosts = useHosts();
|
||||
const hostLabel =
|
||||
hosts.find((host) => host.serverId === plugin.serverId)?.label ?? plugin.serverId;
|
||||
const { environment, props } = usePluginItemHost(plugin, theme);
|
||||
const textSource = composerInput?.textSource;
|
||||
const prompt = useSyncExternalStore(
|
||||
textSource?.subscribe ?? subscribeNothing,
|
||||
textSource?.getSnapshot ?? emptyText,
|
||||
textSource?.getSnapshot ?? emptyText,
|
||||
);
|
||||
const environment = useMemo<PluginEnvironment>(
|
||||
() => ({
|
||||
installation: plugin,
|
||||
toast,
|
||||
state: createPluginClientStateSource(plugin.serverId),
|
||||
}),
|
||||
[plugin, toast],
|
||||
);
|
||||
const composer = useMemo(
|
||||
() =>
|
||||
agent && composerInput ? toPluginComposer({ plugin, agent, composerInput, prompt }) : null,
|
||||
[agent, composerInput, plugin, prompt],
|
||||
);
|
||||
const props = useMemo<PluginHostProps>(
|
||||
() => ({
|
||||
theme,
|
||||
host: { id: plugin.serverId, label: hostLabel },
|
||||
layout: { compact, platform: resolvePluginPlatform() },
|
||||
}),
|
||||
[compact, hostLabel, plugin.serverId, theme],
|
||||
);
|
||||
if (!composer) return null;
|
||||
return (
|
||||
<PluginEnvironmentProvider environment={environment}>
|
||||
<PluginComposerProvider composer={composer}>
|
||||
{plugin.composerItems.map(({ id, Component }) => (
|
||||
<SurfaceErrorBoundary
|
||||
key={id}
|
||||
installation={plugin}
|
||||
Surface={Component}
|
||||
renderError={renderNothing}
|
||||
>
|
||||
<Component {...props} />
|
||||
</SurfaceErrorBoundary>
|
||||
))}
|
||||
<PluginItemList plugin={plugin} items={plugin.composerItems} props={props} />
|
||||
</PluginComposerProvider>
|
||||
</PluginEnvironmentProvider>
|
||||
);
|
||||
|
||||
@@ -30,6 +30,7 @@ function installed(): InstalledPlugin {
|
||||
legacySidebarItems: [],
|
||||
filePanels: [],
|
||||
composerItems: [],
|
||||
newWorkspaceItems: [],
|
||||
workspacePanels: [],
|
||||
commandCenterItems: [],
|
||||
clientSlashCommands: [],
|
||||
|
||||
@@ -133,6 +133,7 @@ export function runPluginClientBundle(
|
||||
legacySidebarItems: [],
|
||||
filePanels: [],
|
||||
composerItems: [],
|
||||
newWorkspaceItems: [],
|
||||
workspacePanels: [],
|
||||
commandCenterItems: [],
|
||||
clientSlashCommands: [],
|
||||
@@ -149,6 +150,7 @@ export function runPluginClientBundle(
|
||||
};
|
||||
const filePanelIds = new Set<string>();
|
||||
const composerItemIds = new Set<string>();
|
||||
const newWorkspaceItemIds = new Set<string>();
|
||||
const workspacePanelIds = new Set<string>();
|
||||
const commandCenterItemIds = new Set<string>();
|
||||
const clientSlashCommandNames = new Set<string>();
|
||||
@@ -286,6 +288,20 @@ export function runPluginClientBundle(
|
||||
() => composerItemIds.delete(normalizedId),
|
||||
);
|
||||
},
|
||||
addNewWorkspaceItem(contribution) {
|
||||
const normalizedId = requireId(contribution.id, "New workspace item id");
|
||||
if (newWorkspaceItemIds.has(normalizedId))
|
||||
throw new Error(`Duplicate New workspace item: ${normalizedId}`);
|
||||
if (!isComponentType(contribution.Component)) {
|
||||
throw new Error(`New workspace item ${normalizedId} is not a component`);
|
||||
}
|
||||
newWorkspaceItemIds.add(normalizedId);
|
||||
return register(
|
||||
collector.newWorkspaceItems,
|
||||
{ id: normalizedId, Component: contribution.Component },
|
||||
() => newWorkspaceItemIds.delete(normalizedId),
|
||||
);
|
||||
},
|
||||
addSidebarHeaderItem(contribution: PluginSidebarItemContribution) {
|
||||
return addSidebarItem("header", contribution);
|
||||
},
|
||||
@@ -603,6 +619,7 @@ export function runPluginClientBundle(
|
||||
legacySidebarItems: collector.legacySidebarItems,
|
||||
filePanels: collector.filePanels,
|
||||
composerItems: collector.composerItems,
|
||||
newWorkspaceItems: collector.newWorkspaceItems,
|
||||
workspacePanels: collector.workspacePanels as EvaluatedPlugin["workspacePanels"],
|
||||
commandCenterItems: collector.commandCenterItems,
|
||||
clientSlashCommands: collector.clientSlashCommands,
|
||||
|
||||
@@ -40,6 +40,7 @@ function installation(invoked: string[]): InstalledPlugin {
|
||||
legacySidebarItems: [],
|
||||
filePanels: [],
|
||||
composerItems: [],
|
||||
newWorkspaceItems: [],
|
||||
workspacePanels: [],
|
||||
commandCenterItems: [],
|
||||
clientSlashCommands: [],
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
import { useMemo, type ComponentType } from "react";
|
||||
import type { PluginHostProps } from "@getpaseo/plugin/client";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { useToast } from "@/contexts/toast-api-context";
|
||||
import { useHosts } from "@/runtime/host-runtime";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
import { createPluginClientStateSource } from "./client-state/source";
|
||||
import { resolvePluginPlatform } from "./platform";
|
||||
import type { PluginEnvironment } from "./popover";
|
||||
import { SurfaceErrorBoundary } from "./surface-error-boundary";
|
||||
import { toPluginTheme } from "./theme";
|
||||
import type { InstalledPlugin } from "./types";
|
||||
|
||||
/** `withUnistyles` mapping that hands a host the plugin theme. */
|
||||
export const pluginThemeMapping = (theme: Theme) => ({ theme: toPluginTheme(theme) });
|
||||
|
||||
function renderNothing() {
|
||||
return null;
|
||||
}
|
||||
|
||||
/** What a plugin's items on a host surface (composer, New workspace) share: environment and props. */
|
||||
export function usePluginItemHost(
|
||||
plugin: InstalledPlugin,
|
||||
theme: PluginHostProps["theme"],
|
||||
): { environment: PluginEnvironment; props: PluginHostProps } {
|
||||
const toast = useToast();
|
||||
const compact = useIsCompactFormFactor();
|
||||
const hosts = useHosts();
|
||||
const hostLabel =
|
||||
hosts.find((host) => host.serverId === plugin.serverId)?.label ?? plugin.serverId;
|
||||
const environment = useMemo<PluginEnvironment>(
|
||||
() => ({
|
||||
installation: plugin,
|
||||
toast,
|
||||
state: createPluginClientStateSource(plugin.serverId),
|
||||
}),
|
||||
[plugin, toast],
|
||||
);
|
||||
const props = useMemo<PluginHostProps>(
|
||||
() => ({
|
||||
theme,
|
||||
host: { id: plugin.serverId, label: hostLabel },
|
||||
layout: { compact, platform: resolvePluginPlatform() },
|
||||
}),
|
||||
[compact, hostLabel, plugin.serverId, theme],
|
||||
);
|
||||
return { environment, props };
|
||||
}
|
||||
|
||||
/** Mounts each item behind its own boundary; a throwing item draws nothing. */
|
||||
export function PluginItemList({
|
||||
plugin,
|
||||
items,
|
||||
props,
|
||||
}: {
|
||||
plugin: InstalledPlugin;
|
||||
items: readonly { id: string; Component: ComponentType<PluginHostProps> }[];
|
||||
props: PluginHostProps;
|
||||
}) {
|
||||
return (
|
||||
<>
|
||||
{items.map(({ id, Component }) => (
|
||||
<SurfaceErrorBoundary
|
||||
key={id}
|
||||
installation={plugin}
|
||||
Surface={Component}
|
||||
renderError={renderNothing}
|
||||
>
|
||||
<Component {...props} />
|
||||
</SurfaceErrorBoundary>
|
||||
))}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
import { useMemo } from "react";
|
||||
import type { PluginHostProps } from "@getpaseo/plugin/client";
|
||||
import { PluginNewWorkspaceProvider } from "@getpaseo/plugin/client/host";
|
||||
import { withUnistyles } from "react-native-unistyles";
|
||||
import {
|
||||
ComposerControlLockProvider,
|
||||
ComposerControlSurfaceProvider,
|
||||
} from "@/composer/agent-controls/composer-control";
|
||||
import type { PickerItem } from "@/screens/new-workspace-picker-item";
|
||||
import {
|
||||
useNewWorkspaceSetupState,
|
||||
type NewWorkspaceSetup,
|
||||
} from "@/screens/new-workspace/setup-model";
|
||||
import { PluginItemList, pluginThemeMapping, usePluginItemHost } from "../item-host";
|
||||
import { PluginEnvironmentProvider } from "../popover";
|
||||
import { useInstalledPlugins } from "../registry";
|
||||
import type { InstalledPlugin } from "../types";
|
||||
import { toPluginNewWorkspace } from "./model";
|
||||
|
||||
/** What the screen derives and the items read; the rest is in the setup model. */
|
||||
export interface NewWorkspaceItemsScreen {
|
||||
project: { id: string; name: string } | null;
|
||||
isolation: "local" | "worktree";
|
||||
baseItem: PickerItem | null;
|
||||
locked: boolean;
|
||||
}
|
||||
|
||||
function useServerPlugins(serverId: string): InstalledPlugin[] {
|
||||
const installed = useInstalledPlugins();
|
||||
return useMemo(
|
||||
() =>
|
||||
installed.filter(
|
||||
(plugin) => plugin.serverId === serverId && plugin.newWorkspaceItems.length > 0,
|
||||
),
|
||||
[installed, serverId],
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The selected host's plugin items on the New workspace screen, drawn as setup fields. They read
|
||||
* the screen's choices and command them through the setup model.
|
||||
*/
|
||||
export function PluginNewWorkspaceItems({
|
||||
serverId,
|
||||
screen,
|
||||
setup,
|
||||
}: {
|
||||
serverId: string;
|
||||
screen: NewWorkspaceItemsScreen;
|
||||
setup: NewWorkspaceSetup;
|
||||
}) {
|
||||
const plugins = useServerPlugins(serverId);
|
||||
return (
|
||||
<ComposerControlSurfaceProvider value="field">
|
||||
<ComposerControlLockProvider value={screen.locked}>
|
||||
{plugins.map((plugin) => (
|
||||
<ThemedPluginNewWorkspaceItems
|
||||
key={plugin.id}
|
||||
plugin={plugin}
|
||||
screen={screen}
|
||||
setup={setup}
|
||||
uniProps={pluginThemeMapping}
|
||||
/>
|
||||
))}
|
||||
</ComposerControlLockProvider>
|
||||
</ComposerControlSurfaceProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function PluginNewWorkspaceItemsHost({
|
||||
plugin,
|
||||
theme,
|
||||
screen,
|
||||
setup,
|
||||
}: {
|
||||
plugin: InstalledPlugin;
|
||||
theme: PluginHostProps["theme"];
|
||||
screen: NewWorkspaceItemsScreen;
|
||||
setup: NewWorkspaceSetup;
|
||||
}) {
|
||||
const { environment, props } = usePluginItemHost(plugin, theme);
|
||||
const { branch, metadata } = useNewWorkspaceSetupState(setup);
|
||||
const newWorkspace = useMemo(
|
||||
() =>
|
||||
toPluginNewWorkspace({
|
||||
host: props.host,
|
||||
view: { ...screen, branch, metadata },
|
||||
commands: setup.commands,
|
||||
}),
|
||||
[branch, metadata, props.host, screen, setup.commands],
|
||||
);
|
||||
return (
|
||||
<PluginEnvironmentProvider environment={environment}>
|
||||
<PluginNewWorkspaceProvider newWorkspace={newWorkspace}>
|
||||
<PluginItemList plugin={plugin} items={plugin.newWorkspaceItems} props={props} />
|
||||
</PluginNewWorkspaceProvider>
|
||||
</PluginEnvironmentProvider>
|
||||
);
|
||||
}
|
||||
|
||||
const ThemedPluginNewWorkspaceItems = withUnistyles(PluginNewWorkspaceItemsHost);
|
||||
@@ -0,0 +1,40 @@
|
||||
import type { JsonValue } from "@getpaseo/protocol/agent-types";
|
||||
import type { PluginHostProps, PluginNewWorkspace } from "@getpaseo/plugin/client";
|
||||
import { branchNameFromRef, type PickerItem } from "@/screens/new-workspace-picker-item";
|
||||
import type { SetupCommands } from "@/screens/new-workspace/setup-model";
|
||||
import { cloneAndFreeze } from "../freeze";
|
||||
|
||||
/** What the New workspace screen shows at render; the plugin reads it, never writes it. */
|
||||
export interface NewWorkspaceView {
|
||||
project: { id: string; name: string } | null;
|
||||
/** What the screen will create. */
|
||||
isolation: "local" | "worktree";
|
||||
baseItem: PickerItem | null;
|
||||
branch: string | null;
|
||||
metadata: Readonly<Record<string, JsonValue>>;
|
||||
locked: boolean;
|
||||
}
|
||||
|
||||
function toBaseRef(item: PickerItem | null): PluginNewWorkspace["baseRef"] {
|
||||
if (!item) return null;
|
||||
return item.kind === "branch"
|
||||
? { type: "branch", name: branchNameFromRef(item.refName) }
|
||||
: { type: "change-request", number: item.item.number };
|
||||
}
|
||||
|
||||
export function toPluginNewWorkspace(input: {
|
||||
host: PluginHostProps["host"];
|
||||
view: NewWorkspaceView;
|
||||
commands: SetupCommands;
|
||||
}): PluginNewWorkspace {
|
||||
const { host, view, commands } = input;
|
||||
return {
|
||||
host: { id: host.id, label: host.label },
|
||||
project: cloneAndFreeze(view.project),
|
||||
isolation: view.isolation,
|
||||
baseRef: toBaseRef(view.baseItem),
|
||||
branch: view.branch,
|
||||
metadata: cloneAndFreeze(view.metadata),
|
||||
...commands,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
import React from "react";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { ComboboxItem } from "@getpaseo/plugin/client/ui";
|
||||
import type { ToastApi } from "@/components/toast-host";
|
||||
import { ComposerControlSurfaceProvider } from "@/composer/agent-controls/composer-control";
|
||||
import { ToastApiProvider } from "@/contexts/toast-api-context";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
import { Combobox } from "./composer-controls";
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.stubGlobal("React", React);
|
||||
await i18n.changeLanguage("en");
|
||||
});
|
||||
afterEach(cleanup);
|
||||
|
||||
interface Issue extends ComboboxItem {
|
||||
branch: string;
|
||||
}
|
||||
|
||||
const ONE: Issue = { id: "1", label: "Slow sidebar", branch: "one" };
|
||||
const TWO: Issue = { id: "2", label: "Crash on resume", branch: "two" };
|
||||
|
||||
interface Search {
|
||||
query: string;
|
||||
resolve(items: Issue[]): void;
|
||||
reject(error: Error): void;
|
||||
}
|
||||
|
||||
/** A search the test settles by hand, so it decides which one finishes first. */
|
||||
function controlledSearch() {
|
||||
const searches: Search[] = [];
|
||||
const search = ({ query }: { query: string }) =>
|
||||
new Promise<Issue[]>((resolve, reject) => {
|
||||
searches.push({ query, resolve, reject });
|
||||
});
|
||||
const forQuery = (query: string) => {
|
||||
const found = searches.find((candidate) => candidate.query === query);
|
||||
if (!found) throw new Error(`No search for "${query}" yet`);
|
||||
return found;
|
||||
};
|
||||
return { search, forQuery, queries: () => searches.map((candidate) => candidate.query) };
|
||||
}
|
||||
|
||||
const toast = { error: vi.fn() } as unknown as ToastApi;
|
||||
const ignoreSelect = () => undefined;
|
||||
|
||||
function Harness({
|
||||
search,
|
||||
value,
|
||||
onSelect = ignoreSelect,
|
||||
}: {
|
||||
search: (event: { query: string }) => Promise<Issue[]>;
|
||||
value: ComboboxItem | null;
|
||||
onSelect?: (event: { item: Issue }) => void;
|
||||
}) {
|
||||
const [queryClient] = React.useState(() => new QueryClient());
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ToastApiProvider api={toast}>
|
||||
<ComposerControlSurfaceProvider value="field">
|
||||
<Combobox
|
||||
title="Issue"
|
||||
icon="CircleDot"
|
||||
value={value}
|
||||
search={search}
|
||||
onSelect={onSelect}
|
||||
/>
|
||||
</ComposerControlSurfaceProvider>
|
||||
</ToastApiProvider>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function renderCombobox(input: {
|
||||
search: (event: { query: string }) => Promise<Issue[]>;
|
||||
value?: ComboboxItem | null;
|
||||
onSelect?: (event: { item: Issue }) => void;
|
||||
}) {
|
||||
render(<Harness search={input.search} value={input.value ?? null} onSelect={input.onSelect} />);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Issue" }));
|
||||
}
|
||||
|
||||
describe("plugin Combobox", () => {
|
||||
it("searches when the list opens, shows the results, and hands the picked item back", async () => {
|
||||
const controlled = controlledSearch();
|
||||
const onSelect = vi.fn();
|
||||
renderCombobox({ search: controlled.search, onSelect });
|
||||
|
||||
await waitFor(() => expect(controlled.queries()).toEqual([""]));
|
||||
expect(screen.getByText("Searching…")).toBeTruthy();
|
||||
controlled.forQuery("").resolve([ONE, TWO]);
|
||||
|
||||
fireEvent.click(await screen.findByText("Crash on resume"));
|
||||
expect(onSelect).toHaveBeenCalledWith({ item: TWO });
|
||||
});
|
||||
|
||||
it("shows the error and not stale results when the search fails", async () => {
|
||||
const controlled = controlledSearch();
|
||||
renderCombobox({ search: controlled.search });
|
||||
|
||||
await waitFor(() => expect(controlled.queries()).toEqual([""]));
|
||||
controlled.forQuery("").reject(new Error("tracker is down"));
|
||||
|
||||
expect(await screen.findByText("Search failed: tracker is down")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("keeps the previous results while a newer search runs and ignores a superseded one", async () => {
|
||||
const controlled = controlledSearch();
|
||||
renderCombobox({ search: controlled.search });
|
||||
await waitFor(() => expect(controlled.queries()).toEqual([""]));
|
||||
controlled.forQuery("").resolve([ONE, TWO]);
|
||||
await screen.findByText("Slow sidebar");
|
||||
|
||||
const input = screen.getByRole("textbox");
|
||||
fireEvent.change(input, { target: { value: "c" } });
|
||||
await waitFor(() => expect(controlled.queries()).toEqual(["", "c"]));
|
||||
expect(screen.getByText("Slow sidebar")).toBeTruthy();
|
||||
|
||||
fireEvent.change(input, { target: { value: "cr" } });
|
||||
await waitFor(() => expect(controlled.queries()).toEqual(["", "c", "cr"]));
|
||||
controlled.forQuery("cr").resolve([TWO]);
|
||||
await waitFor(() => expect(screen.queryByText("Slow sidebar")).toBeNull());
|
||||
controlled.forQuery("c").resolve([ONE]);
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
expect(screen.getByText("Crash on resume")).toBeTruthy();
|
||||
expect(screen.queryByText("Slow sidebar")).toBeNull();
|
||||
});
|
||||
|
||||
it("shows a chosen value that the search no longer returns", async () => {
|
||||
const controlled = controlledSearch();
|
||||
renderCombobox({ search: controlled.search, value: { id: "9", label: "PAS-9 Old issue" } });
|
||||
|
||||
expect(screen.getByRole("button", { name: "Issue" }).textContent).toContain("PAS-9 Old issue");
|
||||
await waitFor(() => expect(controlled.queries()).toEqual([""]));
|
||||
controlled.forQuery("").resolve([ONE]);
|
||||
await screen.findByText("Slow sidebar");
|
||||
expect(screen.getByRole("button", { name: "Issue" }).textContent).toContain("PAS-9 Old issue");
|
||||
});
|
||||
});
|
||||
@@ -1,11 +1,21 @@
|
||||
import type { ActionProps, SelectProps, ToggleProps } from "@getpaseo/plugin/client/ui";
|
||||
import { useMemo, useState } from "react";
|
||||
import type {
|
||||
ActionProps,
|
||||
ComboboxItem,
|
||||
ComboboxProps,
|
||||
SelectProps,
|
||||
ToggleProps,
|
||||
} from "@getpaseo/plugin/client/ui";
|
||||
import { useEffect, useId, useMemo, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
ComposerControl,
|
||||
useComposerControlLocked,
|
||||
useComposerControlSurface,
|
||||
type ComposerControlItem,
|
||||
} from "@/composer/agent-controls/composer-control";
|
||||
import { useComposerLocked } from "@/composer/session";
|
||||
import { useFetchQuery } from "@/data/query";
|
||||
import { toErrorMessage } from "@/utils/error-messages";
|
||||
import { parsePluginIcon, pluginIconComponent } from "../icons";
|
||||
|
||||
/** Icons resolve at render, so an invalid one throws to the item's boundary. */
|
||||
@@ -13,24 +23,35 @@ function usePluginControlIcon(icon: ToggleProps["icon"]) {
|
||||
return useMemo(() => pluginIconComponent(parsePluginIcon("Composer control", icon)), [icon]);
|
||||
}
|
||||
|
||||
/** Draws one plugin control where its composer item sits: inline, or as a row in the sheet. */
|
||||
/** Draws one plugin control where its item sits: inline, a row in the sheet, or a field. */
|
||||
function PluginComposerControl({
|
||||
item,
|
||||
disabled,
|
||||
onOpenChange,
|
||||
}: {
|
||||
item: ComposerControlItem;
|
||||
disabled: boolean | undefined;
|
||||
onOpenChange?: (open: boolean) => void;
|
||||
}) {
|
||||
const surface = useComposerControlSurface();
|
||||
const locked = useComposerLocked();
|
||||
const composerLocked = useComposerLocked();
|
||||
const fieldLocked = useComposerControlLocked();
|
||||
const locked = composerLocked || fieldLocked;
|
||||
const [open, setOpen] = useState(false);
|
||||
const handleOpenChange = useMemo(
|
||||
() => (next: boolean) => {
|
||||
setOpen(next);
|
||||
onOpenChange?.(next);
|
||||
},
|
||||
[onOpenChange],
|
||||
);
|
||||
return (
|
||||
<ComposerControl
|
||||
item={item}
|
||||
surface={surface}
|
||||
disabled={disabled || locked}
|
||||
open={open}
|
||||
onOpenChange={setOpen}
|
||||
onOpenChange={handleOpenChange}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -85,3 +106,82 @@ export function Action({ title, icon, disabled, onPress }: ActionProps) {
|
||||
);
|
||||
return <PluginComposerControl item={item} disabled={disabled} />;
|
||||
}
|
||||
|
||||
const SEARCH_DEBOUNCE_MS = 200;
|
||||
const NO_RESULTS: readonly never[] = [];
|
||||
|
||||
/** The query settles after the user stops typing; an empty query applies at once. */
|
||||
function useDebounced(query: string): string {
|
||||
const [settled, setSettled] = useState(query);
|
||||
useEffect(() => {
|
||||
if (query === "") return setSettled("");
|
||||
const timer = setTimeout(() => setSettled(query), SEARCH_DEBOUNCE_MS);
|
||||
return () => clearTimeout(timer);
|
||||
}, [query]);
|
||||
return settled;
|
||||
}
|
||||
|
||||
/**
|
||||
* Searches while the list is open. The search runs once per settled query, keeps the previous
|
||||
* results on screen while the next one loads, and drops a search a newer one replaced.
|
||||
*/
|
||||
export function Combobox<Item extends ComboboxItem>({
|
||||
title,
|
||||
icon,
|
||||
disabled,
|
||||
value,
|
||||
search,
|
||||
onSelect,
|
||||
}: ComboboxProps<Item>) {
|
||||
const { t } = useTranslation();
|
||||
const Icon = usePluginControlIcon(icon);
|
||||
const instanceId = useId();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [query, setQuery] = useState("");
|
||||
const settled = useDebounced(query);
|
||||
const results = useFetchQuery({
|
||||
queryKey: ["plugin-combobox", instanceId, settled],
|
||||
queryFn: () => search({ query: settled }),
|
||||
dataShape: "list",
|
||||
staleTimeMs: 0,
|
||||
enabled: open,
|
||||
gcTime: 0,
|
||||
retry: false,
|
||||
});
|
||||
const items: readonly Item[] = results.data ?? NO_RESULTS;
|
||||
const item = useMemo<ComposerControlItem>(() => {
|
||||
const choices = items.map(({ id, label, description }) => ({ value: id, label, description }));
|
||||
return {
|
||||
id: "plugin-combobox",
|
||||
type: "select",
|
||||
title,
|
||||
icon: Icon,
|
||||
value: value?.id ?? null,
|
||||
valueLabel: value?.label,
|
||||
choices,
|
||||
onChange: (id) => {
|
||||
const picked = items.find((candidate) => candidate.id === id);
|
||||
return picked ? onSelect({ item: picked }) : undefined;
|
||||
},
|
||||
searchable: true,
|
||||
remoteSearch: true,
|
||||
onSearchQueryChange: setQuery,
|
||||
emptyText: comboboxEmptyText({ t, results, query, settled }),
|
||||
showCaret: true,
|
||||
};
|
||||
}, [Icon, items, onSelect, query, results, settled, t, title, value]);
|
||||
return <PluginComposerControl item={item} disabled={disabled} onOpenChange={setOpen} />;
|
||||
}
|
||||
|
||||
function comboboxEmptyText(input: {
|
||||
t: (key: string, options?: Record<string, unknown>) => string;
|
||||
results: { isError: boolean; isFetching: boolean; error: unknown };
|
||||
query: string;
|
||||
settled: string;
|
||||
}): string {
|
||||
const { t, results, query, settled } = input;
|
||||
if (results.isError)
|
||||
return t("pluginCombobox.failed", { message: toErrorMessage(results.error) });
|
||||
if (results.isFetching || query !== settled) return t("pluginCombobox.searching");
|
||||
return t("pluginCombobox.empty");
|
||||
}
|
||||
|
||||
@@ -20,7 +20,7 @@ export { FilePanelLoading as Loading } from "@/file-panels/loading";
|
||||
export { SettingsGroup } from "@/components/settings";
|
||||
|
||||
export { Icon } from "../icons";
|
||||
export { Action, Select, Toggle } from "./composer-controls";
|
||||
export { Action, Combobox, Select, Toggle } from "./composer-controls";
|
||||
export { Modal } from "./modal";
|
||||
export { ScrollView, FlatList } from "./scroll-view";
|
||||
export { TextInput } from "./text-input";
|
||||
|
||||
@@ -126,6 +126,7 @@ export class PluginRegistry {
|
||||
legacySidebarItems: [],
|
||||
filePanels: [],
|
||||
composerItems: [],
|
||||
newWorkspaceItems: [],
|
||||
workspacePanels: [],
|
||||
commandCenterItems: [],
|
||||
clientSlashCommands: [],
|
||||
|
||||
@@ -38,6 +38,7 @@ function installed(
|
||||
legacySidebarItems,
|
||||
filePanels: [],
|
||||
composerItems: [],
|
||||
newWorkspaceItems: [],
|
||||
workspacePanels: [],
|
||||
commandCenterItems: [],
|
||||
clientSlashCommands: [],
|
||||
|
||||
@@ -57,6 +57,7 @@ function installation(
|
||||
})),
|
||||
filePanels: [],
|
||||
composerItems: [],
|
||||
newWorkspaceItems: [],
|
||||
workspacePanels: [],
|
||||
commandCenterItems: [],
|
||||
clientSlashCommands: [],
|
||||
|
||||
@@ -65,6 +65,7 @@ function installed(serverId: string, themes: PluginThemeContribution[]): Install
|
||||
legacySidebarItems: [],
|
||||
filePanels: [],
|
||||
composerItems: [],
|
||||
newWorkspaceItems: [],
|
||||
workspacePanels: [],
|
||||
commandCenterItems: [],
|
||||
clientSlashCommands: [],
|
||||
|
||||
@@ -28,6 +28,7 @@ function plugin(input: {
|
||||
legacySidebarItems: [],
|
||||
filePanels: [],
|
||||
composerItems: [],
|
||||
newWorkspaceItems: [],
|
||||
workspacePanels: [],
|
||||
commandCenterItems: [],
|
||||
clientSlashCommands: [],
|
||||
|
||||
@@ -12,6 +12,7 @@ import type {
|
||||
PluginCommandCenterItemContribution as SDKPluginCommandCenterItemContribution,
|
||||
PluginClientSlashCommandContribution as SDKPluginClientSlashCommandContribution,
|
||||
PluginComposerItemContribution,
|
||||
PluginNewWorkspaceItemContribution,
|
||||
PluginComposerPillContribution as SDKPluginComposerPillContribution,
|
||||
PluginSidebarContribution as SDKPluginSidebarContribution,
|
||||
PluginSidebarItemContribution as SDKPluginSidebarItemContribution,
|
||||
@@ -55,6 +56,7 @@ export interface EvaluatedPlugin {
|
||||
legacySidebarItems: PluginSidebarContribution[];
|
||||
filePanels: PluginFilePanelContribution[];
|
||||
composerItems: PluginComposerItemContribution[];
|
||||
newWorkspaceItems: PluginNewWorkspaceItemContribution[];
|
||||
workspacePanels: EvaluatedPluginWorkspacePanelContribution[];
|
||||
commandCenterItems: PluginCommandCenterItemContribution[];
|
||||
clientSlashCommands: PluginClientSlashCommandContribution[];
|
||||
@@ -87,6 +89,7 @@ export type {
|
||||
PluginCommandCenterItemContribution,
|
||||
PluginClientSlashCommandContribution,
|
||||
PluginComposerItemContribution,
|
||||
PluginNewWorkspaceItemContribution,
|
||||
PluginComposerPillContribution,
|
||||
PluginSidebarContribution,
|
||||
PluginSidebarItemContribution,
|
||||
|
||||
@@ -25,6 +25,7 @@ function installed(): InstalledPlugin {
|
||||
legacySidebarItems: [],
|
||||
filePanels: [],
|
||||
composerItems: [],
|
||||
newWorkspaceItems: [],
|
||||
workspacePanels: [
|
||||
{
|
||||
id: "details",
|
||||
|
||||
@@ -132,7 +132,7 @@ export interface BaseRefCheckoutStatus {
|
||||
|
||||
// Display only. The exact ref is what every request carries; this is just how a ref reads in
|
||||
// a row label, so "refs/remotes/origin/other-name" shows as "other-name".
|
||||
function branchNameFromRef(refName: string): string {
|
||||
export function branchNameFromRef(refName: string): string {
|
||||
if (refName.startsWith("refs/heads/")) return refName.slice("refs/heads/".length);
|
||||
if (refName.startsWith(REMOTE_TRACKING_PREFIX)) {
|
||||
const remainder = refName.slice(REMOTE_TRACKING_PREFIX.length);
|
||||
|
||||
@@ -6,7 +6,7 @@ import type {
|
||||
import type { AgentSnapshotPayload, CreationSnapshot } from "@getpaseo/protocol/messages";
|
||||
import { encodeImages } from "@/utils/encode-images";
|
||||
import { getHostRuntimeStore } from "@/runtime/host-runtime";
|
||||
import { useCallback, useEffect, useMemo, useReducer, useRef, useState } from "react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import type { ReactNode } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Text, View } from "react-native";
|
||||
@@ -78,7 +78,7 @@ import type { MessagePayload } from "@/composer/types";
|
||||
import type { UserComposerAttachment } from "@/attachments/types";
|
||||
import type { AgentAttachment, ForgeSearchItem } from "@getpaseo/protocol/messages";
|
||||
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import type { AgentProvider } from "@getpaseo/protocol/agent-types";
|
||||
import type { AgentProvider, JsonValue } from "@getpaseo/protocol/agent-types";
|
||||
import type { WorkspaceDraftTabSetup, WorkspaceTabTarget } from "@/workspace-tabs/model";
|
||||
import { isEmptyWorkspaceSubmission, runCreateEmptyWorkspace } from "./new-workspace-empty";
|
||||
import {
|
||||
@@ -97,10 +97,18 @@ import {
|
||||
} from "./new-workspace-picker-item";
|
||||
import {
|
||||
clearPickerPrAttachmentForTargetChange,
|
||||
initialPickerSelectionState,
|
||||
reducePickerSelection,
|
||||
syncPickerPrAttachment,
|
||||
} from "./new-workspace-picker-state";
|
||||
import {
|
||||
PluginNewWorkspaceItems,
|
||||
type NewWorkspaceItemsScreen,
|
||||
} from "@/plugins/new-workspace-items";
|
||||
import {
|
||||
createNewWorkspaceSetup,
|
||||
useNewWorkspaceSetupState,
|
||||
type NewWorkspaceSetup,
|
||||
type SetupFacts,
|
||||
} from "./new-workspace/setup-model";
|
||||
import {
|
||||
resolveNewWorkspaceAutomaticServerId,
|
||||
resolveNewWorkspaceInitialServerId,
|
||||
@@ -194,13 +202,14 @@ interface WorkspaceIsolationState {
|
||||
function useWorkspaceIsolation(input: {
|
||||
supportsMultiplicity: boolean;
|
||||
worktreeSupport: "supported" | "unsupported" | "unknown";
|
||||
manualIsolation: "local" | "worktree" | null;
|
||||
setManualIsolation: (value: "local" | "worktree") => void;
|
||||
}): WorkspaceIsolationState {
|
||||
const { supportsMultiplicity, worktreeSupport } = input;
|
||||
const { supportsMultiplicity, worktreeSupport, manualIsolation, setManualIsolation } = input;
|
||||
// The last isolation choice is remembered alongside the other New Workspace
|
||||
// form preferences (provider, model, mode). A manual in-screen pick overrides
|
||||
// the remembered default until the screen remounts.
|
||||
const { preferences, updatePreferences } = useFormPreferences();
|
||||
const [manualIsolation, setManualIsolation] = useState<"local" | "worktree" | null>(null);
|
||||
const isolation = manualIsolation ?? preferences.isolation ?? "local";
|
||||
const canCreateWorktree = supportsMultiplicity && worktreeSupport !== "unsupported";
|
||||
const isWorktree = isolation === "worktree" && canCreateWorktree;
|
||||
@@ -210,7 +219,7 @@ function useWorkspaceIsolation(input: {
|
||||
setManualIsolation(value);
|
||||
void updatePreferences({ isolation: value });
|
||||
},
|
||||
[updatePreferences],
|
||||
[setManualIsolation, updatePreferences],
|
||||
);
|
||||
|
||||
return {
|
||||
@@ -287,6 +296,10 @@ async function createMultiplicityWorkspace(input: {
|
||||
project: HostProjectListItem;
|
||||
sourceDirectory: string;
|
||||
checkoutRequest: PickerCheckoutRequest | undefined;
|
||||
/** Names the new branch of a worktree cut from a branch. */
|
||||
branchName: string | null;
|
||||
/** Stored on the created workspace. */
|
||||
metadata: Readonly<Record<string, JsonValue>>;
|
||||
withInitialAgent: boolean;
|
||||
agent?: CreateWorkspaceRequestOptions["agent"];
|
||||
onEvent?: (snapshot: CreationSnapshot) => void;
|
||||
@@ -317,6 +330,9 @@ async function createMultiplicityWorkspace(input: {
|
||||
projectId,
|
||||
worktreeSlug: input.worktreeSlug,
|
||||
...input.checkoutRequest,
|
||||
...(input.branchName && input.checkoutRequest?.action === "branch-off"
|
||||
? { branchName: input.branchName }
|
||||
: {}),
|
||||
}
|
||||
: {
|
||||
kind: "directory",
|
||||
@@ -324,6 +340,7 @@ async function createMultiplicityWorkspace(input: {
|
||||
projectId,
|
||||
},
|
||||
...(firstAgentContext ? { firstAgentContext } : {}),
|
||||
...(Object.keys(input.metadata).length > 0 ? { metadata: { ...input.metadata } } : {}),
|
||||
});
|
||||
if (payload.error || !payload.workspace) {
|
||||
throw new Error(payload.error ?? input.createFailedMessage);
|
||||
@@ -1001,22 +1018,24 @@ export function NewWorkspaceScreen({
|
||||
}),
|
||||
});
|
||||
const composerState = chatDraft.composerState;
|
||||
const [pickerSelection, dispatchPickerSelection] = useReducer(
|
||||
reducePickerSelection,
|
||||
initialPickerSelectionState,
|
||||
);
|
||||
const selectedItem = pickerSelection.selectedItem;
|
||||
const [setup] = useState(createNewWorkspaceSetup);
|
||||
const setupState = useNewWorkspaceSetupState(setup);
|
||||
const dispatchPickerSelection = setup.dispatchPicker;
|
||||
const selectedItem = setupState.pickerSelection.selectedItem;
|
||||
|
||||
const handleForgeChangeRequestDetected = useCallback(() => {
|
||||
dispatchPickerSelection({ type: "pr-detected" });
|
||||
}, []);
|
||||
}, [dispatchPickerSelection]);
|
||||
|
||||
const handleForgeChangeRequestAutoAttach = useCallback((item: ForgeSearchItem) => {
|
||||
dispatchPickerSelection({
|
||||
type: "pr-added",
|
||||
item: { kind: "github-pr", item },
|
||||
});
|
||||
}, []);
|
||||
const handleForgeChangeRequestAutoAttach = useCallback(
|
||||
(item: ForgeSearchItem) => {
|
||||
dispatchPickerSelection({
|
||||
type: "pr-added",
|
||||
item: { kind: "github-pr", item },
|
||||
});
|
||||
},
|
||||
[dispatchPickerSelection],
|
||||
);
|
||||
|
||||
const withConnectedClient = useCallback(() => {
|
||||
const connectedClient = getHostRuntimeStore().getClient(selectedServerId);
|
||||
@@ -1043,6 +1062,8 @@ export function NewWorkspaceScreen({
|
||||
useWorkspaceIsolation({
|
||||
supportsMultiplicity: supportsWorkspaceMultiplicity,
|
||||
worktreeSupport,
|
||||
manualIsolation: setupState.manualIsolation,
|
||||
setManualIsolation: setup.setManualIsolation,
|
||||
});
|
||||
|
||||
const branchSuggestionsQuery = useQuery({
|
||||
@@ -1116,9 +1137,21 @@ export function NewWorkspaceScreen({
|
||||
chatDraft.setAttachments(nextAttachments);
|
||||
setPickerOpen(false);
|
||||
},
|
||||
[chatDraft],
|
||||
[chatDraft, dispatchPickerSelection],
|
||||
);
|
||||
|
||||
const pluginScreen = usePluginSetup({
|
||||
setup,
|
||||
serverId: selectedServerId,
|
||||
project: selectedProject,
|
||||
baseItem,
|
||||
isolation: effectiveIsolation,
|
||||
canCreateWorktree,
|
||||
locked: isPending,
|
||||
chooseIsolation: setIsolation,
|
||||
chooseBase: selectPickerItem,
|
||||
});
|
||||
|
||||
const handleSelectOption = useCallback(
|
||||
(id: string) => {
|
||||
const item = itemById.get(id);
|
||||
@@ -1139,7 +1172,7 @@ export function NewWorkspaceScreen({
|
||||
chatDraft.setAttachments(nextAttachments);
|
||||
dispatchPickerSelection({ type: "target-changed" });
|
||||
},
|
||||
[chatDraft],
|
||||
[chatDraft, dispatchPickerSelection],
|
||||
);
|
||||
|
||||
const handleSelectProjectOption = useCallback(
|
||||
@@ -1257,6 +1290,8 @@ export function NewWorkspaceScreen({
|
||||
project: selectedProject,
|
||||
sourceDirectory: selectedSourceDirectory,
|
||||
checkoutRequest,
|
||||
branchName: setup.getSnapshot().branch,
|
||||
metadata: setup.getSnapshot().metadata,
|
||||
withInitialAgent: input.withInitialAgent,
|
||||
prompt: input.prompt,
|
||||
attachments: input.attachments,
|
||||
@@ -1279,6 +1314,7 @@ export function NewWorkspaceScreen({
|
||||
selectedProject,
|
||||
selectedServerId,
|
||||
selectedSourceDirectory,
|
||||
setup,
|
||||
supportsWorkspaceMultiplicity,
|
||||
t,
|
||||
withConnectedClient,
|
||||
@@ -1459,6 +1495,9 @@ export function NewWorkspaceScreen({
|
||||
const formStack = useNewWorkspaceForm({
|
||||
isCompact,
|
||||
isPending,
|
||||
pluginItems: (
|
||||
<PluginNewWorkspaceItems serverId={selectedServerId} screen={pluginScreen} setup={setup} />
|
||||
),
|
||||
project: {
|
||||
anchorRef: projectPickerAnchorRef,
|
||||
open: openProjectPicker,
|
||||
@@ -1600,6 +1639,45 @@ export function NewWorkspaceScreen({
|
||||
}
|
||||
|
||||
/** Terminal and chat launches edit in separate sessions; the screen follows the mounted one. */
|
||||
/** Reports the screen's current facts to the setup model, which plugin commands read when they run. */
|
||||
function usePluginSetup(input: {
|
||||
setup: NewWorkspaceSetup;
|
||||
serverId: string | null;
|
||||
project: Parameters<typeof getHostProjectId>[0] | null;
|
||||
baseItem: PickerItem | null;
|
||||
isolation: NewWorkspaceItemsScreen["isolation"];
|
||||
canCreateWorktree: boolean;
|
||||
locked: boolean;
|
||||
chooseIsolation: SetupFacts["chooseIsolation"];
|
||||
chooseBase: SetupFacts["chooseBase"];
|
||||
}): NewWorkspaceItemsScreen {
|
||||
const { setup, serverId, project, baseItem, isolation, locked } = input;
|
||||
const { canCreateWorktree, chooseIsolation, chooseBase } = input;
|
||||
const supportsMetadata = useHostFeature(serverId, "entityMetadata");
|
||||
const projectId = project && serverId ? getHostProjectId(project, serverId) : null;
|
||||
const projectName = project?.projectName ?? null;
|
||||
const screen = useMemo<NewWorkspaceItemsScreen>(
|
||||
() => ({
|
||||
project: projectId && projectName ? { id: projectId, name: projectName } : null,
|
||||
isolation,
|
||||
baseItem,
|
||||
locked,
|
||||
}),
|
||||
[baseItem, isolation, locked, projectId, projectName],
|
||||
);
|
||||
useEffect(() => {
|
||||
setup.report({
|
||||
locked: screen.locked,
|
||||
project: screen.project,
|
||||
canCreateWorktree,
|
||||
supportsMetadata,
|
||||
chooseIsolation,
|
||||
chooseBase,
|
||||
});
|
||||
}, [canCreateWorktree, chooseBase, chooseIsolation, screen, setup, supportsMetadata]);
|
||||
return screen;
|
||||
}
|
||||
|
||||
function useNewWorkspaceComposerEditing() {
|
||||
const terminal = useComposerEditingSession("terminal");
|
||||
const chat = useComposerEditingSession("chat");
|
||||
|
||||
@@ -33,6 +33,8 @@ interface PickerControl {
|
||||
export interface NewWorkspaceFormProps {
|
||||
isCompact: boolean;
|
||||
isPending: boolean;
|
||||
/** Plugin fields, drawn after the base ref. */
|
||||
pluginItems: ReactNode;
|
||||
project: PickerControl & {
|
||||
options: ComboboxOption[];
|
||||
projectByOptionId: Map<string, HostProjectListItem>;
|
||||
@@ -165,7 +167,7 @@ function useRefRenderOption(itemById: Map<string, PickerItem>, isPending: boolea
|
||||
*/
|
||||
export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement {
|
||||
const { t } = useTranslation();
|
||||
const { isCompact, isPending, project, host, isolation, base, launch } = props;
|
||||
const { isCompact, isPending, pluginItems, project, host, isolation, base, launch } = props;
|
||||
const variant: FieldTriggerVariant = isCompact ? "field" : "badge";
|
||||
const projectPicker = useProjectPicker(project, isPending);
|
||||
const isolationPicker = useIsolationPicker(isolation, isPending);
|
||||
@@ -337,6 +339,7 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement
|
||||
{hostField}
|
||||
{isolationField}
|
||||
{baseField}
|
||||
{pluginItems}
|
||||
{launchField}
|
||||
{/* Isolation and Base come and go with the project; their rows stay reserved so the
|
||||
stack keeps one height and nothing above the composer jumps. */}
|
||||
@@ -353,6 +356,7 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement
|
||||
<View style={styles.desktopControl}>{hostField}</View>
|
||||
{isolationField ? <View style={styles.desktopControl}>{isolationField}</View> : null}
|
||||
{baseField ? <View style={styles.desktopControl}>{baseField}</View> : null}
|
||||
{pluginItems}
|
||||
<View style={styles.launchSpacer} pointerEvents="none" />
|
||||
{launchField}
|
||||
{pickers}
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { PickerItem } from "../new-workspace-picker-item";
|
||||
import { createNewWorkspaceSetup, type SetupFacts } from "./setup-model";
|
||||
|
||||
function readyFacts(overrides: Partial<SetupFacts> = {}): SetupFacts {
|
||||
return {
|
||||
locked: false,
|
||||
project: { id: "p1", name: "repo" },
|
||||
canCreateWorktree: true,
|
||||
supportsMetadata: true,
|
||||
chooseIsolation: () => {},
|
||||
chooseBase: () => {},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("New workspace setup commands", () => {
|
||||
it("applies commands that run back to back without waiting for a render", async () => {
|
||||
const setup = createNewWorkspaceSetup();
|
||||
setup.report(readyFacts());
|
||||
|
||||
void setup.commands.setBranch("pas-101");
|
||||
void setup.commands.setMetadata({ issue: "PAS-101", keep: true });
|
||||
await setup.commands.setMetadata({ keep: null });
|
||||
|
||||
expect(setup.getSnapshot().branch).toBe("pas-101");
|
||||
expect(setup.getSnapshot().metadata).toEqual({ issue: "PAS-101" });
|
||||
});
|
||||
|
||||
it("passes a base branch and an isolation choice to the picker's own handlers", async () => {
|
||||
const setup = createNewWorkspaceSetup();
|
||||
const chosen: PickerItem[] = [];
|
||||
const isolations: string[] = [];
|
||||
setup.report(
|
||||
readyFacts({
|
||||
chooseBase: (item) => chosen.push(item),
|
||||
chooseIsolation: (isolation) => isolations.push(isolation),
|
||||
}),
|
||||
);
|
||||
|
||||
await setup.commands.setBaseRef({ type: "branch", name: " release " });
|
||||
await setup.commands.setIsolation("worktree");
|
||||
|
||||
expect(chosen).toMatchObject([{ kind: "branch", name: "release", refName: "release" }]);
|
||||
expect(isolations).toEqual(["worktree"]);
|
||||
});
|
||||
|
||||
it("rejects every command while the screen is locked, as the pickers do", async () => {
|
||||
const setup = createNewWorkspaceSetup();
|
||||
setup.report(readyFacts({ locked: true }));
|
||||
|
||||
const results = await Promise.allSettled([
|
||||
setup.commands.setBranch("x"),
|
||||
setup.commands.setMetadata({ a: 1 }),
|
||||
setup.commands.setIsolation("local"),
|
||||
setup.commands.setBaseRef({ type: "branch", name: "main" }),
|
||||
]);
|
||||
|
||||
expect(results.map((result) => result.status)).toEqual(Array(4).fill("rejected"));
|
||||
expect(setup.getSnapshot().branch).toBeNull();
|
||||
expect(setup.getSnapshot().metadata).toEqual({});
|
||||
});
|
||||
|
||||
it("reads the facts when a command runs, so a project change after render is seen", async () => {
|
||||
const setup = createNewWorkspaceSetup();
|
||||
setup.report(readyFacts());
|
||||
const pending = setup.commands.setBaseRef({ type: "branch", name: "main" });
|
||||
setup.report(readyFacts({ project: null }));
|
||||
await pending;
|
||||
await expect(setup.commands.setBaseRef({ type: "branch", name: "main" })).rejects.toThrow(
|
||||
"Choose a project first.",
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects what the project or host cannot do", async () => {
|
||||
const setup = createNewWorkspaceSetup();
|
||||
setup.report(readyFacts({ canCreateWorktree: false, supportsMetadata: false }));
|
||||
|
||||
await expect(setup.commands.setIsolation("worktree")).rejects.toThrow(
|
||||
"cannot create worktrees",
|
||||
);
|
||||
await expect(setup.commands.setMetadata({ a: 1 })).rejects.toThrow("Update the host");
|
||||
await expect(setup.commands.setBranch(" ")).rejects.toThrow("needs a name");
|
||||
await setup.commands.setBranch(null);
|
||||
expect(setup.getSnapshot().branch).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,128 @@
|
||||
import { useSyncExternalStore } from "react";
|
||||
import type { JsonValue } from "@getpaseo/protocol/agent-types";
|
||||
import { applyMetadataPatch } from "@/composer/draft/metadata";
|
||||
import type { PickerItem } from "../new-workspace-picker-item";
|
||||
import {
|
||||
initialPickerSelectionState,
|
||||
reducePickerSelection,
|
||||
type PickerSelectionEvent,
|
||||
type PickerSelectionState,
|
||||
} from "../new-workspace-picker-state";
|
||||
|
||||
type Isolation = "local" | "worktree";
|
||||
|
||||
/** What the user has chosen on the New workspace screen, apart from project and host. */
|
||||
interface SetupState {
|
||||
pickerSelection: PickerSelectionState;
|
||||
manualIsolation: Isolation | null;
|
||||
/** The name for a new worktree branch; null lets Paseo pick one. */
|
||||
branch: string | null;
|
||||
/** The created workspace's metadata. */
|
||||
metadata: Readonly<Record<string, JsonValue>>;
|
||||
}
|
||||
|
||||
/**
|
||||
* What the screen derives from its hooks and reports on every render, so a command reads it at the
|
||||
* moment it runs rather than from the render that built the command.
|
||||
*/
|
||||
export interface SetupFacts {
|
||||
locked: boolean;
|
||||
project: { id: string; name: string } | null;
|
||||
canCreateWorktree: boolean;
|
||||
supportsMetadata: boolean;
|
||||
/** The picker's own handlers, so a command has the effects a pick has. */
|
||||
chooseIsolation(isolation: Isolation): void;
|
||||
chooseBase(item: PickerItem): void;
|
||||
}
|
||||
|
||||
export interface SetupCommands {
|
||||
setIsolation(isolation: Isolation): Promise<void>;
|
||||
setBaseRef(ref: { type: "branch"; name: string }): Promise<void>;
|
||||
setBranch(name: string | null): Promise<void>;
|
||||
setMetadata(patch: Record<string, JsonValue>): Promise<void>;
|
||||
}
|
||||
|
||||
export interface NewWorkspaceSetup {
|
||||
subscribe(listener: () => void): () => void;
|
||||
getSnapshot(): SetupState;
|
||||
dispatchPicker(event: PickerSelectionEvent): void;
|
||||
setManualIsolation(isolation: Isolation): void;
|
||||
report(facts: SetupFacts): void;
|
||||
commands: SetupCommands;
|
||||
}
|
||||
|
||||
const LOCKED_MESSAGE = "The New workspace screen is locked while the workspace is being created.";
|
||||
|
||||
/**
|
||||
* The New workspace screen's choices as one plain model. The pickers and the plugin commands
|
||||
* write to it, so a command sees what an earlier command or pick left, and applies the same rules
|
||||
* as the picker it stands in for.
|
||||
*/
|
||||
export function createNewWorkspaceSetup(): NewWorkspaceSetup {
|
||||
let state: SetupState = {
|
||||
pickerSelection: initialPickerSelectionState,
|
||||
manualIsolation: null,
|
||||
branch: null,
|
||||
metadata: {},
|
||||
};
|
||||
let facts: SetupFacts | null = null;
|
||||
const listeners = new Set<() => void>();
|
||||
const update = (patch: Partial<SetupState>) => {
|
||||
state = { ...state, ...patch };
|
||||
for (const listener of listeners) listener();
|
||||
};
|
||||
const unlocked = (): SetupFacts => {
|
||||
if (!facts) throw new Error("The New workspace screen is not ready.");
|
||||
if (facts.locked) throw new Error(LOCKED_MESSAGE);
|
||||
return facts;
|
||||
};
|
||||
return {
|
||||
subscribe(listener) {
|
||||
listeners.add(listener);
|
||||
return () => listeners.delete(listener);
|
||||
},
|
||||
getSnapshot: () => state,
|
||||
dispatchPicker: (event) =>
|
||||
update({ pickerSelection: reducePickerSelection(state.pickerSelection, event) }),
|
||||
setManualIsolation: (manualIsolation) => update({ manualIsolation }),
|
||||
report: (next) => {
|
||||
facts = next;
|
||||
},
|
||||
commands: {
|
||||
async setIsolation(isolation) {
|
||||
const current = unlocked();
|
||||
if (isolation === "worktree" && !current.canCreateWorktree) {
|
||||
throw new Error("This project cannot create worktrees.");
|
||||
}
|
||||
current.chooseIsolation(isolation);
|
||||
},
|
||||
async setBaseRef({ name }) {
|
||||
const current = unlocked();
|
||||
const refName = name.trim();
|
||||
if (!current.project) throw new Error("Choose a project first.");
|
||||
if (!refName) throw new Error("A base branch needs a name.");
|
||||
current.chooseBase({
|
||||
kind: "branch",
|
||||
name: refName,
|
||||
refName,
|
||||
accessibilityLabel: `${refName}, branch`,
|
||||
});
|
||||
},
|
||||
async setBranch(name) {
|
||||
unlocked();
|
||||
const branch = name === null ? null : name.trim();
|
||||
if (branch === "") throw new Error("A branch needs a name.");
|
||||
update({ branch });
|
||||
},
|
||||
async setMetadata(patch) {
|
||||
const current = unlocked();
|
||||
if (!current.supportsMetadata) throw new Error("Update the host to use metadata.");
|
||||
update({ metadata: applyMetadataPatch(state.metadata, patch) });
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function useNewWorkspaceSetupState(setup: NewWorkspaceSetup): SetupState {
|
||||
return useSyncExternalStore(setup.subscribe, setup.getSnapshot, setup.getSnapshot);
|
||||
}
|
||||
@@ -250,6 +250,51 @@ describe("plugin composer SDK boundary", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("plugin New workspace SDK boundary", () => {
|
||||
it("lets a New workspace item read the setup and change it through typed commands and a Combobox", () => {
|
||||
expect(
|
||||
typeErrors(`
|
||||
import { useNewWorkspace, type PluginClientContext } from "@getpaseo/plugin/client";
|
||||
import { Combobox } from "@getpaseo/plugin/client/ui";
|
||||
interface Issue { id: string; label: string; branch: string }
|
||||
function Item() {
|
||||
const newWorkspace = useNewWorkspace();
|
||||
const isolation: "local" | "worktree" = newWorkspace.isolation;
|
||||
const branch: string | null = newWorkspace.branch;
|
||||
const project: string | undefined = newWorkspace.project?.name;
|
||||
const host: string = newWorkspace.host.label;
|
||||
const base = newWorkspace.baseRef;
|
||||
if (base?.type === "branch") { const name: string = base.name; }
|
||||
// @ts-expect-error project is read-only
|
||||
newWorkspace.project = null;
|
||||
// @ts-expect-error host is read-only
|
||||
newWorkspace.setHost("other");
|
||||
// @ts-expect-error metadata reads are not writable
|
||||
newWorkspace.metadata.key = "x";
|
||||
newWorkspace.setIsolation("worktree").then(() => newWorkspace.setBaseRef({ type: "branch", name: "main" }));
|
||||
newWorkspace.setBranch(null);
|
||||
newWorkspace.setMetadata({ issue: "1", stale: null });
|
||||
// @ts-expect-error commands take JSON values
|
||||
newWorkspace.setMetadata({ fn: () => {} });
|
||||
return (
|
||||
<Combobox<Issue>
|
||||
title="Issue"
|
||||
icon="CircleDot"
|
||||
value={{ id: "1", label: "One" }}
|
||||
search={async ({ query }: { query: string }) => [{ id: query, label: query, branch: "b" }]}
|
||||
onSelect={({ item }) => newWorkspace.setBranch(item.branch)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
export default function contribute(client: PluginClientContext) {
|
||||
client.addNewWorkspaceItem({ id: "item", Component: Item });
|
||||
return () => {};
|
||||
}
|
||||
`),
|
||||
).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("plugin agent tools SDK boundary", () => {
|
||||
it("lets a session hook attach typed tools without exposing their transport", () => {
|
||||
expect(
|
||||
|
||||
@@ -5,6 +5,7 @@ import type { AgentTimelineItem, JsonValue } from "@getpaseo/protocol/agent-type
|
||||
import type { ZodType, input as ZodInput, output as ZodOutput } from "zod";
|
||||
import type { PluginFile } from "./file.js";
|
||||
import type { PluginComposerItemContribution } from "./composer.js";
|
||||
import type { PluginNewWorkspaceItemContribution } from "./new-workspace.js";
|
||||
import type {
|
||||
PluginRpcContract,
|
||||
PluginSubscribeOptions,
|
||||
@@ -202,6 +203,7 @@ export interface PluginClientContext extends PluginCommandCapabilities, PluginCl
|
||||
): PluginButtonRegistration<PluginText>;
|
||||
addAttachmentSource(contribution: PluginAttachmentSourceContribution<PluginText>): PluginCleanup;
|
||||
addComposerItem(contribution: PluginComposerItemContribution): PluginCleanup;
|
||||
addNewWorkspaceItem(contribution: PluginNewWorkspaceItemContribution): PluginCleanup;
|
||||
addTheme(contribution: PluginThemeContribution<PluginText>): PluginCleanup;
|
||||
addFilePanel(contribution: PluginFilePanelContribution<PluginText>): PluginCleanup;
|
||||
addTimelineTransformer<ItemType extends AgentTimelineItem["type"]>(
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { PluginText } from "../text.js";
|
||||
import { PluginAttachmentSearchPayloadSchema } from "../attachments.js";
|
||||
export { PluginClientStateProvider, type PluginClientStateSource } from "./client-state.js";
|
||||
export { PluginComposerProvider } from "./composer.js";
|
||||
export { PluginNewWorkspaceProvider } from "./new-workspace.js";
|
||||
export {
|
||||
usePluginRuntimeContextBridge,
|
||||
type PluginRuntimeContextBridge,
|
||||
|
||||
@@ -78,6 +78,12 @@ export type {
|
||||
PluginComposerItemContribution,
|
||||
PluginComposerItemProps,
|
||||
} from "./composer.js";
|
||||
export { useNewWorkspace } from "./new-workspace.js";
|
||||
export type {
|
||||
PluginNewWorkspace,
|
||||
PluginNewWorkspaceItemContribution,
|
||||
PluginNewWorkspaceItemProps,
|
||||
} from "./new-workspace.js";
|
||||
export { useRpc, useSubscription, type PluginSubscriptionState } from "./rpc-context.js";
|
||||
export type {
|
||||
PluginSubscribeOptions,
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import { createContext, useContext, type ComponentType, type ReactNode } from "react";
|
||||
import type { JsonValue } from "@getpaseo/protocol/agent-types";
|
||||
import type { PluginHostProps } from "./contracts.js";
|
||||
|
||||
/**
|
||||
* The New workspace setup the item sits in. `host` and `project` are the user's choices and are
|
||||
* read-only. The commands change what the created workspace is built from, under the same rules as
|
||||
* the screen's own pickers.
|
||||
*/
|
||||
export interface PluginNewWorkspace {
|
||||
readonly host: { readonly id: string; readonly label: string };
|
||||
readonly project: { readonly id: string; readonly name: string } | null;
|
||||
/** What the screen will create. A project that cannot make worktrees reads `"local"`. */
|
||||
readonly isolation: "local" | "worktree";
|
||||
/** What a new worktree starts from; `null` until the project's default is known. */
|
||||
readonly baseRef:
|
||||
| { readonly type: "branch"; readonly name: string }
|
||||
| { readonly type: "change-request"; readonly number: number }
|
||||
| null;
|
||||
/**
|
||||
* The name of the branch a new worktree is created on; `null` lets Paseo pick one. It is kept
|
||||
* while isolation is local or the base is a change request, and applies only to a worktree
|
||||
* created from a branch.
|
||||
*/
|
||||
readonly branch: string | null;
|
||||
/** The workspace's metadata, not the first agent's. */
|
||||
readonly metadata: Readonly<Record<string, JsonValue>>;
|
||||
/** Rejects `"worktree"` for a project that cannot make worktrees. */
|
||||
setIsolation(isolation: "local" | "worktree"): Promise<void>;
|
||||
/** Starts the workspace from a branch. Rejects while no project is chosen. */
|
||||
setBaseRef(ref: { type: "branch"; name: string }): Promise<void>;
|
||||
setBranch(name: string | null): Promise<void>;
|
||||
/** Top-level keys replace; `null` removes the key. Rejects on a host without metadata support. */
|
||||
setMetadata(patch: Record<string, JsonValue>): Promise<void>;
|
||||
}
|
||||
|
||||
export interface PluginNewWorkspaceItemProps extends PluginHostProps {}
|
||||
|
||||
export interface PluginNewWorkspaceItemContribution {
|
||||
id: string;
|
||||
Component: ComponentType<PluginNewWorkspaceItemProps>;
|
||||
}
|
||||
|
||||
const PluginNewWorkspaceContext = createContext<PluginNewWorkspace | null>(null);
|
||||
|
||||
export function PluginNewWorkspaceProvider({
|
||||
newWorkspace,
|
||||
children,
|
||||
}: {
|
||||
newWorkspace: PluginNewWorkspace;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<PluginNewWorkspaceContext.Provider value={newWorkspace}>
|
||||
{children}
|
||||
</PluginNewWorkspaceContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
/** The New workspace setup this item sits in. Call it from a component registered with `addNewWorkspaceItem`. */
|
||||
export function useNewWorkspace(): PluginNewWorkspace {
|
||||
const newWorkspace = useContext(PluginNewWorkspaceContext);
|
||||
if (!newWorkspace) throw new Error("useNewWorkspace must run inside a New workspace item");
|
||||
return newWorkspace;
|
||||
}
|
||||
@@ -210,10 +210,35 @@ export interface ActionPressEvent {}
|
||||
export interface ActionProps extends ComposerControlProps {
|
||||
onPress(event: ActionPressEvent): void | Promise<void>;
|
||||
}
|
||||
/** One result of a `Combobox` search. Extra fields ride along to `onSelect`. */
|
||||
export interface ComboboxItem {
|
||||
id: string;
|
||||
label: string;
|
||||
description?: string;
|
||||
}
|
||||
export interface ComboboxSearchEvent {
|
||||
/** Empty when the list opens. */
|
||||
query: string;
|
||||
}
|
||||
export interface ComboboxProps<
|
||||
Item extends ComboboxItem = ComboboxItem,
|
||||
> extends ComposerControlProps {
|
||||
/** What the control shows. It need not be among the search results. */
|
||||
value: ComboboxItem | null;
|
||||
/**
|
||||
* Called when the list opens and again, debounced, as the user types. Paseo shows the loading
|
||||
* and error states, keeps the previous results while a search runs, and ignores a search that a
|
||||
* newer one replaced.
|
||||
*/
|
||||
search(event: ComboboxSearchEvent): Promise<readonly Item[]>;
|
||||
onSelect(event: { item: Item }): void | Promise<void>;
|
||||
}
|
||||
/**
|
||||
* Composer controls. Render them from a composer item's `Component`. Paseo draws them inline when
|
||||
* the composer has room and as rows in its overflow sheet when it does not.
|
||||
* Paseo's controls. Render them from a composer item's or a New workspace item's `Component`.
|
||||
* Paseo draws them where the item sits: inline when the composer has room and as rows in its
|
||||
* overflow sheet when it does not, and as a field in the New workspace setup.
|
||||
*/
|
||||
export declare const Toggle: ComponentType<ToggleProps>;
|
||||
export declare function Select<Value extends string>(props: SelectProps<Value>): ReactNode;
|
||||
export declare const Action: ComponentType<ActionProps>;
|
||||
export declare function Combobox<Item extends ComboboxItem>(props: ComboboxProps<Item>): ReactNode;
|
||||
|
||||
Reference in New Issue
Block a user