mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-29 03:35:39 +00:00
Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
47573fde57 | ||
|
|
08298dcc10 | ||
|
|
cafb42560c | ||
|
|
6655aa77b3 | ||
|
|
291d54fa71 | ||
|
|
ddb15230b3 | ||
|
|
9dc533fcd2 | ||
|
|
0ee4a57981 | ||
|
|
aa957c9ca9 | ||
|
|
a96a4d61f1 |
@@ -233,6 +233,57 @@ test("opening an agent focuses the composer when a mouse drives the UI", async (
|
||||
}
|
||||
});
|
||||
|
||||
/** The composer frame's border colour once its border-color transition has finished. */
|
||||
async function readSettledFrameBorder(page: Page): Promise<string> {
|
||||
return composerLocator(page).evaluate(async (input) => {
|
||||
let frame = input.parentElement;
|
||||
while (frame && parseFloat(getComputedStyle(frame).borderTopWidth) < 1) {
|
||||
frame = frame.parentElement;
|
||||
}
|
||||
if (!frame) throw new Error("Composer frame has no border");
|
||||
while (frame.getAnimations().length > 0) {
|
||||
await new Promise((resolve) => requestAnimationFrame(resolve));
|
||||
}
|
||||
return getComputedStyle(frame).borderTopColor;
|
||||
});
|
||||
}
|
||||
|
||||
test("the composer frame shows hover and focus", async ({ page }) => {
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: "composer-frame-focus-",
|
||||
title: "Composer frame focus",
|
||||
});
|
||||
|
||||
try {
|
||||
await openAgentRoute(page, agent);
|
||||
const composer = composerLocator(page);
|
||||
await expectComposerVisible(page);
|
||||
await page.mouse.move(0, 0);
|
||||
await blurComposerInput(page);
|
||||
const rest = await readSettledFrameBorder(page);
|
||||
|
||||
await composer.hover();
|
||||
const hover = await readSettledFrameBorder(page);
|
||||
expect(hover).not.toBe(rest);
|
||||
|
||||
await composer.click();
|
||||
await page.mouse.move(0, 0);
|
||||
await expectComposerFocused(page);
|
||||
const focus = await readSettledFrameBorder(page);
|
||||
expect(focus).not.toBe(rest);
|
||||
expect(focus).not.toBe(hover);
|
||||
|
||||
await composer.hover();
|
||||
expect(await readSettledFrameBorder(page)).toBe(focus);
|
||||
|
||||
await page.mouse.move(0, 0);
|
||||
await blurComposerInput(page);
|
||||
expect(await readSettledFrameBorder(page)).toBe(rest);
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
async function waitForAnimationFrames(page: Page, count: number): Promise<void> {
|
||||
await page.evaluate(async (frames) => {
|
||||
for (let frame = 0; frame < frames; frame += 1) {
|
||||
|
||||
@@ -155,6 +155,39 @@ describe("resolveAgentModelSelection", () => {
|
||||
expect(selection.selectedThinkingId).toBe("high");
|
||||
});
|
||||
|
||||
it("lists and selects the agent's thinking level when the model does not list it", () => {
|
||||
const selection = resolveAgentModelSelection({
|
||||
models: [
|
||||
{
|
||||
id: "opus",
|
||||
provider: "claude",
|
||||
label: "opus",
|
||||
thinkingOptions: [
|
||||
{ id: "low", label: "Low" },
|
||||
{ id: "medium", label: "Medium" },
|
||||
{ id: "high", label: "High", isDefault: true },
|
||||
{ id: "max", label: "Max" },
|
||||
],
|
||||
defaultThinkingOptionId: "high",
|
||||
},
|
||||
],
|
||||
runtimeModelId: "opus",
|
||||
configuredModelId: "opus",
|
||||
runtimeThinkingOptionId: null,
|
||||
explicitThinkingOptionId: "xhigh",
|
||||
});
|
||||
|
||||
expect(selection.selectedThinkingId).toBe("xhigh");
|
||||
expect(selection.displayThinking).toBe("Extra high");
|
||||
expect(selection.thinkingOptions?.map((option) => option.id)).toEqual([
|
||||
"low",
|
||||
"medium",
|
||||
"high",
|
||||
"max",
|
||||
"xhigh",
|
||||
]);
|
||||
});
|
||||
|
||||
it("formats raw thinking labels in the selected model display", () => {
|
||||
const selection = resolveAgentModelSelection({
|
||||
models: [
|
||||
|
||||
@@ -130,6 +130,21 @@ function resolveEffectiveThinking(
|
||||
return selectedThinking ?? thinkingOptions?.[0] ?? null;
|
||||
}
|
||||
|
||||
// The agent runs on its level even when the model's list leaves it out. The level joins the
|
||||
// list, so the controls show and check it and none of them falls back to the first option.
|
||||
function includeResolvedThinkingOption(
|
||||
thinkingOptions: ThinkingOption[] | null,
|
||||
resolvedThinkingId: string | null,
|
||||
): ThinkingOption[] | null {
|
||||
if (!thinkingOptions || thinkingOptions.length === 0 || !resolvedThinkingId) {
|
||||
return thinkingOptions;
|
||||
}
|
||||
if (thinkingOptions.some((option) => option.id === resolvedThinkingId)) {
|
||||
return thinkingOptions;
|
||||
}
|
||||
return [...thinkingOptions, { id: resolvedThinkingId, label: resolvedThinkingId }];
|
||||
}
|
||||
|
||||
function resolveModelDisplay(
|
||||
selectedModel: AgentModelDefinition | null,
|
||||
preferredModelId: string | null,
|
||||
@@ -192,12 +207,15 @@ export function resolveAgentModelSelection(input: {
|
||||
i18n.t("agentControls.model.unknown"),
|
||||
);
|
||||
|
||||
const thinkingOptions = selectedModel?.thinkingOptions ?? null;
|
||||
const resolvedThinkingId = resolveThinkingId(
|
||||
runtimeThinkingOptionId,
|
||||
explicitThinkingOptionId,
|
||||
selectedModel,
|
||||
);
|
||||
const thinkingOptions = includeResolvedThinkingOption(
|
||||
selectedModel?.thinkingOptions ?? null,
|
||||
resolvedThinkingId,
|
||||
);
|
||||
const effectiveThinking = resolveEffectiveThinking(thinkingOptions, resolvedThinkingId);
|
||||
const selectedThinkingId = effectiveThinking?.id ?? resolvedThinkingId;
|
||||
const displayThinking = resolveThinkingDisplay(
|
||||
|
||||
@@ -110,6 +110,7 @@ import {
|
||||
applyDictationTranscript,
|
||||
computeCanStartDictation,
|
||||
resolveAlternateSendAction,
|
||||
resolveComposerFramePhase,
|
||||
resolveComposerSurfacePresentation,
|
||||
resolveComposerSurfaceText,
|
||||
resolveMessageInputEnterAction,
|
||||
@@ -1368,6 +1369,8 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
|
||||
const dictationToggleKeys = useShortcutKeys("dictation-toggle");
|
||||
const focusInputKeys = useShortcutKeys("focus-message-input");
|
||||
const [isInputFocused, setIsInputFocused] = useState(false);
|
||||
// Only the frame's pointer events set it, so hover stays a web thing; see docs/hover.md.
|
||||
const [isInputHovered, setIsInputHovered] = useState(false);
|
||||
useKeyboardFocusSurface("message-input", isInputFocused && isPaneFocused);
|
||||
// Web text is DOM-owned between deferred draft publications. The action button only needs
|
||||
// this boundary, so publish empty/non-empty transitions without rerendering for every key.
|
||||
@@ -2038,15 +2041,32 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
|
||||
void handleStopRealtimeVoice();
|
||||
}, [handleStopRealtimeVoice]);
|
||||
|
||||
const handleInputWrapperPointerEnter = useCallback(() => setIsInputHovered(true), []);
|
||||
const handleInputWrapperPointerLeave = useCallback(() => setIsInputHovered(false), []);
|
||||
const framePhase = resolveComposerFramePhase({
|
||||
hovered: isInputHovered,
|
||||
focused: isInputFocused,
|
||||
readOnly,
|
||||
disabled,
|
||||
});
|
||||
const inputWrapperCombinedStyle = useMemo(
|
||||
() => [
|
||||
styles.inputWrapper,
|
||||
Platform.OS !== "ios" && isCompact && !isFullscreen && styles.inputWrapperCompact,
|
||||
readOnly && styles.inputWrapperReadOnly,
|
||||
framePhase === "hover" && styles.inputWrapperHovered,
|
||||
framePhase === "active" && styles.inputWrapperFocused,
|
||||
inputWrapperStyle,
|
||||
{ opacity: surfacePresentation.input.opacity },
|
||||
],
|
||||
[inputWrapperStyle, isCompact, isFullscreen, readOnly, surfacePresentation.input.opacity],
|
||||
[
|
||||
framePhase,
|
||||
inputWrapperStyle,
|
||||
isCompact,
|
||||
isFullscreen,
|
||||
readOnly,
|
||||
surfacePresentation.input.opacity,
|
||||
],
|
||||
);
|
||||
// `withUnistyles` maps this component's `style` into a `.hash > *` child
|
||||
// rule, which ties on specificity with react-native-web's own
|
||||
@@ -2394,6 +2414,8 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
|
||||
onExit={exitFullscreen}
|
||||
inputWrapperRef={inputWrapperRef}
|
||||
inputWrapperStyle={inputWrapperCombinedStyle}
|
||||
onInputWrapperPointerEnter={handleInputWrapperPointerEnter}
|
||||
onInputWrapperPointerLeave={handleInputWrapperPointerLeave}
|
||||
inputPointerEvents={surfacePresentation.input.pointerEvents}
|
||||
attachmentSlot={attachmentSlot}
|
||||
showFullscreenButton={shouldShowFullscreenControl(
|
||||
@@ -2448,6 +2470,15 @@ const styles = StyleSheet.create((theme: Theme) => ({
|
||||
inputWrapperReadOnly: {
|
||||
borderStyle: "dotted",
|
||||
},
|
||||
// The rest border is already the `borderAccent` that `controlHover` gives other inputs, so
|
||||
// hover steps up one surface; focus takes the accent, like their focus ring. Colour only:
|
||||
// the border width stays put, so the frame never shifts under the pointer.
|
||||
inputWrapperHovered: {
|
||||
borderColor: theme.colors.surface4,
|
||||
},
|
||||
inputWrapperFocused: {
|
||||
borderColor: theme.colors.accent,
|
||||
},
|
||||
// The band the fullscreen glyph sits in is the input's own padding, so a tap
|
||||
// anywhere in it (under the glyph, or where the glyph would be) is a tap on the
|
||||
// editor: it focuses, shows the keyboard, and places the caret. Reserved whether
|
||||
|
||||
@@ -37,6 +37,8 @@ export function ComposerInputPresentation({
|
||||
onExit,
|
||||
inputWrapperRef,
|
||||
inputWrapperStyle,
|
||||
onInputWrapperPointerEnter,
|
||||
onInputWrapperPointerLeave,
|
||||
inputPointerEvents,
|
||||
attachmentSlot,
|
||||
showFullscreenButton,
|
||||
@@ -53,6 +55,9 @@ export function ComposerInputPresentation({
|
||||
onExit: () => void;
|
||||
inputWrapperRef: Ref<View>;
|
||||
inputWrapperStyle: ViewProps["style"];
|
||||
/** Hover tracking for the frame's border; the frame is a plain View, per docs/hover.md. */
|
||||
onInputWrapperPointerEnter: () => void;
|
||||
onInputWrapperPointerLeave: () => void;
|
||||
inputPointerEvents: ViewProps["pointerEvents"];
|
||||
attachmentSlot: ReactNode;
|
||||
showFullscreenButton: boolean;
|
||||
@@ -107,6 +112,8 @@ export function ComposerInputPresentation({
|
||||
ref={inputWrapperRef}
|
||||
style={fullscreen ? styles.fullscreenInputWrapper : inputWrapperStyle}
|
||||
pointerEvents={inputPointerEvents}
|
||||
onPointerEnter={onInputWrapperPointerEnter}
|
||||
onPointerLeave={onInputWrapperPointerLeave}
|
||||
>
|
||||
{fullscreen ? null : attachmentSlot}
|
||||
<View style={fullscreen ? styles.fullscreenTextSurface : styles.inlineTextSurface}>
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
computeCanStartDictation,
|
||||
type MessageInputEnterContext,
|
||||
resolveActiveSendBehavior,
|
||||
resolveComposerFramePhase,
|
||||
resolveComposerSurfacePresentation,
|
||||
resolveComposerSurfaceText,
|
||||
resolveGlyphRailOffset,
|
||||
@@ -614,3 +615,23 @@ describe("fullscreen glyph rail", () => {
|
||||
expect(offset + inkInset).toBeCloseTo(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("composer frame phase", () => {
|
||||
const rest = { hovered: false, focused: false, readOnly: false, disabled: false };
|
||||
|
||||
it("shows the focus border while the editor has focus, hovered or not", () => {
|
||||
expect(resolveComposerFramePhase({ ...rest, focused: true })).toBe("active");
|
||||
expect(resolveComposerFramePhase({ ...rest, focused: true, hovered: true })).toBe("active");
|
||||
});
|
||||
|
||||
it("shows the hover border only while the pointer is over an unfocused frame", () => {
|
||||
expect(resolveComposerFramePhase({ ...rest, hovered: true })).toBe("hover");
|
||||
expect(resolveComposerFramePhase(rest)).toBe("rest");
|
||||
});
|
||||
|
||||
it("keeps a read-only or disabled frame at rest", () => {
|
||||
const engaged = { ...rest, hovered: true, focused: true };
|
||||
expect(resolveComposerFramePhase({ ...engaged, readOnly: true })).toBe("rest");
|
||||
expect(resolveComposerFramePhase({ ...engaged, disabled: true })).toBe("rest");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,6 +3,10 @@ import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import type { ActiveTurnBehavior } from "@getpaseo/protocol/messages";
|
||||
import type { MessagePayload, TextReplacement } from "@/composer/types";
|
||||
import type { MessageInputKeyboardActionKind } from "@/keyboard/actions";
|
||||
import {
|
||||
getControlInteractionPhase,
|
||||
type ControlInteractionPhase,
|
||||
} from "@/components/ui/control-geometry";
|
||||
|
||||
export type SendBehavior = ActiveTurnBehavior | "queue";
|
||||
|
||||
@@ -246,6 +250,23 @@ export function resolveGlyphRailOffset(input: {
|
||||
return -inkInset;
|
||||
}
|
||||
|
||||
/**
|
||||
* The composer frame follows the phases of the app's other inputs: focus wins over hover, and
|
||||
* a frame you can't type into (read-only, disabled) stays at rest.
|
||||
*/
|
||||
export function resolveComposerFramePhase(input: {
|
||||
hovered: boolean;
|
||||
focused: boolean;
|
||||
readOnly: boolean;
|
||||
disabled: boolean;
|
||||
}): ControlInteractionPhase {
|
||||
return getControlInteractionPhase({
|
||||
hovered: input.hovered,
|
||||
focused: input.focused,
|
||||
disabled: input.readOnly || input.disabled,
|
||||
});
|
||||
}
|
||||
|
||||
export function resolveComposerSurfaceText(
|
||||
liveText: string,
|
||||
replacement: TextReplacement,
|
||||
|
||||
@@ -41,9 +41,12 @@ export function createScheduleCommand(): Command {
|
||||
.option("--expires-in <duration>", "Time to live for the schedule"),
|
||||
).action(withOutput(runCreateCommand));
|
||||
|
||||
addJsonAndDaemonHostOptions(schedule.command("ls").description("List schedules")).action(
|
||||
withOutput(runLsCommand),
|
||||
);
|
||||
addJsonAndDaemonHostOptions(
|
||||
schedule
|
||||
.command("ls")
|
||||
.description("List new-agent schedules")
|
||||
.option("--all", "Include schedules targeting existing agents"),
|
||||
).action(withOutput(runLsCommand));
|
||||
|
||||
addJsonAndDaemonHostOptions(
|
||||
schedule.command("inspect").description("Inspect a schedule").argument("<id>", "Schedule ID"),
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { Command } from "commander";
|
||||
import type { ListResult } from "../../output/index.js";
|
||||
import { isHumanOutput, type ListResult } from "../../output/index.js";
|
||||
import { scheduleSchema } from "./schema.js";
|
||||
import {
|
||||
connectScheduleClient,
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
} from "./shared.js";
|
||||
|
||||
export async function runLsCommand(
|
||||
options: ScheduleCommandOptions,
|
||||
options: ScheduleCommandOptions & { all?: boolean },
|
||||
_command: Command,
|
||||
): Promise<ListResult<ScheduleRow>> {
|
||||
const { client } = await connectScheduleClient(options.daemonTarget);
|
||||
@@ -19,11 +19,18 @@ export async function runLsCommand(
|
||||
if (payload.error) {
|
||||
throw new Error(payload.error);
|
||||
}
|
||||
const visible = options.all
|
||||
? payload.schedules
|
||||
: payload.schedules.filter((schedule) => schedule.target.type === "new-agent");
|
||||
const hiddenCount = payload.schedules.length - visible.length;
|
||||
if (hiddenCount > 0 && isHumanOutput(options)) {
|
||||
console.error(
|
||||
`Schedules targeting existing agents: ${hiddenCount} hidden. Use --all to include them.`,
|
||||
);
|
||||
}
|
||||
return {
|
||||
type: "list",
|
||||
data: payload.schedules
|
||||
.filter((schedule) => schedule.target.type === "new-agent")
|
||||
.map(toScheduleRow),
|
||||
data: visible.map(toScheduleRow),
|
||||
schema: scheduleSchema,
|
||||
};
|
||||
} catch (error) {
|
||||
|
||||
@@ -60,4 +60,9 @@ export {
|
||||
} from "./render-async.js";
|
||||
|
||||
// Command wrapper
|
||||
export { withOutput, createOutputOptions, type CommandOptions } from "./with-output.js";
|
||||
export {
|
||||
withOutput,
|
||||
createOutputOptions,
|
||||
isHumanOutput,
|
||||
type CommandOptions,
|
||||
} from "./with-output.js";
|
||||
|
||||
@@ -63,6 +63,11 @@ function extractOutputOptions(options: CommandOptions): OutputOptions {
|
||||
};
|
||||
}
|
||||
|
||||
export function isHumanOutput(options: CommandOptions): boolean {
|
||||
const { format, quiet } = extractOutputOptions(options);
|
||||
return format === "table" && !quiet;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrap a command handler to automatically render output.
|
||||
*
|
||||
|
||||
@@ -294,6 +294,24 @@ try {
|
||||
const createdJson = JSON.parse(created.stdout);
|
||||
assert.strictEqual(createdJson.target, "agent:0000000");
|
||||
|
||||
const human = await ctx.paseo(["schedule", "ls"]);
|
||||
assert.strictEqual(human.exitCode, 0, human.stderr);
|
||||
assert.match(human.stderr, /1 hidden.*--all/);
|
||||
|
||||
const alias = await ctx.paseo(["--format", "cli", "schedule", "ls"]);
|
||||
assert.strictEqual(alias.exitCode, 0, alias.stderr);
|
||||
assert.match(alias.stderr, /1 hidden.*--all/);
|
||||
|
||||
const all = await ctx.paseo(["schedule", "ls", "--all", "--json"]);
|
||||
assert.strictEqual(all.exitCode, 0, all.stderr);
|
||||
assert(
|
||||
JSON.parse(all.stdout).some(
|
||||
(row: { id: string; target: string }) =>
|
||||
row.id === createdJson.id && row.target === createdJson.target,
|
||||
),
|
||||
all.stdout,
|
||||
);
|
||||
|
||||
const deleted = await ctx.paseo(["schedule", "delete", createdJson.id, "--json"]);
|
||||
assert.strictEqual(deleted.exitCode, 0, deleted.stderr);
|
||||
assert.strictEqual(JSON.parse(deleted.stdout).id, createdJson.id);
|
||||
|
||||
@@ -6,6 +6,7 @@ import type {
|
||||
EditorTargetIcon,
|
||||
EditorTargetRuntime,
|
||||
} from "./target.js";
|
||||
import { antigravityTarget } from "./targets/antigravity.js";
|
||||
import { cursorTarget } from "./targets/cursor.js";
|
||||
import { explorerTarget, fileManagerTarget, finderTarget } from "./targets/file-manager.js";
|
||||
import { intellijIdeaTarget } from "./targets/intellij-idea.js";
|
||||
@@ -243,6 +244,41 @@ describe("editor target registry", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("never mistakes the agy CLI agent or Antigravity.app for the Antigravity IDE", async () => {
|
||||
const runtime = new FakeEditorTargets("darwin");
|
||||
runtime.installCommand("agy");
|
||||
runtime.installMacApplication("Antigravity");
|
||||
|
||||
expect(await antigravityTarget.isInstalled(runtime)).toBe(false);
|
||||
});
|
||||
|
||||
it("launches Antigravity through the IDE's bundled antigravity-ide command", async () => {
|
||||
const runtime = new FakeEditorTargets("darwin");
|
||||
const bundled = "/Applications/Antigravity IDE.app/Contents/Resources/app/bin/antigravity-ide";
|
||||
runtime.installCommand("agy");
|
||||
runtime.installCommand(bundled, bundled);
|
||||
|
||||
await antigravityTarget.launch(
|
||||
{ workspacePath: "/repo", filePath: "/repo/a.ts", line: 3 },
|
||||
runtime,
|
||||
);
|
||||
|
||||
expect(runtime.launches).toEqual([
|
||||
{ command: bundled, args: ["/repo", "--goto", "/repo/a.ts:3"] },
|
||||
]);
|
||||
});
|
||||
|
||||
it("opens the Antigravity IDE application when no launcher command resolves", async () => {
|
||||
const runtime = new FakeEditorTargets("darwin");
|
||||
runtime.installMacApplication("Antigravity IDE");
|
||||
|
||||
await antigravityTarget.launch({ workspacePath: "/repo" }, runtime);
|
||||
|
||||
expect(runtime.openedMacApplications).toEqual([
|
||||
{ applicationName: "Antigravity IDE", paths: ["/repo"] },
|
||||
]);
|
||||
});
|
||||
|
||||
it("detects and launches the macOS application when the command is absent", async () => {
|
||||
const runtime = new FakeEditorTargets("darwin");
|
||||
runtime.installMacApplication("Cursor");
|
||||
|
||||
@@ -1,6 +1,23 @@
|
||||
import type { EditorTarget, EditorTargetLaunchInput } from "../target.js";
|
||||
import type { EditorTarget, EditorTargetLaunchInput, EditorTargetRuntime } from "../target.js";
|
||||
|
||||
const COMMANDS = ["agy", "antigravity"] as const;
|
||||
// On macOS the IDE ships `antigravity-ide`. `agy` is the standalone Antigravity CLI agent and
|
||||
// `Antigravity.app` (com.google.antigravity) is a separate app: neither opens the editor.
|
||||
// IDE builds from before the rename keep their launcher at Antigravity.app/.../bin/antigravity.
|
||||
const APP_NAME = "Antigravity IDE";
|
||||
|
||||
function commands(runtime: EditorTargetRuntime): string[] {
|
||||
// `antigravity` is the launcher on other platforms and in builds before the rename.
|
||||
const candidates = ["antigravity-ide", "antigravity"];
|
||||
if (runtime.platform === "darwin") {
|
||||
const roots = ["/Applications"];
|
||||
if (runtime.env.HOME) roots.push(`${runtime.env.HOME}/Applications`);
|
||||
for (const root of roots) {
|
||||
candidates.push(`${root}/Antigravity IDE.app/Contents/Resources/app/bin/antigravity-ide`);
|
||||
candidates.push(`${root}/Antigravity.app/Contents/Resources/app/bin/antigravity`);
|
||||
}
|
||||
}
|
||||
return candidates;
|
||||
}
|
||||
|
||||
function location(input: EditorTargetLaunchInput): string {
|
||||
if (!input.line) return input.filePath!;
|
||||
@@ -26,11 +43,23 @@ export const antigravityTarget: EditorTarget = {
|
||||
};
|
||||
},
|
||||
async isInstalled(runtime) {
|
||||
return runtime.resolveCommand(COMMANDS) !== null;
|
||||
return (
|
||||
runtime.resolveCommand(commands(runtime)) !== null || runtime.hasMacApplication(APP_NAME)
|
||||
);
|
||||
},
|
||||
async launch(input, runtime) {
|
||||
const command = runtime.resolveCommand(COMMANDS);
|
||||
if (!command) throw new Error("Antigravity is not installed");
|
||||
await runtime.spawnDetached({ command, args: launchArgs(input) });
|
||||
const command = runtime.resolveCommand(commands(runtime));
|
||||
if (command) {
|
||||
await runtime.spawnDetached({ command, args: launchArgs(input) });
|
||||
return;
|
||||
}
|
||||
if (runtime.hasMacApplication(APP_NAME)) {
|
||||
await runtime.openMacApplication({
|
||||
applicationName: APP_NAME,
|
||||
paths: input.filePath ? [input.workspacePath, input.filePath] : [input.workspacePath],
|
||||
});
|
||||
return;
|
||||
}
|
||||
throw new Error("Antigravity is not installed");
|
||||
},
|
||||
};
|
||||
|
||||
@@ -2304,7 +2304,14 @@ class AcpRuntime {
|
||||
if (!active.deferred && wasOpenQualifying && !isOpen && this.toolKeepsTurnOpen(snapshot)) {
|
||||
active.crossedEndTurn = true;
|
||||
}
|
||||
if (isOpenQualifying) active.replyState = "idle";
|
||||
if (
|
||||
isOpenQualifying ||
|
||||
(!isOpen &&
|
||||
this.toolKeepsTurnOpen(snapshot) &&
|
||||
active.replyState === "settled_with_open_tools")
|
||||
) {
|
||||
active.replyState = "idle";
|
||||
}
|
||||
if (active.deferred) this.scheduleDeferredSettle();
|
||||
}
|
||||
|
||||
|
||||
@@ -5518,7 +5518,7 @@ describe("deferTurnOnRunningTools", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("settles on the reply timer when reply usage arrives before the final background tool completes", async () => {
|
||||
it("keeps the turn open after an interim status reply while another background tool is still running", async () => {
|
||||
const { connector, instances } = connectorHarness({
|
||||
handleRequest(instance, request) {
|
||||
if (request.method !== "session/prompt") return false;
|
||||
@@ -5526,9 +5526,9 @@ describe("deferTurnOnRunningTools", () => {
|
||||
sessionId: "connector-session",
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId: "bg-u1",
|
||||
toolCallId: "bg-interim-1",
|
||||
name: "run_command",
|
||||
title: "Job 1",
|
||||
title: "Build",
|
||||
status: "in_progress",
|
||||
},
|
||||
});
|
||||
@@ -5536,9 +5536,9 @@ describe("deferTurnOnRunningTools", () => {
|
||||
sessionId: "connector-session",
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId: "bg-u2",
|
||||
toolCallId: "bg-interim-2",
|
||||
name: "run_command",
|
||||
title: "Job 2",
|
||||
title: "Review",
|
||||
status: "in_progress",
|
||||
},
|
||||
});
|
||||
@@ -5547,12 +5547,12 @@ describe("deferTurnOnRunningTools", () => {
|
||||
},
|
||||
});
|
||||
const registration = runAcpProvider({
|
||||
id: "deferred-usage-before-tool",
|
||||
label: "Deferred Usage Before Tool",
|
||||
id: "deferred-interim-reply-two-tools",
|
||||
label: "Deferred Interim Reply Two Tools",
|
||||
connector,
|
||||
acpOptions: {
|
||||
deferTurnOnRunningTools: {
|
||||
settleDelayMs: 30,
|
||||
settleDelayMs: 40,
|
||||
quietLimitMs: 1_500,
|
||||
},
|
||||
},
|
||||
@@ -5570,9 +5570,9 @@ describe("deferTurnOnRunningTools", () => {
|
||||
type: "session.prompt",
|
||||
sessionId: "session-1",
|
||||
prompt: {
|
||||
clientMessageId: "usage-first-turn",
|
||||
clientMessageId: "interim-two-tools-turn",
|
||||
delivery: "auto",
|
||||
input: { type: "message", content: [{ type: "text", text: "run jobs" }] },
|
||||
input: { type: "message", content: [{ type: "text", text: "build and review" }] },
|
||||
},
|
||||
});
|
||||
await waitForEvent(
|
||||
@@ -5580,47 +5580,310 @@ describe("deferTurnOnRunningTools", () => {
|
||||
(event) =>
|
||||
event.type === "timeline.item" &&
|
||||
event.item.type === "tool_call" &&
|
||||
event.item.id === "bg-u2",
|
||||
event.item.id === "bg-interim-2",
|
||||
);
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
|
||||
// Job 1 finishes, reply + usage_update arrive while Job 2 is still running.
|
||||
// Job 1 completes and the agent sends an interim status reply + usage while Job 2 is still running.
|
||||
instances[1].notify("session/update", {
|
||||
sessionId: "connector-session",
|
||||
update: { sessionUpdate: "tool_call_update", toolCallId: "bg-u1", status: "completed" },
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId: "bg-interim-1",
|
||||
status: "completed",
|
||||
},
|
||||
});
|
||||
instances[1].notify("session/update", {
|
||||
sessionId: "connector-session",
|
||||
update: textChunk("All done."),
|
||||
update: textChunk("Build passed, waiting on review."),
|
||||
});
|
||||
instances[1].notify("session/update", {
|
||||
sessionId: "connector-session",
|
||||
update: { sessionUpdate: "usage_update", used: 300, size: 1000 },
|
||||
});
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
// Still running because Job 2 has not completed yet.
|
||||
await new Promise((resolve) => setTimeout(resolve, 60));
|
||||
expect(
|
||||
events.some(
|
||||
(event) =>
|
||||
event.type === "session.turn" &&
|
||||
event.turnId === "acp:usage-first-turn" &&
|
||||
event.turnId === "acp:interim-two-tools-turn" &&
|
||||
event.state !== "started",
|
||||
),
|
||||
).toBe(false);
|
||||
|
||||
// Job 2 completes -> should settle via settleDelayMs, not quietLimitMs.
|
||||
// Job 2 completes; pause longer than settleDelayMs to simulate LLM TTFB before wakeup chunks stream.
|
||||
instances[1].notify("session/update", {
|
||||
sessionId: "connector-session",
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId: "bg-interim-2",
|
||||
status: "completed",
|
||||
},
|
||||
});
|
||||
await new Promise((resolve) => setTimeout(resolve, 160));
|
||||
expect(
|
||||
events.some(
|
||||
(event) =>
|
||||
event.type === "session.turn" &&
|
||||
event.turnId === "acp:interim-two-tools-turn" &&
|
||||
event.state !== "started",
|
||||
),
|
||||
).toBe(false);
|
||||
|
||||
// Follow-up reply arrives after all tools are complete -> settles via settleDelayMs.
|
||||
instances[1].notify("session/update", {
|
||||
sessionId: "connector-session",
|
||||
update: {
|
||||
sessionUpdate: "agent_thought_chunk",
|
||||
content: { type: "text", text: "Reviewing findings..." },
|
||||
},
|
||||
});
|
||||
instances[1].notify("session/update", {
|
||||
sessionId: "connector-session",
|
||||
update: textChunk("Review complete and applied."),
|
||||
});
|
||||
const startedAt = Date.now();
|
||||
instances[1].notify("session/update", {
|
||||
sessionId: "connector-session",
|
||||
update: { sessionUpdate: "tool_call_update", toolCallId: "bg-u2", status: "completed" },
|
||||
update: { sessionUpdate: "usage_update", used: 450, size: 1000 },
|
||||
});
|
||||
await waitForEvent(
|
||||
events,
|
||||
(event) =>
|
||||
event.type === "session.turn" &&
|
||||
event.turnId === "acp:usage-first-turn" &&
|
||||
event.turnId === "acp:interim-two-tools-turn" &&
|
||||
event.state === "completed",
|
||||
);
|
||||
expect(Date.now() - startedAt).toBeLessThan(400);
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps the turn open after a mid-wait status check reply on a single background tool", async () => {
|
||||
const { connector, instances } = connectorHarness({
|
||||
handleRequest(instance, request) {
|
||||
if (request.method !== "session/prompt") return false;
|
||||
instance.notify("session/update", {
|
||||
sessionId: "connector-session",
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId: "bg-long",
|
||||
name: "run_command",
|
||||
title: "Long review",
|
||||
status: "in_progress",
|
||||
},
|
||||
});
|
||||
instance.respond(request, { stopReason: "end_turn" });
|
||||
return true;
|
||||
},
|
||||
});
|
||||
const registration = runAcpProvider({
|
||||
id: "deferred-interim-status-check",
|
||||
label: "Deferred Interim Status Check",
|
||||
connector,
|
||||
acpOptions: {
|
||||
deferTurnOnRunningTools: {
|
||||
settleDelayMs: 40,
|
||||
quietLimitMs: 1_500,
|
||||
},
|
||||
},
|
||||
});
|
||||
const connection = await registration.connect({
|
||||
versions: [1],
|
||||
capabilities: ["prompt.message"],
|
||||
});
|
||||
const events: ProviderEvent[] = [];
|
||||
connection.onEvent((event) => events.push(event));
|
||||
try {
|
||||
await connection.send(openInput());
|
||||
await waitForEvent(events, (event) => event.type === "session.ready");
|
||||
await connection.send({
|
||||
type: "session.prompt",
|
||||
sessionId: "session-1",
|
||||
prompt: {
|
||||
clientMessageId: "interim-status-check-turn",
|
||||
delivery: "auto",
|
||||
input: { type: "message", content: [{ type: "text", text: "run long review" }] },
|
||||
},
|
||||
});
|
||||
await waitForEvent(
|
||||
events,
|
||||
(event) =>
|
||||
event.type === "timeline.item" &&
|
||||
event.item.type === "tool_call" &&
|
||||
event.item.id === "bg-long",
|
||||
);
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
|
||||
// Mid-wait notification wakes the agent to inspect task status and send a progress update.
|
||||
instances[1].notify("session/update", {
|
||||
sessionId: "connector-session",
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId: "check-1",
|
||||
name: "manage_task",
|
||||
title: "Manage task",
|
||||
status: "in_progress",
|
||||
},
|
||||
});
|
||||
instances[1].notify("session/update", {
|
||||
sessionId: "connector-session",
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId: "check-1",
|
||||
status: "completed",
|
||||
},
|
||||
});
|
||||
instances[1].notify("session/update", {
|
||||
sessionId: "connector-session",
|
||||
update: textChunk("Still running, continuing to wait."),
|
||||
});
|
||||
instances[1].notify("session/update", {
|
||||
sessionId: "connector-session",
|
||||
update: { sessionUpdate: "usage_update", used: 250, size: 1000 },
|
||||
});
|
||||
await new Promise((resolve) => setTimeout(resolve, 60));
|
||||
|
||||
// Long background job finally completes; turn must remain open past settleDelayMs for follow-up.
|
||||
instances[1].notify("session/update", {
|
||||
sessionId: "connector-session",
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId: "bg-long",
|
||||
status: "completed",
|
||||
},
|
||||
});
|
||||
await new Promise((resolve) => setTimeout(resolve, 160));
|
||||
expect(
|
||||
events.some(
|
||||
(event) =>
|
||||
event.type === "session.turn" &&
|
||||
event.turnId === "acp:interim-status-check-turn" &&
|
||||
event.state !== "started",
|
||||
),
|
||||
).toBe(false);
|
||||
|
||||
// Final reply arrives -> settles quickly via settleDelayMs.
|
||||
instances[1].notify("session/update", {
|
||||
sessionId: "connector-session",
|
||||
update: textChunk("Long review finished."),
|
||||
});
|
||||
const startedAt = Date.now();
|
||||
instances[1].notify("session/update", {
|
||||
sessionId: "connector-session",
|
||||
update: { sessionUpdate: "usage_update", used: 400, size: 1000 },
|
||||
});
|
||||
await waitForEvent(
|
||||
events,
|
||||
(event) =>
|
||||
event.type === "session.turn" &&
|
||||
event.turnId === "acp:interim-status-check-turn" &&
|
||||
event.state === "completed",
|
||||
);
|
||||
expect(Date.now() - startedAt).toBeLessThan(400);
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("settles on the reply timer when an open tool is reclassified as an excluded daemon after reply usage", async () => {
|
||||
const { connector, instances } = connectorHarness({
|
||||
handleRequest(instance, request) {
|
||||
if (request.method !== "session/prompt") return false;
|
||||
instance.notify("session/update", {
|
||||
sessionId: "connector-session",
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId: "late-daemon",
|
||||
name: "run_command",
|
||||
title: "Dev server",
|
||||
status: "in_progress",
|
||||
},
|
||||
});
|
||||
instance.respond(request, { stopReason: "end_turn" });
|
||||
return true;
|
||||
},
|
||||
});
|
||||
const registration = runAcpProvider({
|
||||
id: "deferred-daemon-reclassify-after-usage",
|
||||
label: "Deferred Daemon Reclassify After Usage",
|
||||
connector,
|
||||
acpOptions: {
|
||||
deferTurnOnRunningTools: {
|
||||
settleDelayMs: 40,
|
||||
quietLimitMs: 1_500,
|
||||
keepsTurnOpen(toolCall) {
|
||||
const input = toolCall.input;
|
||||
if (typeof input !== "object" || input === null || Array.isArray(input)) return true;
|
||||
return input.IsDaemon !== true;
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
const connection = await registration.connect({
|
||||
versions: [1],
|
||||
capabilities: ["prompt.message"],
|
||||
});
|
||||
const events: ProviderEvent[] = [];
|
||||
connection.onEvent((event) => events.push(event));
|
||||
try {
|
||||
await connection.send(openInput());
|
||||
await waitForEvent(events, (event) => event.type === "session.ready");
|
||||
await connection.send({
|
||||
type: "session.prompt",
|
||||
sessionId: "session-1",
|
||||
prompt: {
|
||||
clientMessageId: "daemon-reclassify-after-usage-turn",
|
||||
delivery: "auto",
|
||||
input: { type: "message", content: [{ type: "text", text: "start dev server" }] },
|
||||
},
|
||||
});
|
||||
await waitForEvent(
|
||||
events,
|
||||
(event) =>
|
||||
event.type === "timeline.item" &&
|
||||
event.item.type === "tool_call" &&
|
||||
event.item.id === "late-daemon",
|
||||
);
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
|
||||
// Final reply + usage arrive before rawInput identifies the running tool as a daemon.
|
||||
instances[1].notify("session/update", {
|
||||
sessionId: "connector-session",
|
||||
update: textChunk("Dev server is up."),
|
||||
});
|
||||
instances[1].notify("session/update", {
|
||||
sessionId: "connector-session",
|
||||
update: { sessionUpdate: "usage_update", used: 200, size: 1000 },
|
||||
});
|
||||
await new Promise((resolve) => setTimeout(resolve, 60));
|
||||
expect(
|
||||
events.some(
|
||||
(event) =>
|
||||
event.type === "session.turn" &&
|
||||
event.turnId === "acp:daemon-reclassify-after-usage-turn" &&
|
||||
event.state !== "started",
|
||||
),
|
||||
).toBe(false);
|
||||
|
||||
// Reclassifying the still-running tool as a daemon releases the settled reply on settleDelayMs.
|
||||
const startedAt = Date.now();
|
||||
instances[1].notify("session/update", {
|
||||
sessionId: "connector-session",
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId: "late-daemon",
|
||||
status: "in_progress",
|
||||
rawInput: { CommandLine: "npm run dev", IsDaemon: true },
|
||||
},
|
||||
});
|
||||
await waitForEvent(
|
||||
events,
|
||||
(event) =>
|
||||
event.type === "session.turn" &&
|
||||
event.turnId === "acp:daemon-reclassify-after-usage-turn" &&
|
||||
event.state === "completed",
|
||||
400,
|
||||
);
|
||||
expect(Date.now() - startedAt).toBeLessThan(400);
|
||||
} finally {
|
||||
|
||||
@@ -196,7 +196,7 @@ describe("Claude SDK env", () => {
|
||||
await resumed.run("after disable");
|
||||
expect(prompts).toEqual([
|
||||
{ type: "preset", preset: "claude_code", append: "Plugin instructions" },
|
||||
{ type: "preset", preset: "claude_code", append: "" },
|
||||
{ type: "preset", preset: "claude_code", append: "", snapshot: false },
|
||||
]);
|
||||
} finally {
|
||||
await resumed.close();
|
||||
|
||||
@@ -4240,6 +4240,8 @@ class ClaudeAgentSession implements AgentSession {
|
||||
type: "preset",
|
||||
preset: "claude_code",
|
||||
append: appendedSystemPrompt,
|
||||
// Rebuild on resume so the current launch can replace or remove plugin instructions.
|
||||
...(sessionBinding.resume ? { snapshot: false } : {}),
|
||||
},
|
||||
settingSources: CLAUDE_SETTING_SOURCES,
|
||||
stderr: (data: string) => {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, onTestFinished, test } from "vitest";
|
||||
import { setImmediate as waitForImmediate } from "node:timers/promises";
|
||||
import { setImmediate as waitForImmediate, setTimeout as delay } from "node:timers/promises";
|
||||
import { mkdtemp, mkdir, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
@@ -148,6 +148,9 @@ class ManualIdleScheduler implements OmpProviderIdleScheduler {
|
||||
if (this.waitCount >= count) return Promise.resolve();
|
||||
return new Promise((resolve) => this.waiters.push({ count, resolve }));
|
||||
}
|
||||
waits(): number {
|
||||
return this.waitCount;
|
||||
}
|
||||
|
||||
retry(): void {
|
||||
const resolve = this.retries.shift();
|
||||
@@ -540,10 +543,78 @@ describe("OMP agent client and session", () => {
|
||||
args: { command: "sleep 30" },
|
||||
});
|
||||
expect(omp.runningToolCallIds()).toEqual(["tool-at-deadline"]);
|
||||
await new Promise((resolve) => setTimeout(resolve, 60));
|
||||
await delay(60);
|
||||
scheduler.retry();
|
||||
await expect(completion).rejects.toThrow(/provider idle/i);
|
||||
expect(omp.runningToolCallIds()).toEqual([]);
|
||||
// The provider still owned the turn when the gate expired. Abort it so the
|
||||
// next prompt is not rejected with "Agent is already processing".
|
||||
expect(omp.wasAborted()).toBe(true);
|
||||
});
|
||||
|
||||
test("does not start the idle wait for a non-terminal agent_end", async () => {
|
||||
const scheduler = new ManualIdleScheduler();
|
||||
const omp = new OmpHarness({ providerIdleScheduler: scheduler, providerIdleDeadlineMs: 50 });
|
||||
await omp.start();
|
||||
const { completion } = await omp.startPromptWithNonTerminalEnd("first", "first done");
|
||||
|
||||
await delay(70);
|
||||
expect(scheduler.waits()).toBe(0);
|
||||
expect(omp.completedTurnCount()).toBe(0);
|
||||
|
||||
const runtime = omp.runtime();
|
||||
runtime.beginTurn();
|
||||
runtime.streamAssistantText("continued");
|
||||
runtime.state = { ...runtime.state, isStreaming: false, isCompacting: false };
|
||||
runtime.finishTurn();
|
||||
|
||||
await expect(completion).resolves.toMatchObject({
|
||||
finalText: expect.stringContaining("continued"),
|
||||
});
|
||||
});
|
||||
|
||||
test("extends the idle deadline while the provider keeps producing events", async () => {
|
||||
const scheduler = new ManualIdleScheduler();
|
||||
const omp = new OmpHarness({ providerIdleScheduler: scheduler, providerIdleDeadlineMs: 80 });
|
||||
await omp.start();
|
||||
const { completion } = await omp.startPromptUntilProviderIdle("first", "first done", {
|
||||
isStreaming: true,
|
||||
isCompacting: false,
|
||||
});
|
||||
await scheduler.waitForWaits(1);
|
||||
|
||||
await delay(50);
|
||||
omp.runtime().emit({ type: "turn_start" });
|
||||
await delay(50);
|
||||
scheduler.retry();
|
||||
await waitForImmediate();
|
||||
|
||||
expect(omp.completedTurnCount()).toBe(0);
|
||||
|
||||
omp.reportProviderState({ isStreaming: false, isCompacting: false });
|
||||
scheduler.retry();
|
||||
await expect(completion).resolves.toMatchObject({ finalText: "first done" });
|
||||
});
|
||||
|
||||
test("keeps the turn active while an OMP question waits for the user", async () => {
|
||||
const scheduler = new ManualIdleScheduler();
|
||||
const omp = new OmpHarness({ providerIdleScheduler: scheduler, providerIdleDeadlineMs: 50 });
|
||||
await omp.start();
|
||||
const { completion } = await omp.startPromptUntilProviderIdle("first", "first done", {
|
||||
isStreaming: true,
|
||||
isCompacting: false,
|
||||
});
|
||||
await scheduler.waitForWaits(1);
|
||||
|
||||
omp.requestToolApproval({ id: "approval-1", tool: "bash", detail: "echo hi" });
|
||||
scheduler.retry();
|
||||
await delay(70);
|
||||
|
||||
expect(omp.completedTurnCount()).toBe(0);
|
||||
|
||||
omp.reportProviderState({ isStreaming: false, isCompacting: false });
|
||||
await omp.respondToPermission("approval-1", { behavior: "allow" });
|
||||
await expect(completion).resolves.toMatchObject({ finalText: "first done" });
|
||||
});
|
||||
|
||||
test("steers a running turn and correlates a template-expanded echo exactly once", async () => {
|
||||
@@ -2296,3 +2367,26 @@ describe("OMP catalog model labels", () => {
|
||||
expect(catalog.models[0]?.id).toBe(`${model.provider}/${model.id}`);
|
||||
});
|
||||
});
|
||||
|
||||
test("OMP catalog sessions skip startup work that agent sessions keep", async () => {
|
||||
const runtime = new FakeOmp();
|
||||
const client = new OmpAgentClient({ logger: createTestLogger(), runtime });
|
||||
const catalogOnlyFlags = ["--no-skills", "--no-session", "--no-title"];
|
||||
|
||||
await client.fetchCatalog({ scope: "workspace", cwd: "/workspace/project", force: false });
|
||||
const session = await client.createSession({ provider: "omp", cwd: "/workspace/project" });
|
||||
onTestFinished(() => session.close());
|
||||
|
||||
const [catalogLaunch, agentLaunch] = runtime.recordedLaunches;
|
||||
expect(catalogLaunch?.argv).toEqual([
|
||||
"omp",
|
||||
"--mode",
|
||||
"rpc-ui",
|
||||
"--approval-mode",
|
||||
"yolo",
|
||||
...catalogOnlyFlags,
|
||||
]);
|
||||
for (const flag of catalogOnlyFlags) {
|
||||
expect(agentLaunch?.argv).not.toContain(flag);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -721,6 +721,8 @@ export class OmpAgentSession implements AgentSession {
|
||||
);
|
||||
private closed = false;
|
||||
private live: boolean;
|
||||
private lastProviderActivityAt = Date.now();
|
||||
private readonly extensionUiWaiters = new Set<() => void>();
|
||||
private readonly emittedUserMessageIds = new Set<string>();
|
||||
|
||||
private readonly usageSessionKey = randomUUID();
|
||||
@@ -891,6 +893,7 @@ export class OmpAgentSession implements AgentSession {
|
||||
throw new Error("An OMP turn is already active");
|
||||
}
|
||||
|
||||
this.lastProviderActivityAt = Date.now();
|
||||
const turnId = randomUUID();
|
||||
this.live = true;
|
||||
this.activeTurnId = turnId;
|
||||
@@ -978,6 +981,7 @@ export class OmpAgentSession implements AgentSession {
|
||||
return { status: "unavailable" };
|
||||
if (this.parseSlashCommandInput(payload.text)) return { status: "unavailable" };
|
||||
const submission = this.rememberClientMessage(options.clientMessageId ?? null, payload.text);
|
||||
this.lastProviderActivityAt = Date.now();
|
||||
try {
|
||||
await this.runtimeSession.steer(payload.text, payload.images);
|
||||
} catch (error) {
|
||||
@@ -1150,6 +1154,8 @@ export class OmpAgentSession implements AgentSession {
|
||||
throw new Error(`No pending permission request with id '${requestId}'`);
|
||||
}
|
||||
this.pendingExtensionUiRequests.delete(requestId);
|
||||
this.lastProviderActivityAt = Date.now();
|
||||
this.notifyExtensionUiWaiters();
|
||||
|
||||
const approvalResponse = buildOmpRpcUiPermissionResponse(request, response);
|
||||
if (approvalResponse) {
|
||||
@@ -1188,6 +1194,7 @@ export class OmpAgentSession implements AgentSession {
|
||||
async interrupt(): Promise<void> {
|
||||
const turnId = this.activeTurnId;
|
||||
await this.runtimeSession.abort();
|
||||
this.clearPendingExtensionUiRequests();
|
||||
if (turnId && this.activeTurnId === turnId) {
|
||||
this.usagePoller.stopTurn();
|
||||
this.resetActiveTurn({ terminalizeWork: true });
|
||||
@@ -1242,6 +1249,7 @@ export class OmpAgentSession implements AgentSession {
|
||||
this.unsubscribeRuntime?.();
|
||||
this.usagePoller.close();
|
||||
this.cancelNoTurnPromptCompletion();
|
||||
this.clearPendingExtensionUiRequests();
|
||||
try {
|
||||
await this.runtimeSession.close();
|
||||
} finally {
|
||||
@@ -1289,6 +1297,7 @@ export class OmpAgentSession implements AgentSession {
|
||||
this.pendingClientMessages.length = 0;
|
||||
this.turnMeter.reset();
|
||||
this.clearNoTurnBuffers();
|
||||
this.wakeExtensionUiWaiters();
|
||||
}
|
||||
|
||||
async listCommands(): Promise<AgentSlashCommand[]> {
|
||||
@@ -1671,6 +1680,8 @@ export class OmpAgentSession implements AgentSession {
|
||||
/** OMP aborted or timed out a dialog: close its card without a reply OMP would reject. */
|
||||
private closeExtensionUiRequest(requestId: string): void {
|
||||
if (!this.pendingExtensionUiRequests.delete(requestId)) return;
|
||||
this.lastProviderActivityAt = Date.now();
|
||||
this.notifyExtensionUiWaiters();
|
||||
this.questionUi.forget(requestId);
|
||||
this.emit({
|
||||
type: "permission_resolved",
|
||||
@@ -1681,6 +1692,29 @@ export class OmpAgentSession implements AgentSession {
|
||||
});
|
||||
}
|
||||
|
||||
private waitForExtensionUiRequestsToClear(): Promise<void> {
|
||||
if (this.pendingExtensionUiRequests.size === 0) return Promise.resolve();
|
||||
return new Promise((resolve) => this.extensionUiWaiters.add(resolve));
|
||||
}
|
||||
|
||||
private notifyExtensionUiWaiters(): void {
|
||||
if (this.pendingExtensionUiRequests.size > 0) return;
|
||||
this.wakeExtensionUiWaiters();
|
||||
}
|
||||
|
||||
private wakeExtensionUiWaiters(): void {
|
||||
for (const resolve of this.extensionUiWaiters) resolve();
|
||||
this.extensionUiWaiters.clear();
|
||||
}
|
||||
|
||||
private clearPendingExtensionUiRequests(): void {
|
||||
for (const requestId of this.pendingExtensionUiRequests.keys()) {
|
||||
this.questionUi.forget(requestId);
|
||||
}
|
||||
this.pendingExtensionUiRequests.clear();
|
||||
this.wakeExtensionUiWaiters();
|
||||
}
|
||||
|
||||
private mapExtensionUiSideEffect(
|
||||
event: Extract<OmpRuntimeEvent, { type: "extension_ui_request" }>,
|
||||
): AgentTimelineItem | null {
|
||||
@@ -1851,6 +1885,9 @@ export class OmpAgentSession implements AgentSession {
|
||||
}
|
||||
|
||||
private handleRuntimeEvent(event: OmpRuntimeEvent): void {
|
||||
// The idle deadline measures provider silence. Any event, including a
|
||||
// non-terminal agent_end or a subagent update, proves OMP is still alive.
|
||||
this.lastProviderActivityAt = Date.now();
|
||||
if (isExtensionUiRequestEvent(event)) {
|
||||
this.handleExtensionUiRequest(event);
|
||||
return;
|
||||
@@ -1989,6 +2026,12 @@ export class OmpAgentSession implements AgentSession {
|
||||
this.handleCompactionEvent(event, turnId);
|
||||
return;
|
||||
case "agent_end": {
|
||||
// OMP reports a turn that has a queued continuation or async delivery
|
||||
// as non-terminal. The final end owns the idle wait; starting the
|
||||
// failure clock here would fail a turn that is still running.
|
||||
if (event.isTerminal === false) {
|
||||
return;
|
||||
}
|
||||
const messages = event.messages ?? [];
|
||||
let terminalMessages: OmpAgentMessage[] | null = null;
|
||||
if (messages.some((message) => message.role === "assistant")) {
|
||||
@@ -2321,17 +2364,16 @@ export class OmpAgentSession implements AgentSession {
|
||||
turnId: string | undefined,
|
||||
messages: OmpAgentMessage[],
|
||||
): Promise<void> {
|
||||
const deadline = Date.now() + this.providerIdleDeadlineMs;
|
||||
while (!this.closed && this.activeTurnStarted && this.currentTurnIdForEvent() === turnId) {
|
||||
if (Date.now() >= deadline) {
|
||||
// A question or approval waiting for the user is not a hung provider.
|
||||
// Wait for the card to settle instead of counting the wait as silence.
|
||||
if (this.pendingExtensionUiRequests.size > 0) {
|
||||
await this.waitForExtensionUiRequestsToClear();
|
||||
continue;
|
||||
}
|
||||
if (Date.now() - this.lastProviderActivityAt >= this.providerIdleDeadlineMs) {
|
||||
this.usagePoller.stopTurn();
|
||||
this.resetActiveTurn({ terminalizeWork: true });
|
||||
this.emit({
|
||||
type: "turn_failed",
|
||||
provider: this.provider,
|
||||
turnId,
|
||||
error: "OMP provider idle deadline exceeded",
|
||||
});
|
||||
await this.failProviderIdleTurn(turnId);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
@@ -2352,6 +2394,34 @@ export class OmpAgentSession implements AgentSession {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The provider still owns the turn after the idle deadline. Abort it before
|
||||
* failing so the next prompt is not rejected with "Agent is already
|
||||
* processing"; if the abort fails, replace the runtime on the next prompt.
|
||||
*/
|
||||
private async failProviderIdleTurn(turnId: string | undefined): Promise<void> {
|
||||
try {
|
||||
await this.runtimeSession.abort();
|
||||
} catch (error) {
|
||||
this.logger.warn(
|
||||
{ err: error },
|
||||
"OMP idle deadline abort failed; the next prompt will replace the runtime",
|
||||
);
|
||||
this.runtimeDead = true;
|
||||
}
|
||||
this.clearPendingExtensionUiRequests();
|
||||
if (this.closed || this.currentTurnIdForEvent() !== turnId) {
|
||||
return;
|
||||
}
|
||||
this.resetActiveTurn({ terminalizeWork: true });
|
||||
this.emit({
|
||||
type: "turn_failed",
|
||||
provider: this.provider,
|
||||
turnId,
|
||||
error: "OMP provider idle deadline exceeded",
|
||||
});
|
||||
}
|
||||
|
||||
private async refreshState(): Promise<void> {
|
||||
this.installState(await this.runtimeSession.getState());
|
||||
}
|
||||
@@ -2660,7 +2730,11 @@ export class OmpAgentClient implements AgentClient {
|
||||
cwd: options.scope === "global" ? homedir() : options.cwd,
|
||||
protocolMode: "rpc-ui",
|
||||
modeId: launchMode.modeId,
|
||||
extraArgs: launchMode.extraArgs,
|
||||
// Catalogue sessions only answer get_available_models. --no-skills stops OMP's
|
||||
// startup routing-hint compression calls, which the close would cancel every
|
||||
// refresh. Never add --no-tools: it skips provider extensions, and
|
||||
// get_available_models then never answers.
|
||||
extraArgs: [...launchMode.extraArgs, "--no-skills", "--no-session", "--no-title"],
|
||||
signal: context?.signal,
|
||||
});
|
||||
if (context?.signal.aborted) await closeSession();
|
||||
|
||||
@@ -384,7 +384,13 @@ export const OmpAgentSessionEventSchema = z.discriminatedUnion("type", [
|
||||
})
|
||||
.passthrough(),
|
||||
z
|
||||
.object({ type: z.literal("agent_end"), messages: z.array(OmpAgentMessageSchema).optional() })
|
||||
.object({
|
||||
type: z.literal("agent_end"),
|
||||
messages: z.array(OmpAgentMessageSchema).optional(),
|
||||
// OMP marks an end that still has a queued continuation or async delivery
|
||||
// as non-terminal. The final end is the one that owns the idle wait.
|
||||
isTerminal: z.boolean().optional(),
|
||||
})
|
||||
.passthrough(),
|
||||
]);
|
||||
|
||||
|
||||
@@ -488,9 +488,16 @@ export class FakeOmpSession implements OmpRuntimeSession {
|
||||
}
|
||||
}
|
||||
|
||||
finishTurn(message: OmpAgentMessage = { role: "assistant", content: [] }): void {
|
||||
finishTurn(
|
||||
message: OmpAgentMessage = { role: "assistant", content: [] },
|
||||
options: { isTerminal?: boolean } = {},
|
||||
): void {
|
||||
this.messages = [...this.messages, message];
|
||||
this.emit({ type: "agent_end", messages: this.messages });
|
||||
this.emit({
|
||||
type: "agent_end",
|
||||
messages: this.messages,
|
||||
...(options.isTerminal === undefined ? {} : { isTerminal: options.isTerminal }),
|
||||
});
|
||||
}
|
||||
|
||||
finishTurnWithEmptyAgentEnd(message: OmpAgentMessage = { role: "assistant", content: [] }): void {
|
||||
|
||||
@@ -283,6 +283,23 @@ export class OmpHarness {
|
||||
return { completion: run };
|
||||
}
|
||||
|
||||
async startPromptWithNonTerminalEnd(
|
||||
input: string,
|
||||
output: string,
|
||||
): Promise<{ completion: Promise<unknown> }> {
|
||||
const session = this.requireSession();
|
||||
const promptStarted = this.omp.latestSession().nextPrompt();
|
||||
const completion = session.run(input);
|
||||
await promptStarted;
|
||||
const runtime = this.omp.latestSession();
|
||||
runtime.beginTurn();
|
||||
runtime.acceptPrompt(input, "user-1");
|
||||
runtime.streamAssistantText(output);
|
||||
runtime.state = { ...runtime.state, isStreaming: true, isCompacting: false };
|
||||
runtime.finishTurn(undefined, { isTerminal: false });
|
||||
return { completion };
|
||||
}
|
||||
|
||||
waitForProviderStateChecks(count: number): Promise<void> {
|
||||
return this.omp.latestSession().waitForStateRequests(count);
|
||||
}
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import { createServer } from "node:http";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import pino from "pino";
|
||||
import { expect, test } from "vitest";
|
||||
import { DaemonClient } from "../test-utils/daemon-client.js";
|
||||
import type { AgentClient, AgentSessionConfig } from "../agent/agent-sdk-types.js";
|
||||
import { ClaudeAgentClient } from "../agent/providers/claude/agent.js";
|
||||
import { createTestAgentClient } from "../test-utils/fake-agent-client.js";
|
||||
import { createTestPaseoDaemon } from "../test-utils/paseo-daemon.js";
|
||||
import { createTestPaseoDaemon, type TestPaseoDaemon } from "../test-utils/paseo-daemon.js";
|
||||
|
||||
test("the configuration example saves Codex options and injects launch-only MCP servers while preserving other configuration", async () => {
|
||||
const directory = await mkdtemp(path.join(tmpdir(), "paseo-config-example-"));
|
||||
@@ -73,6 +76,132 @@ test("the configuration example saves Codex options and injects launch-only MCP
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
test("Claude sends the current plugin system prompt after refreshing a session", async () => {
|
||||
const directory = await mkdtemp(path.join(tmpdir(), "paseo-claude-append-"));
|
||||
const configDir = path.join(directory, "claude");
|
||||
const pluginId = "claude-append-test";
|
||||
const requests: { markers: string[]; hasPriorTurn: boolean }[] = [];
|
||||
const model = "claude-haiku-4-5-20251001";
|
||||
// Run Claude Code's real prompt assembly and resume logic with a local Messages endpoint.
|
||||
const server = createServer(async (request, response) => {
|
||||
let body = "";
|
||||
for await (const chunk of request) body += chunk;
|
||||
if (!request.url?.match(/^\/v1\/messages(?:\?|$)/)) {
|
||||
response.writeHead(200, { "content-type": "application/json" });
|
||||
response.end("{}");
|
||||
return;
|
||||
}
|
||||
const payload = JSON.parse(body);
|
||||
const system = JSON.stringify(payload.system ?? "");
|
||||
requests.push({
|
||||
markers: ["PASEO-APPEND-ALPHA", "PASEO-APPEND-BETA"].filter((marker) =>
|
||||
system.includes(marker),
|
||||
),
|
||||
hasPriorTurn: JSON.stringify(payload.messages).includes("First turn of the append test."),
|
||||
});
|
||||
const events = [
|
||||
{
|
||||
type: "message_start",
|
||||
message: {
|
||||
id: `msg_append_${requests.length}`,
|
||||
type: "message",
|
||||
role: "assistant",
|
||||
model,
|
||||
content: [],
|
||||
stop_reason: null,
|
||||
stop_sequence: null,
|
||||
usage: { input_tokens: 100, output_tokens: 0 },
|
||||
},
|
||||
},
|
||||
{ type: "content_block_start", index: 0, content_block: { type: "text", text: "" } },
|
||||
{ type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "OK" } },
|
||||
{ type: "content_block_stop", index: 0 },
|
||||
{ type: "message_delta", delta: { stop_reason: "end_turn" }, usage: { output_tokens: 1 } },
|
||||
{ type: "message_stop" },
|
||||
];
|
||||
response.writeHead(200, { "content-type": "text/event-stream" });
|
||||
response.end(
|
||||
events.map((event) => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`).join(""),
|
||||
);
|
||||
});
|
||||
|
||||
async function writeHook(marker: string) {
|
||||
await writeFile(
|
||||
path.join(directory, "index.server.ts"),
|
||||
`export default function contribute(server) {
|
||||
return server.addHook("agent.open.before", ({ request }) => ({
|
||||
...request,
|
||||
appendSystemPrompt: [${JSON.stringify(marker)}],
|
||||
}));
|
||||
}`,
|
||||
);
|
||||
}
|
||||
|
||||
let daemon: TestPaseoDaemon | undefined;
|
||||
let client: DaemonClient | undefined;
|
||||
try {
|
||||
await mkdir(configDir);
|
||||
await writeFile(
|
||||
path.join(directory, "paseo-plugin.json"),
|
||||
JSON.stringify({ id: pluginId, requirements: { paseo: ">=0.17.0" } }),
|
||||
);
|
||||
await writeHook("PASEO-APPEND-ALPHA");
|
||||
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
|
||||
const address = server.address();
|
||||
if (!address || typeof address === "string") throw new Error("Fixture has no TCP address");
|
||||
const logger = pino({ level: "silent" });
|
||||
daemon = await createTestPaseoDaemon({
|
||||
daemonVersion: "0.17.5",
|
||||
agentClients: {
|
||||
claude: new ClaudeAgentClient({
|
||||
logger,
|
||||
runtimeSettings: {
|
||||
env: {
|
||||
ANTHROPIC_BASE_URL: `http://127.0.0.1:${address.port}`,
|
||||
ANTHROPIC_AUTH_TOKEN: "fixture-token",
|
||||
ANTHROPIC_API_KEY: "",
|
||||
CLAUDE_CODE_OAUTH_TOKEN: "",
|
||||
CLAUDE_CONFIG_DIR: configDir,
|
||||
CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1",
|
||||
},
|
||||
},
|
||||
}),
|
||||
},
|
||||
mcpEnabled: false,
|
||||
});
|
||||
client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws`, appVersion: "0.17.5" });
|
||||
await client.connect();
|
||||
await client.fetchAgents({ subscribe: {} });
|
||||
await client.patchDaemonConfig({ pluginsEnabled: true });
|
||||
expect((await client.installDirectoryPlugin(directory)).status).toBe("running");
|
||||
const agent = await client.createAgent({ provider: "claude", cwd: directory, model });
|
||||
|
||||
await client.sendMessage(agent.id, "First turn of the append test.");
|
||||
expect((await client.waitForFinish(agent.id, 15_000)).status).toBe("idle");
|
||||
expect(requests.at(-1)?.markers).toEqual(["PASEO-APPEND-ALPHA"]);
|
||||
|
||||
await writeHook("PASEO-APPEND-BETA");
|
||||
expect((await client.reloadPlugin(pluginId)).status).toBe("running");
|
||||
await client.refreshAgent(agent.id);
|
||||
await client.sendMessage(agent.id, "Second turn of the append test.");
|
||||
expect((await client.waitForFinish(agent.id, 15_000)).status).toBe("idle");
|
||||
expect(requests.at(-1)).toEqual({ markers: ["PASEO-APPEND-BETA"], hasPriorTurn: true });
|
||||
|
||||
await client.disablePlugin(pluginId);
|
||||
await client.refreshAgent(agent.id);
|
||||
await client.sendMessage(agent.id, "Third turn of the append test.");
|
||||
expect((await client.waitForFinish(agent.id, 15_000)).status).toBe("idle");
|
||||
expect(requests.at(-1)).toEqual({ markers: [], hasPriorTurn: true });
|
||||
expect(requests).toHaveLength(3);
|
||||
} finally {
|
||||
await client?.close();
|
||||
await daemon?.close();
|
||||
server.closeAllConnections();
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
test("session-open entrypoint contributions are optional and rederived for existing agents", async () => {
|
||||
const directory = await mkdtemp(path.join(tmpdir(), "paseo-entrypoint-hook-"));
|
||||
const launches: { provider: string; env?: Record<string, string> }[] = [];
|
||||
|
||||
@@ -136,12 +136,11 @@ describe.skipIf(isPlatform("win32"))("createForgeCliRunner", () => {
|
||||
}
|
||||
}
|
||||
|
||||
it("kills a hung CLI invocation after the configured timeout", async () => {
|
||||
const cli = writeSlowCli();
|
||||
it("kills a CLI that ignores SIGTERM at the configured timeout", async () => {
|
||||
const runner = createForgeCliRunner({
|
||||
binary: cli,
|
||||
binary: process.execPath,
|
||||
envOverlay: {},
|
||||
timeoutMs: 100,
|
||||
timeoutMs: 500,
|
||||
isAuthFailureText: () => false,
|
||||
errorClasses: {
|
||||
isAlreadyClassified: () => false,
|
||||
@@ -152,7 +151,12 @@ describe.skipIf(isPlatform("win32"))("createForgeCliRunner", () => {
|
||||
},
|
||||
});
|
||||
|
||||
await expect(runner.run(["arg"], { cwd: tempDir })).rejects.toThrow();
|
||||
await expect(
|
||||
runner.run(
|
||||
["-e", "process.on('SIGTERM', () => {}); setTimeout(() => process.exit(7), 2000);"],
|
||||
{ cwd: tempDir },
|
||||
),
|
||||
).rejects.toMatchObject({ killed: true, signal: "SIGKILL" });
|
||||
});
|
||||
|
||||
it("classifies a timed-out invocation through normalizeError", async () => {
|
||||
|
||||
@@ -161,6 +161,8 @@ export function createForgeCliRunner(options: CreateForgeCliRunnerOptions): Forg
|
||||
envOverlay: { ...options.envOverlay, ...runOptions.envOverlay },
|
||||
maxBuffer: 10 * 1024 * 1024,
|
||||
timeout: options.timeoutMs,
|
||||
// execFile sends one signal at the deadline. A CLI can ignore SIGTERM.
|
||||
killSignal: "SIGKILL",
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -76,7 +76,7 @@ export class Session {
|
||||
private readonly buffered: Notification[] = [];
|
||||
private opening = true;
|
||||
private closing = false;
|
||||
private firstTurn = true;
|
||||
private systemPromptPending = true;
|
||||
private interruptCompletion: {
|
||||
turnId: string;
|
||||
resolve(): void;
|
||||
@@ -122,7 +122,6 @@ export class Session {
|
||||
model: this.config.model ?? saved.model,
|
||||
thinkingOption: this.config.thinkingOption ?? saved.thinkingOption,
|
||||
};
|
||||
this.firstTurn = false;
|
||||
} else {
|
||||
response = await this.host.command(
|
||||
"session/start",
|
||||
@@ -242,7 +241,7 @@ export class Session {
|
||||
this.messages.set(id, prompt.clientMessageId);
|
||||
const input: TurnStartParams["input"] = [];
|
||||
const text: string[] = [];
|
||||
if (this.firstTurn && this.config.systemPrompt)
|
||||
if (this.systemPromptPending && this.config.systemPrompt)
|
||||
input.push({
|
||||
type: "text",
|
||||
text: `<system_instructions>\n${this.config.systemPrompt}\n</system_instructions>`,
|
||||
@@ -272,7 +271,7 @@ export class Session {
|
||||
: undefined,
|
||||
};
|
||||
const response = await this.host.command("turn/start", params, promptResultSchema);
|
||||
this.firstTurn = false;
|
||||
this.systemPromptPending = false;
|
||||
if (response.disposition === "started" && this.turns.get(response.turnId) !== "completed")
|
||||
this.turns.set(response.turnId, "active");
|
||||
this.live().recovery.activity(undefined, this.activeTurnIds().length > 0);
|
||||
|
||||
@@ -89,8 +89,11 @@ async function harness(
|
||||
}
|
||||
async function open(
|
||||
persistence?: Extract<ProviderInput, { type: "session.open" }>["persistence"],
|
||||
mode = "onRequest",
|
||||
model: string | null = "meta/muse-spark-1.3",
|
||||
{
|
||||
mode = "onRequest",
|
||||
model = "meta/muse-spark-1.3",
|
||||
systemPrompt = "Test instructions",
|
||||
}: { mode?: string; model?: string | null; systemPrompt?: string } = {},
|
||||
) {
|
||||
await send({
|
||||
type: "session.open",
|
||||
@@ -106,7 +109,7 @@ async function harness(
|
||||
mode,
|
||||
model: model ?? undefined,
|
||||
thinkingOption: "high",
|
||||
systemPrompt: "Test instructions",
|
||||
systemPrompt,
|
||||
},
|
||||
persistence,
|
||||
history: "replay",
|
||||
@@ -411,7 +414,7 @@ test("multi-stage approvals surface Stage 2 then Stage 3 and send the current re
|
||||
});
|
||||
test("Full access automatically answers every escalated stage with the published allow-once choice", async () => {
|
||||
const h = await harness("multi-stage-approval");
|
||||
await h.open(undefined, "allowAll");
|
||||
await h.open(undefined, { mode: "allowAll" });
|
||||
await h.prompt();
|
||||
await h.wait((event) => event.type === "session.turn" && event.state === "completed");
|
||||
expect(h.events.filter((event) => event.type === "session.permission")).toEqual([]);
|
||||
@@ -438,8 +441,8 @@ test("interrupt awaits cancelled terminal and reconciles the tool", async () =>
|
||||
),
|
||||
).toBeGreaterThan(terminalIndex);
|
||||
});
|
||||
test("a fresh connection restores earlier messages from persisted session state", async () => {
|
||||
const original = await harness();
|
||||
test("resume restores earlier messages and sends the current system prompt once", async () => {
|
||||
const original = await harness("image-followup");
|
||||
const historyPath = path.join(original.root, "native-history.ndjson");
|
||||
original.launch.env.MUSE_TEST_HISTORY = historyPath;
|
||||
await original.open();
|
||||
@@ -467,10 +470,12 @@ test("a fresh connection restores earlier messages from persisted session state"
|
||||
}),
|
||||
);
|
||||
await original.connection.close();
|
||||
const reopened = await harness("text-reasoning", { MUSE_TEST_HISTORY: historyPath });
|
||||
expect(await reopened.open(JSON.parse(await readFile(persistencePath, "utf8")))).toMatchObject({
|
||||
type: "session.ready",
|
||||
});
|
||||
const reopened = await harness("image-followup", { MUSE_TEST_HISTORY: historyPath });
|
||||
expect(
|
||||
await reopened.open(JSON.parse(await readFile(persistencePath, "utf8")), {
|
||||
systemPrompt: "Updated instructions",
|
||||
}),
|
||||
).toMatchObject({ type: "session.ready" });
|
||||
const restored = reopened.events
|
||||
.filter((event) => event.type === "timeline.item")
|
||||
.map((event) => event.item)
|
||||
@@ -483,6 +488,19 @@ test("a fresh connection restores earlier messages from persisted session state"
|
||||
expect(reopened.events.filter((event) => event.type === "session.turn")).toEqual([]);
|
||||
await reopened.prompt();
|
||||
await reopened.wait((event) => event.type === "session.turn" && event.state === "completed");
|
||||
const from = await reopened.prompt();
|
||||
await reopened.wait(
|
||||
(event) => event.type === "session.turn" && event.state === "completed",
|
||||
from,
|
||||
);
|
||||
const turns = (await reopened.recorded()).filter((frame) => frame.method === "turn/start");
|
||||
expect(turns.map((frame) => frame.params.input)).toEqual([
|
||||
[
|
||||
{ type: "text", text: "<system_instructions>\nUpdated instructions\n</system_instructions>" },
|
||||
{ type: "text", text: "hello" },
|
||||
],
|
||||
[{ type: "text", text: "hello" }],
|
||||
]);
|
||||
});
|
||||
|
||||
for (const cursor of [undefined, "v:old:7"]) {
|
||||
@@ -890,7 +908,7 @@ for (const [configuredModel, catalogModels, expectedModel] of [
|
||||
MUSE_TEST_NULL_MODEL: "1",
|
||||
MUSE_TEST_MODELS: JSON.stringify(catalogModels),
|
||||
});
|
||||
expect(await h.open(undefined, "onRequest", configuredModel || null)).toEqual({
|
||||
expect(await h.open(undefined, { model: configuredModel || null })).toEqual({
|
||||
type: "session.ready",
|
||||
requestId: "open",
|
||||
sessionId: "paseo-session",
|
||||
|
||||
Reference in New Issue
Block a user