fix(web): preserve profile/state on /learn handoff, cancel on startup paste, and split chat learn tests
Some checks failed
Live provider canaries / Live provider canaries (push) Has been cancelled

- Preserve ?profile= when navigating from SkillsPage to /chat and preserve router location.state in ProfileProvider's ?profile= URL sync so delayed/lazy ChatPage mounts keep learnSeed.
- Detect user-initiated terminal input (typing, editing keys, bracketed paste) independently of the mobile line tracker via isUserInitiatedTerminalInput while ignoring terminal-generated replies (CPR, DA, DECRPM, focus, OSC/DCS, mouse).
- Move the self-contained /learn handoff tests out of ChatPage.test.tsx (restoring it to 946 lines) into ChatPage.learn.test.tsx, adding bracketed-paste cancellation and real ProfileProvider delayed-mount coverage.
This commit is contained in:
unsupportedpastels
2026-11-20 03:31:48 +00:00
committed by Mark S.
parent 6add0e500a
commit 32dbc1dcda
9 changed files with 666 additions and 210 deletions

View File

@@ -34,7 +34,7 @@ const router: { navigate?: NavigateFunction } = {};
function Probe() {
const navigate = useNavigate();
const { profile, setProfile } = useProfileScope();
const { pathname, search } = useLocation();
const { pathname, search, state } = useLocation();
useEffect(() => {
router.navigate = navigate;
}, [navigate]);
@@ -42,6 +42,7 @@ function Probe() {
<button
data-profile={profile}
data-url={pathname + search}
data-state={JSON.stringify(state ?? null)}
onClick={() => setProfile("gamma")}
/>
);
@@ -52,6 +53,11 @@ function seen() {
return { profile: probe.dataset.profile, url: probe.dataset.url };
}
function seenState() {
const probe = container.querySelector("button")!;
return JSON.parse(probe.dataset.state ?? "null");
}
async function mount(initialEntry: string) {
container = document.createElement("div");
document.body.append(container);
@@ -91,4 +97,14 @@ describe("ProfileProvider URL sync", () => {
await act(async () => container.querySelector("button")!.click());
expect(seen()).toEqual({ profile: "gamma", url: "/config?profile=gamma" });
});
it("preserves router location state when re-asserting ?profile= after a bare navigation", async () => {
await mount("/skills?profile=alpha");
await act(async () =>
router.navigate!("/chat", { state: { learnSeed: "keep me" } }),
);
expect(seen()).toEqual({ profile: "alpha", url: "/chat?profile=alpha" });
expect(seenState()).toEqual({ learnSeed: "keep me" });
});
});

View File

@@ -40,7 +40,7 @@ import {
*/
export function ProfileProvider({ children }: { children: ReactNode }) {
const [searchParams, setSearchParams] = useSearchParams();
const { pathname } = useLocation();
const { pathname, state: locationState } = useLocation();
const [profiles, setProfiles] = useState<string[]>([]);
const [currentProfile, setCurrentProfile] = useState("default");
const bootstrapProfile = dashboardInitialProfile();
@@ -81,7 +81,7 @@ export function ProfileProvider({ children }: { children: ReactNode }) {
else next.delete("profile");
return next;
},
{ replace: true },
{ replace: true, state: locationState },
);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [pathname, urlProfile, profile]);

View File

@@ -5,6 +5,7 @@ import {
createLearnHandoffController,
formatLearnCommand,
hasLearnSeedState,
isUserInitiatedTerminalInput,
type LearnSocketLike,
normalizeLearnSeed,
readLearnSeedFromState,
@@ -296,3 +297,37 @@ describe("createLearnHandoffController", () => {
}
});
});
describe("isUserInitiatedTerminalInput", () => {
it("recognizes user typing, editing keys, and bracketed paste", () => {
expect(isUserInitiatedTerminalInput("a")).toBe(true);
expect(isUserInitiatedTerminalInput("draft text")).toBe(true);
expect(isUserInitiatedTerminalInput("\r")).toBe(true);
expect(isUserInitiatedTerminalInput("\u007f")).toBe(true);
expect(isUserInitiatedTerminalInput("\u001b[A")).toBe(true);
expect(isUserInitiatedTerminalInput("\u001b[200~pasted draft\u001b[201~")).toBe(
true,
);
expect(
isUserInitiatedTerminalInput("\u001b[200~line 1\rline 2\u001b[201~"),
).toBe(true);
});
it("ignores empty input and terminal-generated replies or focus/mouse events", () => {
expect(isUserInitiatedTerminalInput("")).toBe(false);
expect(isUserInitiatedTerminalInput("\u001b[1;1R")).toBe(false);
expect(isUserInitiatedTerminalInput("\u001b[?1;2c")).toBe(false);
expect(isUserInitiatedTerminalInput("\u001b[>0;276;0c")).toBe(false);
expect(isUserInitiatedTerminalInput("\u001b[?2004;1$y")).toBe(false);
expect(isUserInitiatedTerminalInput("\u001b[I")).toBe(false);
expect(isUserInitiatedTerminalInput("\u001b[O")).toBe(false);
expect(isUserInitiatedTerminalInput("\u001b]11;rgb:0000/0000/0000\u001b\\")).toBe(
false,
);
expect(isUserInitiatedTerminalInput("\u001bP>|xterm.js(6.0.0)\u001b\\")).toBe(
false,
);
expect(isUserInitiatedTerminalInput("\u001b[<0;12;5M")).toBe(false);
expect(isUserInitiatedTerminalInput("\u001b[?1;2c\u001b[1;1R")).toBe(false);
});
});

View File

@@ -41,6 +41,26 @@ const LEARN_SEED_KEY = "learnSeed";
const WS_READY_STATE_OPEN = 1;
const DEFAULT_COMPOSER_READY_DELAY_MS = 800;
// Matches terminal-generated reports/replies and mouse/focus events emitted
// through xterm's onData (CPR/DSR, DA1/DA2/DA3, DECRPM, XTWINOPS, Kitty kbd
// query reply, focus in/out, OSC/DCS replies, SGR/X10 mouse). User typing,
// editing keys, and bracketed paste (\x1b[200~...) never match.
const TERMINAL_REPLY_ONLY_RE =
// eslint-disable-next-line no-control-regex -- intentional terminal-reply detection for PTY input
/^(?:\u001b\[(?:[IO]|<\d+;\d+;\d+[Mm]|M[\s\S]{3}|[?>=][0-9;]*c|\?\d+u|\??[0-9;]+(?:[Rnt]|\$y))|\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)|\u001bP[^\u001b]*\u001b\\)+$/;
/**
* True when an xterm `onData` chunk represents user-initiated input (typing,
* editing keys, or bracketed paste) rather than terminal-generated replies or
* mouse/focus reports.
*/
export function isUserInitiatedTerminalInput(data: string): boolean {
if (!data) {
return false;
}
return !TERMINAL_REPLY_ONLY_RE.test(data);
}
function isPlainRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}

View File

@@ -0,0 +1,532 @@
// @vitest-environment jsdom
import { act, useEffect, useState, type ReactNode } from "react";
import { createRoot, type Root } from "react-dom/client";
import { MemoryRouter, useLocation, useNavigate } from "react-router";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const { FakeFitAddon, FakeTerminal, FakeWebglAddon } = vi.hoisted(() => {
class HoistedFitAddon {
fit() {}
}
class HoistedWebglAddon {
onContextLoss() {
return { dispose() {} };
}
dispose() {}
}
class HoistedTerminal {
static latestDataHandler: ((data: string) => void) | null = null;
options: Record<string, unknown>;
rows = 24;
cols = 80;
parser = { registerOscHandler: vi.fn() };
unicode = { activeVersion: "" };
constructor(options: Record<string, unknown>) {
this.options = options;
}
attachCustomKeyEventHandler() {
return true;
}
attachCustomWheelEventHandler() {
return true;
}
clearSelection() {}
clearTextureAtlas() {}
dispose() {}
focus() {}
getSelection() {
return "";
}
loadAddon() {}
onData(handler: (data: string) => void) {
HoistedTerminal.latestDataHandler = handler;
return {
dispose() {
if (HoistedTerminal.latestDataHandler === handler) {
HoistedTerminal.latestDataHandler = null;
}
},
};
}
onResize() {
return { dispose() {} };
}
onScroll() {
return { dispose() {} };
}
get buffer() {
return { active: { baseY: 0, viewportY: 0 } };
}
scrollToBottom() {}
open() {}
paste() {}
refresh() {}
write() {}
}
return {
FakeFitAddon: HoistedFitAddon,
FakeTerminal: HoistedTerminal,
FakeWebglAddon: HoistedWebglAddon,
};
});
const apiMocks = vi.hoisted(() => ({
buildWsUrl: vi.fn(async () => "ws://localhost/api/pty?channel=chat-1"),
getProfiles: vi.fn(() => new Promise(() => {})),
getActiveProfile: vi.fn(() => new Promise(() => {})),
}));
vi.mock("@xterm/addon-fit", () => ({ FitAddon: FakeFitAddon }));
vi.mock("@xterm/addon-unicode11", () => ({ Unicode11Addon: class {} }));
vi.mock("@xterm/addon-web-links", () => ({ WebLinksAddon: class {} }));
vi.mock("@xterm/addon-webgl", () => ({ WebglAddon: FakeWebglAddon }));
vi.mock("@xterm/xterm", () => ({ Terminal: FakeTerminal }));
vi.mock("@/components/ChatSidebar", () => ({ ChatSidebar: () => null }));
vi.mock("@/components/ChatSessionList", () => ({ ChatSessionList: () => null }));
vi.mock("@/components/Backdrop", () => ({ Backdrop: () => null }));
vi.mock("@/plugins", () => ({ PluginSlot: () => null }));
vi.mock("@/contexts/usePageHeader", () => ({
usePageHeader: () => ({ setEnd: vi.fn(), setTitle: vi.fn() }),
}));
vi.mock("@/themes", () => ({
useTheme: () => ({ theme: { terminalBackground: "#000000" } }),
}));
vi.mock("@/i18n", () => ({
useI18n: () => ({
t: {
app: {
closeModelTools: "Close model tools",
modelToolsSheetSubtitle: "Tools",
modelToolsSheetTitle: "Model",
},
},
}),
}));
vi.mock("@/lib/dashboard-auth-reload", () => ({
maybeReloadForLoopbackWsAuthFailure: vi.fn(() => false),
}));
vi.mock("@/lib/api", () => ({
api: apiMocks,
buildWsUrl: apiMocks.buildWsUrl,
setManagementProfile: vi.fn(),
}));
import { ProfileProvider } from "@/contexts/ProfileProvider";
import ChatPage from "./ChatPage";
type CloseEventLike = { code: number; reason: string; wasClean: boolean };
class FakeWebSocket {
static instances: FakeWebSocket[] = [];
static OPEN = 1;
binaryType = "blob";
onclose: ((event: CloseEventLike) => void) | null = null;
onmessage: ((event: { data: ArrayBuffer | string }) => void) | null = null;
onopen: (() => void) | null = null;
readyState = FakeWebSocket.OPEN;
url: string;
send = vi.fn();
constructor(url: string) {
this.url = url;
FakeWebSocket.instances.push(this);
}
close() {
this.readyState = 3;
}
}
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT =
true;
let container: HTMLDivElement;
let root: Root;
async function render(ui: ReactNode) {
container = document.createElement("div");
document.body.append(container);
root = createRoot(container);
await act(async () => root.render(ui));
}
beforeEach(() => {
FakeWebSocket.instances = [];
FakeTerminal.latestDataHandler = null;
apiMocks.buildWsUrl.mockReset();
apiMocks.buildWsUrl.mockResolvedValue("ws://localhost/api/pty?channel=chat-1");
vi.stubGlobal("WebSocket", FakeWebSocket);
vi.stubGlobal(
"ResizeObserver",
class {
disconnect() {}
observe() {}
unobserve() {}
},
);
vi.stubGlobal("requestAnimationFrame", (cb: FrameRequestCallback) => {
cb(0);
return 1;
});
vi.stubGlobal("cancelAnimationFrame", () => {});
vi.stubGlobal("matchMedia", () => ({
addEventListener() {},
matches: false,
media: "",
removeEventListener() {},
}));
vi.stubGlobal("crypto", {
getRandomValues: (values: Uint8Array) => {
values.fill(7);
return values;
},
randomUUID: () => "chat-learn-test-id",
});
Object.defineProperty(window, "visualViewport", {
configurable: true,
value: {
addEventListener() {},
height: 800,
offsetTop: 0,
removeEventListener() {},
},
});
Object.defineProperty(window, "__HERMES_SESSION_TOKEN__", {
configurable: true,
value: "test-token",
writable: true,
});
Object.defineProperty(window, "__HERMES_AUTH_REQUIRED__", {
configurable: true,
value: false,
writable: true,
});
Object.defineProperty(window.navigator, "clipboard", {
configurable: true,
value: {
readText: vi.fn(async () => ""),
writeText: vi.fn(async () => {}),
},
});
sessionStorage.clear();
const store: Record<string, string> = {};
vi.stubGlobal("localStorage", {
getItem: (k: string) => store[k] ?? null,
setItem: (k: string, v: string) => {
store[k] = String(v);
},
removeItem: (k: string) => {
delete store[k];
},
clear: () => {
for (const k of Object.keys(store)) delete store[k];
},
});
});
afterEach(async () => {
await act(async () => root?.unmount());
container?.remove();
vi.unstubAllGlobals();
});
describe("ChatPage /learn router-state handoff", () => {
it("ignores ?learn= URL query parameters and never submits them to the PTY", async () => {
vi.useFakeTimers();
try {
await render(
<MemoryRouter initialEntries={["/chat?learn=%15!id%0d&other=1"]}>
<ProfileProvider>
<ChatPage />
</ProfileProvider>
</MemoryRouter>,
);
await vi.waitFor(() => expect(FakeWebSocket.instances).toHaveLength(1));
const socket = FakeWebSocket.instances[0];
await act(async () => socket.onopen?.());
await act(async () => {
await vi.advanceTimersByTimeAsync(1500);
});
const sent = socket.send.mock.calls.map(([payload]) => String(payload));
expect(sent.filter((msg) => msg.includes("/learn"))).toEqual([]);
expect(sent.filter((msg) => msg.includes("!id"))).toEqual([]);
} finally {
vi.useRealTimers();
}
});
it("delivers normalized router-state handoff once on cold start and strips learnSeed", async () => {
vi.useFakeTimers();
try {
let latestLocation: { pathname: string; search: string; state: unknown } | null = null;
function LocationSpy() {
const loc = useLocation();
latestLocation = { pathname: loc.pathname, search: loc.search, state: loc.state };
return null;
}
await render(
<MemoryRouter
initialEntries={[
{
pathname: "/chat",
state: {
learnSeed: "docs \u001b]52;c;YWJj\u0007\u0015\u001b7guide\u001b8",
from: "/skills",
},
},
]}
>
<ProfileProvider>
<LocationSpy />
<ChatPage />
</ProfileProvider>
</MemoryRouter>,
);
expect(latestLocation).toEqual({
pathname: "/chat",
search: "",
state: { from: "/skills" },
});
await vi.waitFor(() => expect(FakeWebSocket.instances).toHaveLength(1));
const socket = FakeWebSocket.instances[0];
await act(async () => socket.onopen?.());
// Terminal-generated startup replies must not cancel the pending handoff.
await act(async () => {
FakeTerminal.latestDataHandler?.("\u001b[1;1R");
FakeTerminal.latestDataHandler?.("\u001b[?1;2c");
FakeTerminal.latestDataHandler?.("\u001b[?2004;1$y");
FakeTerminal.latestDataHandler?.("\u001b[I");
});
await act(async () => {
await vi.advanceTimersByTimeAsync(799);
});
expect(socket.send).not.toHaveBeenCalledWith(expect.stringContaining("/learn"));
await act(async () => {
await vi.advanceTimersByTimeAsync(1);
});
expect(socket.send).toHaveBeenCalledWith("/learn docs guide\r");
expect(
socket.send.mock.calls.filter(([payload]) => String(payload).startsWith("/learn")),
).toHaveLength(1);
} finally {
vi.useRealTimers();
}
});
it("cancels a pending cold-start handoff when the user pastes a draft via bracketed paste", async () => {
vi.useFakeTimers();
try {
await render(
<MemoryRouter
initialEntries={[
{
pathname: "/chat",
state: { learnSeed: "startup skill" },
},
]}
>
<ProfileProvider>
<ChatPage />
</ProfileProvider>
</MemoryRouter>,
);
await vi.waitFor(() => expect(FakeWebSocket.instances).toHaveLength(1));
const socket = FakeWebSocket.instances[0];
await act(async () => socket.onopen?.());
await act(async () => {
await vi.advanceTimersByTimeAsync(300);
FakeTerminal.latestDataHandler?.("\u001b[200~pasted draft\u001b[201~");
});
expect(socket.send).toHaveBeenCalledWith("\u001b[200~pasted draft\u001b[201~");
socket.send.mockClear();
await act(async () => {
await vi.advanceTimersByTimeAsync(1000);
});
expect(socket.send).not.toHaveBeenCalled();
} finally {
vi.useRealTimers();
}
});
it("retains an unsent handoff across a transient early close/reconnect and never replays after delivery", async () => {
vi.useFakeTimers();
try {
await render(
<MemoryRouter
initialEntries={[
{
pathname: "/chat",
state: { learnSeed: "retry workflow" },
},
]}
>
<ProfileProvider>
<ChatPage />
</ProfileProvider>
</MemoryRouter>,
);
await vi.waitFor(() => expect(FakeWebSocket.instances).toHaveLength(1));
const first = FakeWebSocket.instances[0];
await act(async () => first.onopen?.());
await act(async () => {
await vi.advanceTimersByTimeAsync(300);
});
expect(first.send).not.toHaveBeenCalledWith(expect.stringContaining("/learn"));
await act(async () => {
first.readyState = 3;
first.onclose?.({ code: 1006, reason: "", wasClean: false });
});
await act(async () => {
await vi.advanceTimersByTimeAsync(2000);
});
await vi.waitFor(() => expect(FakeWebSocket.instances).toHaveLength(2));
const second = FakeWebSocket.instances[1];
await act(async () => second.onopen?.());
await act(async () => {
await vi.advanceTimersByTimeAsync(800);
});
expect(first.send).not.toHaveBeenCalledWith(expect.stringContaining("/learn"));
expect(second.send).toHaveBeenCalledWith("/learn retry workflow\r");
await act(async () => {
second.readyState = 3;
second.onclose?.({ code: 1006, reason: "", wasClean: false });
});
await act(async () => {
await vi.advanceTimersByTimeAsync(2000);
});
await vi.waitFor(() => expect(FakeWebSocket.instances).toHaveLength(3));
const third = FakeWebSocket.instances[2];
await act(async () => third.onopen?.());
await act(async () => {
await vi.advanceTimersByTimeAsync(800);
});
expect(third.send).not.toHaveBeenCalledWith(expect.stringContaining("/learn"));
} finally {
vi.useRealTimers();
}
});
it("leaves a pre-existing draft untouched and never submits on warm return to an open PTY", async () => {
vi.useFakeTimers();
try {
let pushLearnReturn: (() => void) | null = null;
function NavDriver() {
const navigate = useNavigate();
pushLearnReturn = () =>
navigate("/chat", { state: { learnSeed: "warm skill handoff" } });
return null;
}
await render(
<MemoryRouter initialEntries={["/chat"]}>
<ProfileProvider>
<NavDriver />
<ChatPage />
</ProfileProvider>
</MemoryRouter>,
);
await vi.waitFor(() => expect(FakeWebSocket.instances).toHaveLength(1));
const socket = FakeWebSocket.instances[0];
await act(async () => socket.onopen?.());
await act(async () => {
await vi.advanceTimersByTimeAsync(800);
});
await act(async () => {
FakeTerminal.latestDataHandler?.("unfinished draft");
});
expect(socket.send).toHaveBeenCalledWith("unfinished draft");
socket.send.mockClear();
await act(async () => {
pushLearnReturn?.();
});
await act(async () => {
await vi.advanceTimersByTimeAsync(1500);
});
expect(socket.send).not.toHaveBeenCalled();
} finally {
vi.useRealTimers();
}
});
it("preserves learnSeed across real ProfileProvider ?profile= sync and delayed ChatPage mount", async () => {
vi.useFakeTimers();
try {
let navigateToChat: (() => void) | null = null;
let releaseLazyMount: (() => void) | null = null;
// Mirrors App.tsx: chat host latches on /chat activation and ChatPage
// finishes mounting asynchronously (lazy chunk load) after ProfileProvider's
// ?profile= URL sync effect has already run.
function DelayedChatHost() {
const location = useLocation();
const navigate = useNavigate();
const isChat = location.pathname === "/chat";
const [latched, setLatched] = useState(isChat);
const [lazyLoaded, setLazyLoaded] = useState(false);
useEffect(() => {
navigateToChat = () =>
navigate("/chat", { state: { learnSeed: "profile preserved skill" } });
releaseLazyMount = () => setLazyLoaded(true);
}, [navigate]);
useEffect(() => {
if (isChat) setLatched(true);
}, [isChat]);
return latched && lazyLoaded ? <ChatPage isActive={isChat} /> : null;
}
await render(
<MemoryRouter initialEntries={["/skills?profile=work"]}>
<ProfileProvider>
<DelayedChatHost />
</ProfileProvider>
</MemoryRouter>,
);
// Navigate bare to /chat with state; ProfileProvider syncs ?profile=work
// before ChatPage mounts.
await act(async () => {
navigateToChat?.();
});
await act(async () => {
releaseLazyMount?.();
});
await vi.waitFor(() => expect(FakeWebSocket.instances).toHaveLength(1));
const socket = FakeWebSocket.instances[0];
await act(async () => socket.onopen?.());
await act(async () => {
await vi.advanceTimersByTimeAsync(800);
});
expect(socket.send).toHaveBeenCalledWith("/learn profile preserved skill\r");
} finally {
vi.useRealTimers();
}
});
});

View File

@@ -1,7 +1,7 @@
// @vitest-environment jsdom
import { act, type ReactNode } from "react";
import { createRoot, type Root } from "react-dom/client";
import { MemoryRouter, useLocation, useNavigate } from "react-router";
import { MemoryRouter } from "react-router";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
@@ -30,7 +30,6 @@ class FakeWebglAddon {
}
class FakeTerminal {
static latestDataHandler: ((data: string) => void) | null = null;
options: Record<string, unknown>;
rows = 24;
cols = 80;
@@ -65,15 +64,8 @@ class FakeTerminal {
loadAddon() {}
onData(handler: (data: string) => void) {
FakeTerminal.latestDataHandler = handler;
return {
dispose() {
if (FakeTerminal.latestDataHandler === handler) {
FakeTerminal.latestDataHandler = null;
}
},
};
onData() {
return { dispose() {} };
}
onResize() {
@@ -222,7 +214,6 @@ async function render(ui: ReactNode) {
beforeEach(() => {
FakeWebSocket.instances = [];
FakeTerminal.latestDataHandler = null;
webglInstances.length = 0;
maybeReloadForLoopbackWsAuthFailure.mockClear();
apiMocks.buildWsUrl.mockReset();
@@ -953,193 +944,3 @@ describe("ChatPage WebGL renderer gating", () => {
expect(webglInstances[0].disposed).toBe(true);
});
});
describe("ChatPage /learn router-state handoff", () => {
it("ignores ?learn= URL query parameters and never submits them to the PTY", async () => {
vi.useFakeTimers();
try {
const { default: ChatPage } = await import("./ChatPage");
await render(
<MemoryRouter initialEntries={["/chat?learn=%15!id%0d&other=1"]}>
<ChatPage />
</MemoryRouter>,
);
await vi.waitFor(() => expect(FakeWebSocket.instances).toHaveLength(1));
const socket = FakeWebSocket.instances[0];
await act(async () => socket.onopen?.());
await act(async () => {
await vi.advanceTimersByTimeAsync(1500);
});
const sent = socket.send.mock.calls.map(([payload]) => String(payload));
expect(sent.filter((msg) => msg.includes("/learn"))).toEqual([]);
expect(sent.filter((msg) => msg.includes("!id"))).toEqual([]);
} finally {
vi.useRealTimers();
}
});
it("delivers normalized router-state handoff once on cold start and strips learnSeed", async () => {
vi.useFakeTimers();
try {
const { default: ChatPage } = await import("./ChatPage");
let latestLocation: { pathname: string; search: string; state: unknown } | null = null;
function LocationSpy() {
const loc = useLocation();
latestLocation = { pathname: loc.pathname, search: loc.search, state: loc.state };
return null;
}
await render(
<MemoryRouter
initialEntries={[
{
pathname: "/chat",
state: {
learnSeed: "docs \u001b]52;c;YWJj\u0007\u0015\u001b7guide\u001b8",
from: "/skills",
},
},
]}
>
<LocationSpy />
<ChatPage />
</MemoryRouter>,
);
expect(latestLocation).toEqual({
pathname: "/chat",
search: "",
state: { from: "/skills" },
});
await vi.waitFor(() => expect(FakeWebSocket.instances).toHaveLength(1));
const socket = FakeWebSocket.instances[0];
await act(async () => socket.onopen?.());
await act(async () => {
await vi.advanceTimersByTimeAsync(799);
});
expect(socket.send).not.toHaveBeenCalledWith(expect.stringContaining("/learn"));
await act(async () => {
await vi.advanceTimersByTimeAsync(1);
});
expect(socket.send).toHaveBeenCalledWith("/learn docs guide\r");
expect(
socket.send.mock.calls.filter(([payload]) => String(payload).startsWith("/learn")),
).toHaveLength(1);
} finally {
vi.useRealTimers();
}
});
it("retains an unsent handoff across a transient early close/reconnect and never replays after delivery", async () => {
vi.useFakeTimers();
try {
const { default: ChatPage } = await import("./ChatPage");
await render(
<MemoryRouter
initialEntries={[
{
pathname: "/chat",
state: { learnSeed: "retry workflow" },
},
]}
>
<ChatPage />
</MemoryRouter>,
);
await vi.waitFor(() => expect(FakeWebSocket.instances).toHaveLength(1));
const first = FakeWebSocket.instances[0];
await act(async () => first.onopen?.());
await act(async () => {
await vi.advanceTimersByTimeAsync(300);
});
expect(first.send).not.toHaveBeenCalledWith(expect.stringContaining("/learn"));
// Transient unclean drop before the 800ms composer delay elapses.
await act(async () => {
first.readyState = 3;
first.onclose?.({ code: 1006, reason: "", wasClean: false });
});
await act(async () => {
await vi.advanceTimersByTimeAsync(2000);
});
await vi.waitFor(() => expect(FakeWebSocket.instances).toHaveLength(2));
const second = FakeWebSocket.instances[1];
await act(async () => second.onopen?.());
await act(async () => {
await vi.advanceTimersByTimeAsync(800);
});
expect(first.send).not.toHaveBeenCalledWith(expect.stringContaining("/learn"));
expect(second.send).toHaveBeenCalledWith("/learn retry workflow\r");
// A subsequent reconnect after delivery must not replay the command.
await act(async () => {
second.readyState = 3;
second.onclose?.({ code: 1006, reason: "", wasClean: false });
});
await act(async () => {
await vi.advanceTimersByTimeAsync(2000);
});
await vi.waitFor(() => expect(FakeWebSocket.instances).toHaveLength(3));
const third = FakeWebSocket.instances[2];
await act(async () => third.onopen?.());
await act(async () => {
await vi.advanceTimersByTimeAsync(800);
});
expect(third.send).not.toHaveBeenCalledWith(expect.stringContaining("/learn"));
} finally {
vi.useRealTimers();
}
});
it("leaves a pre-existing draft untouched and never submits on warm return to an open PTY", async () => {
vi.useFakeTimers();
try {
const { default: ChatPage } = await import("./ChatPage");
let pushLearnReturn: (() => void) | null = null;
function NavDriver() {
const navigate = useNavigate();
pushLearnReturn = () =>
navigate("/chat", { state: { learnSeed: "warm skill handoff" } });
return null;
}
await render(
<MemoryRouter initialEntries={["/chat"]}>
<NavDriver />
<ChatPage />
</MemoryRouter>,
);
await vi.waitFor(() => expect(FakeWebSocket.instances).toHaveLength(1));
const socket = FakeWebSocket.instances[0];
await act(async () => socket.onopen?.());
await act(async () => {
await vi.advanceTimersByTimeAsync(800);
});
// User starts typing a draft in the live composer.
await act(async () => {
FakeTerminal.latestDataHandler?.("unfinished draft");
});
expect(socket.send).toHaveBeenCalledWith("unfinished draft");
socket.send.mockClear();
// Returning from /skills with router state must not inject into or submit the draft.
await act(async () => {
pushLearnReturn?.();
});
await act(async () => {
await vi.advanceTimersByTimeAsync(1500);
});
expect(socket.send).not.toHaveBeenCalled();
} finally {
vi.useRealTimers();
}
});
});

View File

@@ -99,6 +99,7 @@ import {
} from "@/lib/terminal-font-refit";
import { generateChannelId } from "@/lib/chat-channel-id";
import { sendCopyLastCommand } from "@/lib/chat-copy-last";
import { isUserInitiatedTerminalInput } from "@/lib/learn-handoff";
import { useLearnHandoff } from "@/lib/use-learn-handoff";
import { CopyLastButton } from "@/lib/chat-copy-last-button";
import {
@@ -1491,7 +1492,7 @@ export default function ChatPage({ isActive = true }: { isActive?: boolean }) {
useMobileReplacement && Date.now() <= mobileReplacementInputUntilRef.current,
);
ptyInputLineRef.current = normalized.nextLine;
if (ptyInputLineRef.current) learnHandoff.onUserInput();
if (isUserInitiatedTerminalInput(normalized.data)) learnHandoff.onUserInput();
if (normalized.normalized) {
mobileReplacementInputUntilRef.current = 0;
}

View File

@@ -11,14 +11,19 @@ const apiMocks = vi.hoisted(() => ({
getSkillsHubTaps: vi.fn(async () => ({ taps: [] })),
}));
const profileScopeState = vi.hoisted(() => ({
selectedProfile: "",
}));
vi.mock("@/lib/api", () => ({
api: apiMocks,
}));
vi.mock("@/contexts/useProfileScope", () => ({
useProfileScope: () => ({
selectedProfile: "default",
activeProfile: "default",
profile: profileScopeState.selectedProfile,
currentProfile: "default",
profiles: [],
setProfile: vi.fn(),
}),
}));
vi.mock("@/contexts/usePageHeader", () => ({
@@ -57,6 +62,7 @@ let root: Root;
beforeEach(() => {
vi.clearAllMocks();
profileScopeState.selectedProfile = "";
container = document.createElement("div");
document.body.append(container);
root = createRoot(container);
@@ -132,4 +138,46 @@ describe("SkillsPage Learn a skill handoff", () => {
state: { learnSeed: "workflow notes second line" },
});
});
it("preserves ?profile= on /chat navigation when a non-empty profile is selected", async () => {
profileScopeState.selectedProfile = "work";
let chatLocation: { pathname: string; search: string; state: unknown } | null = null;
function ChatSpy() {
const loc = useLocation();
chatLocation = { pathname: loc.pathname, search: loc.search, state: loc.state };
return <div data-testid="chat-spy" />;
}
await act(async () => {
root.render(
<I18nProvider>
<MemoryRouter initialEntries={["/skills?profile=work"]}>
<Routes>
<Route path="/skills" element={<SkillsPage />} />
<Route path="/chat" element={<ChatSpy />} />
</Routes>
</MemoryRouter>
</I18nProvider>,
);
});
const openBtn = Array.from(container.querySelectorAll("button")).find((btn) =>
btn.textContent?.includes("Learn a skill"),
);
await act(async () => openBtn!.click());
const textarea = container.querySelector("textarea")!;
await act(async () => setNativeValue(textarea, "profile scoped skill"));
const submitBtn = Array.from(container.querySelectorAll("button")).find((btn) =>
btn.textContent?.includes("Learn it"),
);
await act(async () => submitBtn!.click());
expect(chatLocation).toEqual({
pathname: "/chat",
search: "?profile=work",
state: { learnSeed: "profile scoped skill" },
});
});
});

View File

@@ -251,8 +251,11 @@ export default function SkillsPage() {
const learnState = buildLearnNavigationState(segs.join("; "));
if (!learnState) return;
setLearnOpen(false);
navigate("/chat", { state: learnState });
}, [learnDir, learnUrl, learnText, navigate]);
const target = selectedProfile
? `/chat?profile=${encodeURIComponent(selectedProfile)}`
: "/chat";
navigate(target, { state: learnState });
}, [learnDir, learnUrl, learnText, navigate, selectedProfile]);
const openEditEditor = useCallback((skillName: string) => {
setEditorSkill(skillName);
setEditorOpen(true);