web: create a chat through the directory picker (C2)

This commit is contained in:
2026-10-19 14:25:42 +01:00
parent 2fe63012f9
commit a7872c3f31
9 changed files with 841 additions and 36 deletions
+129
View File
@@ -12,6 +12,13 @@ import {
CHAT_COMMAND_FAILED_LABEL,
CHAT_COMMAND_GLYPH,
CHAT_COMMAND_LABEL,
CHAT_CREATE_BACK_LABEL,
CHAT_CREATE_CANCEL,
CHAT_CREATE_CONFIRM,
CHAT_CREATE_LOADING,
CHAT_CREATE_MODEL_NOTE,
CHAT_CREATE_PROMPT,
CHAT_CREATE_TITLE,
CHAT_FOLLOW_THRESHOLD_PX,
CHAT_QUEUED_NOTICE,
COMPOSER_SEND,
@@ -60,12 +67,16 @@ import {
attachmentDisplayName,
attachmentError,
attachmentFiles,
HOME_DIRECTORY,
HOME_LABEL,
backgroundTasksRunningLabel,
chatBottomDistancePx,
chatCommandEffect,
chatCommandForEnter,
chatCommandHelp,
chatCommandSuggestions,
chatCreateFailed,
chatCreateSucceeded,
chatFirstScroll,
chatFollowsAt,
chatHeaderMeta,
@@ -73,6 +84,7 @@ import {
chatNoticeLabel,
chatOpensAtNewest,
chatShowJumpToLatest,
chatStartInLabel,
chatStreamState,
closeChatConfirmation,
composerAction,
@@ -80,7 +92,9 @@ import {
composerSendEnabled,
composerSubmit,
decisionLabel,
defaultDirectoryChoice,
deltaPartId,
directoryChoices,
directoryLabel,
dismissChatNotice,
filterSessions,
@@ -92,6 +106,7 @@ import {
mergeHistoryPage,
mergeShellFrame,
mergeToolPart,
newChatCreateState,
newChatThread,
parseChatInput,
partRendering,
@@ -104,6 +119,7 @@ import {
runningBackgroundShells,
runningToolElapsedMillis,
runningToolStamps,
selectChatDirectory,
sessionActivity,
sessionActivityBadge,
sessionChipLabel,
@@ -1612,3 +1628,116 @@ test("a step that ends does not clear a background shell that outlives the turn"
assert.equal(resumed.selectedShellId, null);
assert.equal(resumed.shellOutput, null);
});
// ---- The create flow's directory picker (C2, ChatDirectories.kt) -----------
test("directoryChoices makes the first non-blank directory home and keeps recents in server order", () => {
const choices = directoryChoices(["/Users/alan", "", "/work/one", " ", "/work/two"]);
assert.deepEqual(choices, [
{
label: "Home (~)",
path: "/Users/alan",
home: true,
createDirectory: "~",
secondary: "/Users/alan",
},
{
label: "/work/one",
path: "/work/one",
home: false,
createDirectory: "/work/one",
secondary: null,
},
{
label: "/work/two",
path: "/work/two",
home: false,
createDirectory: "/work/two",
secondary: null,
},
]);
});
test("directoryChoices always yields home first, even for an empty or blank reply", () => {
for (const reply of [[], ["", " "], null, undefined]) {
const choices = directoryChoices(reply);
assert.equal(choices.length, 1);
assert.deepEqual(choices[0], {
label: HOME_LABEL,
path: HOME_DIRECTORY,
home: true,
createDirectory: HOME_DIRECTORY,
secondary: HOME_DIRECTORY,
});
}
});
test("the home row is the only one with a secondary path; recents are labelled by full path", () => {
const choices = directoryChoices(["/home/operator", "/repo/a", "/repo/b"]);
assert.deepEqual(
choices.map((choice) => [choice.label, choice.secondary]),
[
["Home (~)", "/home/operator"],
["/repo/a", null],
["/repo/b", null],
],
);
assert.equal(defaultDirectoryChoice(choices)?.label, HOME_LABEL);
assert.equal(defaultDirectoryChoice([]), null);
});
test("newChatCreateState starts on home, not sending, with the caller's operation id", () => {
assert.deepEqual(newChatCreateState("web-chat-op"), {
directory: HOME_DIRECTORY,
operationId: "web-chat-op",
creating: false,
error: "",
});
});
test("selectChatDirectory sends the chosen value and clears a previous refusal", () => {
const state = { ...newChatCreateState("op"), error: "refused" };
const recent = { label: "/repo/a", path: "/repo/a", home: false, createDirectory: "/repo/a", secondary: null };
assert.deepEqual(selectChatDirectory(state, recent), {
directory: "/repo/a",
operationId: "op",
creating: false,
error: "",
});
assert.equal(selectChatDirectory(state, "~").directory, "~");
assert.deepEqual(selectChatDirectory(state, ""), state);
});
test("chatCreateFailed keeps the pane open with the server's message; success stops sending", () => {
const creating = { ...newChatCreateState("op"), creating: true };
assert.deepEqual(chatCreateFailed(creating, "the directory is not available"), {
directory: "~",
operationId: "op",
creating: false,
error: "the directory is not available",
});
});
test("chatCreateSucceeded puts the created session at the head and dedupes by id", () => {
const a = { id: "a", title: "A" };
const b = { id: "b", title: "B" };
const created = { id: "b", title: "New chat" };
assert.deepEqual(chatCreateSucceeded([a, b], created), [created, a]);
assert.deepEqual(chatCreateSucceeded([], created), [created]);
assert.deepEqual(chatCreateSucceeded([a], null), [a]);
});
test("the create flow's wording is the app's verbatim", () => {
assert.equal(CHAT_CREATE_TITLE, "Start a chat");
assert.equal(CHAT_CREATE_BACK_LABEL, "Cancel new chat");
assert.equal(CHAT_CREATE_LOADING, "Loading directories…");
assert.equal(CHAT_CREATE_PROMPT, "Where should this chat live?");
assert.equal(
CHAT_CREATE_MODEL_NOTE,
"This server has no request for choosing a chat's model, so a new chat uses the server's default.",
);
assert.equal(CHAT_CREATE_CONFIRM, "New chat");
assert.equal(CHAT_CREATE_CANCEL, "Cancel");
assert.equal(chatStartInLabel(HOME_DIRECTORY), "Start in ~");
assert.equal(chatStartInLabel("/repo/a"), "Start in /repo/a");
});
+35
View File
@@ -345,6 +345,41 @@ test("chatInterrupt sends the session as chat_query (not a chat_interrupt body)"
assert.deepEqual(lastFrame(ws), { type: "chat_interrupt", chat_query: { session_id: "s1" } });
});
test("chatDirectories sends exactly {type:'chat_directories'} and returns the list", async () => {
const { repo, ws } = connected();
const directories = ["/home/operator", "/repo/one", "/repo/two"];
ws.reply = (frame) => ({ id: frame.id, type: "chat_directories", chat_directories: directories });
assert.deepEqual(await repo.chatDirectories(), directories);
assert.deepEqual(lastFrame(ws), { type: "chat_directories" });
});
test("chatDirectories returns [] when the reply carries no directories", async () => {
const { repo, ws } = connected();
ws.reply = (frame) => ({ id: frame.id, type: "chat_directories" });
assert.deepEqual(await repo.chatDirectories(), []);
});
test("chatDirectories surfaces a server refusal as a ProtocolError", async () => {
const { repo, ws } = connected();
ws.reply = (frame) => ({ id: frame.id, type: "error", error: "unknown command: chat_directories" });
await assert.rejects(() => repo.chatDirectories(), {
name: "ProtocolError",
message: "unknown command: chat_directories",
});
});
test("chatCreate sends home as ~ and carries the exact title/directory/operation_id body", async () => {
const { repo, ws } = connected();
ws.reply = (frame) => ({ id: frame.id, type: "chat_create", chat_session: { id: "ses_new" } });
await repo.chatCreate("New chat", "~", "op-4");
assert.deepEqual(lastFrame(ws), {
type: "chat_create",
chat_create: { title: "New chat", directory: "~", operation_id: "op-4" },
});
});
test("chatCreate sends title/directory/operation_id and returns chat_session", async () => {
const { repo, ws } = connected();
const created = { id: "ses_new", title: "New chat" };
+238 -13
View File
@@ -75,6 +75,9 @@ let failed = false;
// The throwaway chat session this run creates for the running-turn capture. It
// is closed again in cleanup; null once closed (or when none was created).
let throwawaySessionId = null;
// C2's one real session. It is closed in its own step; kept here only so a
// failure before that step can still close it rather than leave it in the list.
let createdSessionId = null;
function step(label) {
console.log(`• ${label}`);
@@ -443,6 +446,13 @@ try {
frame.chat_prompt?.text ?? "",
);
}
// C2: the create bodies this page actually sent, so the smoke can prove
// the picker's chosen value reached chat_create.
if (frame.type === "chat_create") {
(window.__chatCreateBodies = window.__chatCreateBodies || []).push(
frame.chat_create ?? null,
);
}
if (frame.type === "chat_reply") {
const requestId = frame.chat_reply && frame.chat_reply.request_id;
if (window.__suppressChatReplyIds.includes(requestId)) {
@@ -1484,11 +1494,18 @@ try {
};
})()`),
{ timeout: 15000, what: "the live run's active stage" },
);
if (!live.badge) throw new Error(`the active stage showed no elapsed badge: ${JSON.stringify(live)}`);
console.log(` live run ${liveRunId}: active stage ${live.activeKey} (pulsing=${live.pulsing}), badge ${live.badge}`);
await page.rect(".run-detail .graph-viewport");
shots.push(await page.screenshot(`${out}/31-run-live-graph.png`));
).catch(() => null);
// The row was running when it was picked but may have stopped while its
// detail loaded; this capture is documented as best effort, so say so rather
// than fail an unrelated step on live-data timing.
if (!live) {
console.log(` -- run ${liveRunId} stopped before its active stage rendered; skipped the live halo capture`);
} else {
if (!live.badge) throw new Error(`the active stage showed no elapsed badge: ${JSON.stringify(live)}`);
console.log(` live run ${liveRunId}: active stage ${live.activeKey} (pulsing=${live.pulsing}), badge ${live.badge}`);
await page.rect(".run-detail .graph-viewport");
shots.push(await page.screenshot(`${out}/31-run-live-graph.png`));
}
}
// The Output empty state, on the running run that has not produced output yet.
@@ -2383,6 +2400,10 @@ try {
await page.clickText("nav.tabs button.tab", "Chat");
await page.waitForSelector("#chatRows .chat-row", { timeout: 25000 });
// The operator's own session is the one this step reads; the list may lead with
// another run's closed row (C2 closes its create, and history sits by recency),
// so pick the operator row rather than assuming the first.
const expectedSession = "ses_eae413f50ffeLQDExlg8cYnscN";
const chatList = await page.evaluate(`(() => ({
label: document.querySelector("#chatSearch")?.getAttribute("aria-label") ?? "",
placeholder: document.querySelector("#chatSearch")?.getAttribute("placeholder") ?? "",
@@ -2392,26 +2413,31 @@ try {
chips: [...row.querySelectorAll(".chip")].map((chip) => chip.textContent),
meta: row.querySelector(".chat-row-meta")?.textContent ?? "",
close: !!row.querySelector(".chat-close"),
closed: !!row.querySelector(".chat-closed-chip"),
})),
}))()`);
if (chatList.label !== "Search chats") throw new Error(`chat search label: ${chatList.label}`);
if (chatList.placeholder !== "Search chats") throw new Error(`chat search placeholder: ${chatList.placeholder}`);
if (chatList.rows.length === 0) throw new Error("no chat sessions rendered");
if (!chatList.rows[0].title) throw new Error("the first chat row has no title");
if (!chatList.rows[0].chips.includes("Operator")) {
throw new Error(`chat kind chip: ${chatList.rows[0].chips.join(", ")}`);
const operatorRow =
chatList.rows.find((row) => row.id === expectedSession) ??
chatList.rows.find((row) => !row.closed && row.close);
if (!operatorRow) throw new Error("no open chat row rendered");
if (!operatorRow.title) throw new Error("the operator chat row has no title");
if (!operatorRow.chips.includes("Operator")) {
throw new Error(`chat kind chip: ${operatorRow.chips.join(", ")}`);
}
if (!chatList.rows[0].close) throw new Error("the open chat row offers no Close chat action");
if (!operatorRow.close) throw new Error("the open chat row offers no Close chat action");
console.log(
` chat list: ${chatList.rows.length} session(s); "${chatList.rows[0].title}" ` +
`[${chatList.rows[0].chips.join(", ")}] — ${chatList.rows[0].meta}`,
` chat list: ${chatList.rows.length} session(s); "${operatorRow.title}" ` +
`[${operatorRow.chips.join(", ")}] — ${operatorRow.meta}`,
);
await shot("44-chat-sessions.png");
// The row's own Close chat… action with NO conversation open: the list offers
// it on every open row, so the confirm must still appear. Shown and dismissed
// with Cancel; no chat_close is ever sent for the operator's live session.
await page.click(`#chatRows .chat-row[data-session="${chatList.rows[0].id}"] .chat-close`);
await page.click(`#chatRows .chat-row[data-session="${operatorRow.id}"] .chat-close`);
await page.waitForSelector(".confirm-chat-close", { timeout: 15000 });
const listClose = await page.evaluate(
`document.querySelector(".confirm-chat-close .confirm-message")?.textContent ?? ""`,
@@ -2440,12 +2466,179 @@ try {
throw new Error(`Clear search left the query: ${JSON.stringify(clearedQuery)}`);
}
// C2: create a chat through the directory picker. This step creates exactly one
// REAL session (the app's own path, not the ephemeral `/new` verification path),
// captures it, then closes it with `chat_close` so it moves to closed history
// instead of sitting active in the operator's list. The operator's own session
// is never selected, closed or prompted here.
step("C2: the create pane — directory picker, one real create, then close");
await ensureConnected();
await page.evaluate(`(() => {
window.__pipelinesEphemeralChat = false;
window.__chatCreateBodies = [];
return true;
})()`);
await page.click(".chat-toolbar .chat-new");
await page.waitForSelector(".chat-create", { timeout: 15000 });
await page.waitForSelector(".chat-create-choice", { timeout: 20000 });
const picker = await page.evaluate(`(() => ({
title: document.querySelector(".chat-create-title")?.textContent ?? "",
back: document.querySelector(".chat-create-back")?.getAttribute("aria-label") ?? "",
backTitle: document.querySelector(".chat-create-back")?.getAttribute("title") ?? "",
prompt: document.querySelector(".chat-create-prompt")?.textContent ?? "",
loading: !!document.querySelector(".chat-create-loading"),
note: document.querySelector(".chat-create-model-note")?.textContent ?? "",
start: document.querySelector(".chat-create-start")?.textContent ?? "",
cancel: document.querySelector(".chat-create-cancel")?.textContent ?? "",
cancelDisabled: document.querySelector(".chat-create-cancel")?.disabled ?? null,
confirm: document.querySelector(".chat-create-confirm")?.textContent ?? "",
confirmDisabled: document.querySelector(".chat-create-confirm")?.disabled ?? null,
rows: [...document.querySelectorAll(".chat-create-choice")].map((row) => ({
label: row.querySelector(".chat-create-choice-label")?.textContent ?? "",
path: row.querySelector(".chat-create-choice-path")?.textContent ?? "",
directory: row.dataset.directory ?? "",
selected: row.getAttribute("aria-selected") === "true",
})),
}))()`);
if (picker.title !== "Start a chat") throw new Error(`C2 title: ${picker.title}`);
if (picker.back !== "Cancel new chat" || picker.backTitle !== "Cancel new chat") {
throw new Error(`C2 back label: ${JSON.stringify({ aria: picker.back, title: picker.backTitle })}`);
}
if (picker.prompt !== "Where should this chat live?") {
throw new Error(`C2 prompt: ${picker.prompt}`);
}
if (picker.loading) throw new Error("C2 still shows Loading directories… after the choices rendered");
if (
picker.note !==
"This server has no request for choosing a chat's model, so a new chat uses the server's default."
) {
throw new Error(`C2 model note: ${picker.note}`);
}
if (picker.start !== "Start in ~") throw new Error(`C2 footer: ${picker.start}`);
if (picker.cancel !== "Cancel") throw new Error(`C2 cancel: ${picker.cancel}`);
if (picker.cancelDisabled !== false || picker.confirmDisabled !== false) {
throw new Error(`C2 controls disabled before sending: ${JSON.stringify(picker)}`);
}
if (picker.confirm.trim() !== "New chat") throw new Error(`C2 confirm: ${picker.confirm}`);
if (picker.rows.length === 0) throw new Error("C2 rendered no directory choices");
const homeRow = picker.rows[0];
if (homeRow.label !== "Home (~)" || homeRow.directory !== "~" || !homeRow.selected) {
throw new Error(`C2 home row is not first and selected: ${JSON.stringify(homeRow)}`);
}
if (homeRow.path === "" || homeRow.path === "~") {
throw new Error(`C2 home row has no absolute path beneath it: ${JSON.stringify(homeRow)}`);
}
const recents = picker.rows.slice(1);
// A recent's own label is its full path (only the home row carries a separate
// secondary path), so the data-directory value and the label must agree.
if (recents.some((row) => row.label !== row.directory || row.directory === "")) {
throw new Error(`C2 recent rows are not labelled by full path: ${JSON.stringify(recents)}`);
}
console.log(
` create pane: "${picker.title}" (back "${picker.back}"); home "${homeRow.label}" ` +
`${homeRow.path} selected; ${recents.length} recent(s); footer "${picker.start}"`,
);
await shot("75-chat-create-picker.png");
// Choose home explicitly (it is already the default), then create exactly one
// session. The request body is recorded by the socket shim.
await page.click(".chat-create-choice");
await page.evaluate(`window.__chatCreateBodies = []`);
await page.click(".chat-create-confirm");
const beforeCreate = await page.evaluate(
`document.querySelector(".chat-row.selected")?.dataset.session ?? ""`,
);
const createdId = await eventually(
async () => {
const id = await page.evaluate(`document.querySelector(".chat-row.selected")?.dataset.session ?? ""`);
return id && id !== beforeCreate ? id : false;
},
{ timeout: 30000, what: "the C2-created session to be selected" },
);
createdSessionId = createdId;
const created = await page.evaluate(`(() => {
const rows = [...document.querySelectorAll("#chatRows .chat-row")];
const row = document.querySelector('.chat-row[data-session="${createdId}"]');
return {
first: rows[0]?.dataset.session ?? "",
title: row?.querySelector(".chat-row-title")?.textContent ?? "",
selected: row?.classList.contains("selected") ?? false,
closed: !!row?.querySelector(".chat-closed-chip"),
header: document.querySelector(".chat-bar-title")?.textContent ?? "",
empty: document.querySelector(".chat-detail .chat-transcript-empty")?.textContent ?? "",
composer: !!document.querySelector("#chatComposer"),
pickerGone: !document.querySelector(".chat-create"),
};
})()`);
const createBodies = await page.evaluate(`window.__chatCreateBodies || []`);
if (createBodies.length !== 1) {
throw new Error(`C2 sent ${createBodies.length} chat_create request(s) for one create`);
}
const body = createBodies[0] ?? {};
if (
body.title !== "New chat" ||
body.directory !== "~" ||
typeof body.operation_id !== "string" ||
body.operation_id === "" ||
Object.keys(body).sort().join(",") !== "directory,operation_id,title"
) {
throw new Error(`C2 chat_create body: ${JSON.stringify(body)}`);
}
if (!created.pickerGone || !created.selected || created.closed) {
throw new Error(`C2 did not close the pane onto the new conversation: ${JSON.stringify(created)}`);
}
if (created.first !== createdId) {
throw new Error(`C2 created row is not at the head: first=${created.first} created=${createdId}`);
}
if (created.title !== "New chat" || created.header !== "New chat") {
throw new Error(`C2 created title: ${JSON.stringify(created)}`);
}
if (created.empty !== "This chat has no messages yet. Ask something below." || !created.composer) {
throw new Error(`C2 did not load the empty conversation: ${JSON.stringify(created)}`);
}
console.log(
` chat_create sent exactly {title:"New chat",directory:"~",operation_id:${JSON.stringify(body.operation_id)}}; ` +
`session ${createdId} at the head, active with empty history`,
);
await shot("76-chat-created-list.png");
// Close the one real session it created (chat_close through the C3 confirm) and
// capture the Closed chip. Nothing is deleted; the row stays as closed history.
await page.click(`#chatRows .chat-row[data-session="${createdId}"] .chat-close`);
await page.waitForSelector(".confirm-chat-close", { timeout: 15000 });
await page.click(".confirm-chat-close .confirm-accept");
await eventually(
() =>
page.evaluate(
`!!document.querySelector('.chat-row[data-session="${createdId}"] .chat-closed-chip')`,
),
{ timeout: 20000, what: "the C2 session to show as closed" },
);
const createdClosed = await page.evaluate(`(() => {
const row = document.querySelector('.chat-row[data-session="${createdId}"]');
row?.scrollIntoView({ block: "center" });
return {
closed: !!row?.querySelector(".chat-closed-chip"),
hasClose: !!row?.querySelector(".chat-close"),
hasReopen: !!row?.querySelector(".chat-reopen"),
};
})()`);
if (!createdClosed.closed || createdClosed.hasClose || !createdClosed.hasReopen) {
throw new Error(`C2 closed row: ${JSON.stringify(createdClosed)}`);
}
console.log(
` C2: created real session ${createdId} ("New chat" in ~) and closed it via chat_close; ` +
"it now shows the Closed chip (kept as history, not deleted)",
);
await shot("77-chat-created-closed.png");
createdSessionId = null;
// The live session set changes between runs: the first row can be a
// freshly-created empty "New chat" (which renders the empty state, not a
// transcript). Prefer the operator's own session; otherwise try the listed rows
// in order until one carries a real transcript, and say plainly if none does,
// rather than waiting on a hard-coded session that the server no longer lists.
const expectedSession = "ses_eae413f50ffeLQDExlg8cYnscN";
const preferred = chatList.rows.find((row) => row.id === expectedSession);
const openRows = chatList.rows.filter((row) => row.close).map((row) => row.id);
const candidates = [
@@ -5004,6 +5197,38 @@ try {
}
}
} finally {
// Best-effort cleanup of C2's real session: if the run failed between creating
// it and its own close, close it now so it never sits active in the operator's
// list. Nothing is deleted either way.
if (createdSessionId && page) {
try {
const closed = await page.evaluate(
`!!document.querySelector('.chat-row[data-session="${createdSessionId}"] .chat-closed-chip')`,
);
if (!closed) {
await page.evaluate(
`document.querySelector('#chatRows .chat-row[data-session="${createdSessionId}"]')?.click()`,
);
await page.waitForSelector("#chatInput", { timeout: 8000 }).catch(() => {});
await page.evaluate(`(async () => {
const input = document.querySelector("#chatInput");
if (!input) return;
input.value = "/close";
input.dispatchEvent(new Event("input", { bubbles: true }));
input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }));
await new Promise((resolve) => setTimeout(resolve, 400));
document.querySelector(".confirm-chat-close .confirm-accept")?.click();
})()`);
await eventually(() => page.evaluate(`!document.querySelector(".confirm-chat-close")`), {
timeout: 8000,
what: "the C2 cleanup close to finish",
}).catch(() => {});
console.log(` cleanup: closed the C2-created session ${createdSessionId}`);
}
} catch {
// the page may already be gone; the failure above is the real signal
}
}
// Best-effort cleanup of the throwaway session this run created: if the run
// failed before its `/close` step, close it now so it is never left open.
if (throwawaySessionId && page) {