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
+244 -10
View File
@@ -2,7 +2,7 @@
// Deliberately small and DOM-only (no framework, no build step). Every value
// that came from the server is set with textContent, never innerHTML.
import { PipelinesClient } from "./client.js";
import { PipelinesRepository, SHELL_OUTPUT_LIMIT } from "./repository.js";
import { PipelinesRepository, SHELL_OUTPUT_LIMIT, newChatOperationId } from "./repository.js";
import { PROTOCOL_VERSION, Protocol, ChatKeys } from "./protocol.js";
import { validateServerUrl, resolveArtifactUrl } from "./serverUrl.js";
import {
@@ -232,6 +232,13 @@ import {
CHAT_COMMAND_DISMISS_LABEL,
CHAT_COMMAND_GLYPH,
CHAT_COMPOSER_PLACEHOLDER,
CHAT_CREATE_BACK_LABEL,
CHAT_CREATE_CANCEL,
CHAT_CREATE_CONFIRM,
CHAT_CREATE_LOADING,
CHAT_CREATE_MODEL_NOTE,
CHAT_CREATE_PROMPT,
CHAT_CREATE_TITLE,
CHAT_EMPTY,
CHAT_FOLLOW_THRESHOLD_PX,
CHAT_LOADING,
@@ -283,6 +290,9 @@ import {
chatCommandEffect,
chatCommandHelp,
chatCommandSuggestions,
chatCreateFailed,
chatCreateSucceeded,
chatStartInLabel,
chatFirstScroll,
chatFollowsAt,
chatHeaderMeta,
@@ -296,6 +306,8 @@ import {
composerCanSend,
composerSendEnabled,
composerSubmit,
defaultDirectoryChoice,
directoryChoices,
directoryLabel,
dismissChatNotice as dismissChatNoticeModel,
filterSessions,
@@ -304,6 +316,7 @@ import {
makeChatNotice,
mergeHistoryPage,
mergeShellFrame,
newChatCreateState,
newChatThread,
parseChatInput,
queuedAfterFrame,
@@ -317,6 +330,7 @@ import {
sessionChipLabel,
sessionMeta,
sessionStatusLabel,
selectChatDirectory as selectChatDirectoryModel,
sessionTitle,
sessionWorkLabel,
settledThread,
@@ -502,6 +516,11 @@ const state = {
// is set with textContent and the markdown renderer builds DOM nodes, never
// innerHTML.
chatSessions: [],
// The verification chats this page itself created (C2's automation flag). The
// server deliberately never lists them; the page keeps its own in-memory row so
// the creator can keep working with the chat it just opened. The set is
// memory-only, so a reload cannot turn one into a permanent list entry.
chatEphemeralIds: new Set(),
chatLoading: false,
chatLoaded: false,
chatError: "",
@@ -538,6 +557,14 @@ const state = {
// re-established for the open chat on reconnect. A refused subscription simply
// never joins the set, so the badge reads "not live" honestly.
chatSubscriptions: new Set(),
// C2: the create flow. `chatCreate` is the ChatCreateState analogue (null until
// the New chat entry point is used); the directory reply is cached so cancelling
// and reopening does not re-ask, and a failed load keeps its own reason.
chatDirectories: [],
chatDirectoriesLoading: false,
chatDirectoriesLoaded: false,
chatDirectoriesError: "",
chatCreate: null,
};
let runPoll = null;
@@ -1055,7 +1082,9 @@ function renderContent() {
} else if (state.view === "runs") {
split.append(renderRunList(), renderRunDetail());
} else if (state.view === "chat") {
split.append(renderChatList(), renderChatConversation());
// While the create flow is open it owns the detail pane; the session list
// stays visible beside it, exactly as the app's two-pane chat stack does.
split.append(renderChatList(), state.chatCreate ? renderChatCreate() : renderChatConversation());
} else {
split.append(renderTemplateGallery(), renderTemplateDetail());
}
@@ -3983,7 +4012,15 @@ async function loadChatSessions(force = false) {
state.chatError = "";
renderContent();
try {
state.chatSessions = await repo.chatSessions();
const listed = await repo.chatSessions();
// Keep this page's own verification chats, which the server intentionally
// never returns, at the head of the in-memory list (memory-only; see
// chatEphemeralIds). Everything else is the server's list, in its order.
const held = state.chatSessions.filter(
(session) =>
state.chatEphemeralIds.has(session.id) && !listed.some((entry) => entry.id === session.id),
);
state.chatSessions = [...held, ...listed];
state.chatLoaded = true;
} catch (error) {
state.chatError = describeError(error);
@@ -3992,6 +4029,85 @@ async function loadChatSessions(force = false) {
renderContent();
}
// ---------------------------------------------------------------------------
// The create flow (C2, ChatCreatePane.kt)
// ---------------------------------------------------------------------------
/**
* Open the create pane with a fresh operation id. The id is minted once per
* intent, so a retry after a refusal reuses it and the server can dedupe the
* create rather than starting a second session.
*/
function startNewChat() {
state.chatCreate = newChatCreateState(newChatOperationId());
state.chatDirectoriesError = "";
renderContent();
loadChatDirectories();
}
/**
* Fetch `chat_directories` for the open picker. A failure keeps the reason for the
* pane's error state; blank entries are dropped here as well as in the pure model
* so a malformed reply can never produce an empty row. An already-loaded list is
* reused unless [force] (the error state's Retry) asks again.
*/
async function loadChatDirectories(force = false) {
if (!state.chatCreate || state.chatDirectoriesLoading) return;
if (state.chatDirectoriesLoaded && !force) return;
state.chatDirectoriesLoading = true;
state.chatDirectoriesError = "";
renderContent();
try {
const directories = await repo.chatDirectories();
state.chatDirectories = (directories ?? []).filter((entry) => String(entry ?? "").trim() !== "");
state.chatDirectoriesLoaded = true;
} catch (error) {
state.chatDirectoriesError = describeError(error);
}
state.chatDirectoriesLoading = false;
renderContent();
}
/** Select one directory row (the value is what chat_create will send). */
function selectChatDirectory(value) {
if (!state.chatCreate) return;
state.chatCreate = selectChatDirectoryModel(state.chatCreate, value);
renderContent();
}
/** Leave the create flow without creating anything. */
function cancelNewChat() {
state.chatCreate = null;
renderContent();
}
/**
* Create the chat in the chosen directory. Guarded against a double submit: the
* guard reads the held state, so a second click while the request is in flight
* sends nothing. On success the pane closes, the created session goes to the head
* of the list, becomes the open conversation and loads its (empty) history; on
* failure the server's own reason stays in the pane, which does not close.
*/
async function createNewChat() {
const create = state.chatCreate;
if (!create || create.creating) return;
state.chatCreate = { ...create, creating: true, error: "" };
renderContent();
try {
// Not ephemeral: this is the operator's own create path (the UI smoke uses the
// same path for its one real session and closes it afterwards).
const created = await repo.chatCreate("New chat", create.directory, create.operationId);
state.chatCreate = null;
state.chatSessions = chatCreateSucceeded(state.chatSessions, created);
await openChatSession(created.id);
await loadChatSessions();
} catch (error) {
if (!state.chatCreate) return;
state.chatCreate = chatCreateFailed(state.chatCreate, describeError(error));
renderContent();
}
}
/** Open a session: select it, subscribe its stream and load its newest history page. */
async function openChatSession(id) {
if (state.chatActiveId === id && state.chatThreads.get(id)?.loaded) return;
@@ -4585,9 +4701,9 @@ async function startChatSession(directory) {
// An automated check (the UI smoke) can mark its throwaway chat ephemeral, so
// creating one for verification never adds a stray "New chat" to the
// operator's list. Set only by test tooling; a normal page leaves it unset.
const created = await repo.chatCreate("New chat", directory, undefined, {
ephemeral: globalThis.__pipelinesEphemeralChat === true,
});
const ephemeral = globalThis.__pipelinesEphemeralChat === true;
const created = await repo.chatCreate("New chat", directory, undefined, { ephemeral });
if (ephemeral) state.chatEphemeralIds = new Set(state.chatEphemeralIds).add(created.id);
// The list is the server's; insert the created session so the row is present
// before the conversation opens, then refresh from the server.
state.chatSessions = [created, ...state.chatSessions.filter((s) => s.id !== created.id)];
@@ -4776,6 +4892,14 @@ function renderChatList() {
fillChatRows(rows);
},
}),
// C2: the create path stays one tap away while the list is narrowed, the same
// trailing action the app keeps beside its search control.
h("button", {
class: "ghost chat-new",
type: "button",
text: CHAT_NEW_ACTION,
onclick: startNewChat,
}),
);
list.append(toolbar);
const rows = h("div", { id: "chatRows", class: "chat-rows" });
@@ -4817,16 +4941,13 @@ function fillChatRows(rows) {
return;
}
if (filtered.length === 0) {
// The create path is the C2 item; the action is shown but deliberately not
// wired here, exactly as the item says.
const empty = chatEmpty(CHAT_EMPTY);
empty.append(
h("button", {
class: "ghost chat-new",
type: "button",
text: CHAT_NEW_ACTION,
disabled: true,
title: "Creating a chat lands with the C2 item",
onclick: startNewChat,
}),
);
rows.append(empty);
@@ -4935,6 +5056,119 @@ function renderChatRow(session) {
return row;
}
/**
* The create pane (C2): the app's NewChatPane. A back control leaves without
* creating, then the directory error / loading / picker states in the app's own
* order, the model note and the footer naming the value that will be sent. Every
* server string is set with textContent.
*/
function renderChatCreate() {
const create = state.chatCreate;
const pane = h("div", { class: "detail chat-detail chat-create" });
const bar = h("div", { class: "chat-bar chat-create-bar" });
bar.append(
h(
"button",
{
class: "ghost chat-create-back",
type: "button",
"aria-label": CHAT_CREATE_BACK_LABEL,
title: CHAT_CREATE_BACK_LABEL,
onclick: cancelNewChat,
},
h("span", { class: "chat-create-back-glyph", "aria-hidden": "true", text: "←" }),
),
h("h2", { class: "chat-bar-title chat-create-title", text: CHAT_CREATE_TITLE }),
);
pane.append(bar);
if (state.chatDirectoriesError && !state.chatDirectoriesLoaded) {
const empty = chatEmpty(state.chatDirectoriesError);
empty.classList.add("chat-create-directories-error");
empty.append(
h("button", {
class: "ghost chat-create-retry",
type: "button",
text: "Retry",
onclick: () => loadChatDirectories(true),
}),
);
pane.append(empty);
} else if (!state.chatDirectoriesLoaded) {
pane.append(h("div", { class: "chat-create-loading muted", text: CHAT_CREATE_LOADING }));
} else {
pane.append(h("div", { class: "chat-create-prompt muted", text: CHAT_CREATE_PROMPT }));
const choices = directoryChoices(state.chatDirectories);
const selected =
choices.find((choice) => choice.createDirectory === create.directory) ??
defaultDirectoryChoice(choices);
const list = h("div", {
class: "chat-create-choices",
role: "listbox",
"aria-label": CHAT_CREATE_PROMPT,
});
for (const choice of choices) {
const active = choice.createDirectory === selected?.createDirectory;
const row = h("button", {
class: `row chat-create-choice${active ? " selected" : ""}`,
type: "button",
role: "option",
"aria-selected": active ? "true" : "false",
"data-directory": choice.createDirectory,
onclick: () => selectChatDirectory(choice.createDirectory),
});
row.append(h("span", { class: "row-title chat-create-choice-label", text: choice.label }));
if (choice.secondary) {
row.append(h("span", { class: "row-meta chat-create-choice-path", text: choice.secondary }));
}
list.append(row);
}
pane.append(list);
// A refresh that failed after a successful first load keeps the choices and
// says why the list may be stale (the app's own bodySmall error line).
if (state.chatDirectoriesError) {
pane.append(h("div", { class: "chat-create-directories-error", text: state.chatDirectoriesError }));
}
if (create.error) {
pane.append(h("div", { class: "chat-create-error", text: create.error }));
}
pane.append(h("p", { class: "chat-create-model-note muted", text: CHAT_CREATE_MODEL_NOTE }));
const directory = selected?.createDirectory ?? create.directory;
const footer = h("div", { class: "chat-create-footer" });
footer.append(h("span", { class: "chat-create-start", text: chatStartInLabel(directory) }));
footer.append(
h("button", {
class: "ghost chat-create-cancel",
type: "button",
text: CHAT_CREATE_CANCEL,
disabled: create.creating,
onclick: cancelNewChat,
}),
);
const confirm = h("button", {
class: "chat-create-confirm",
type: "button",
"aria-label": CHAT_CREATE_CONFIRM,
disabled: create.creating,
onclick: createNewChat,
});
if (create.creating) {
confirm.append(h("span", { class: "spinner chat-create-spinner", "aria-hidden": "true" }));
} else {
confirm.append(document.createTextNode(CHAT_CREATE_CONFIRM));
}
footer.append(confirm);
pane.append(footer);
}
appendChatDialogs(pane);
return pane;
}
/** The active conversation: identity, context, transcript and its controls. */
function renderChatConversation() {
const pane = h("div", { class: "detail chat-detail" });
+95
View File
@@ -16,6 +16,10 @@
// toolLongRunning (the chip and its panel)
// ui/chat/ChatListFilter.kt sessionMatchesQuery, filterChatSessions,
// groupChatSessionsByDirectory
// ui/chat/ChatDirectories.kt HOME_DIRECTORY, directoryChoices,
// defaultDirectoryChoice (the create picker)
// ui/chat/ChatCreatePane.kt the create flow's wording, NewChatActions footer
// and the create state transitions
// ui/chat/ChatScroll.kt chatBottomDistancePx, chatFollowsAt,
// chatShowJumpToLatest, chatOpensAtNewest,
// chatFirstScroll
@@ -114,6 +118,25 @@ export const CONVERSATION_EMPTY = "This chat has no messages yet. Ask something
export const LOAD_OLDER_ACTION = "Load older messages";
export const SELECT_CHAT_HINT = "Select a chat to open it.";
// The create flow (C2, ChatCreatePane.kt), verbatim. The home choice's row is
// `Home (~)` while chat_create sends the `~` the server documents; the footer
// names the value that will be sent (see chatStartInLabel).
export const HOME_DIRECTORY = "~";
export const HOME_LABEL = `Home (${HOME_DIRECTORY})`;
export const CHAT_CREATE_TITLE = "Start a chat";
export const CHAT_CREATE_BACK_LABEL = "Cancel new chat";
export const CHAT_CREATE_LOADING = "Loading directories…";
export const CHAT_CREATE_PROMPT = "Where should this chat live?";
export const CHAT_CREATE_MODEL_NOTE =
"This server has no request for choosing a chat's model, so a new chat uses the server's default.";
export const CHAT_CREATE_CONFIRM = "New chat";
export const CHAT_CREATE_CANCEL = "Cancel";
/** The create footer's line: `Start in {directory}` with the value that is sent. */
export function chatStartInLabel(directory) {
return `Start in ${str(directory)}`;
}
/** The listing's narrowed-to-nothing message: `No chats match "{query}".` */
export function chatNoMatchMessage(query) {
return `No chats match "${str(query).trim()}".`;
@@ -610,6 +633,78 @@ export function directoryLabel(directory) {
return isBlank(directory) ? NO_DIRECTORY_LABEL : str(directory);
}
// ---------------------------------------------------------------------------
// The create flow's directory choices (ChatDirectories.kt)
// ---------------------------------------------------------------------------
/**
* The picker's choices from the server's reported directories. The first entry is
* the operator's home — the one entry the server always returns first — and the
* rest keep the server's most-recently-used order. A blank entry is dropped, and a
* reply with nothing in it still yields the home choice, so the picker is never
* empty. A recent's `label` is its full path; only the home row carries the path
* as `secondary`, because its own label is `Home (~)`.
*/
export function directoryChoices(directories) {
const cleaned = (directories ?? []).map((entry) => str(entry)).filter((entry) => !isBlank(entry));
const home = cleaned.length > 0 ? cleaned[0] : HOME_DIRECTORY;
return [
{
label: HOME_LABEL,
path: home,
home: true,
createDirectory: HOME_DIRECTORY,
secondary: home,
},
...cleaned.slice(1).map((path) => ({
label: path,
path,
home: false,
createDirectory: path,
secondary: null,
})),
];
}
/** The choice a freshly opened picker starts on: home, first. */
export function defaultDirectoryChoice(choices) {
return (choices ?? [])[0] ?? null;
}
/** A fresh create state: home selected, the caller's operation id, not sending. */
export function newChatCreateState(operationId) {
return {
directory: HOME_DIRECTORY,
operationId: str(operationId),
creating: false,
error: "",
};
}
/**
* Choose one directory for the create. Kept pure so the view can re-render from a
* single state object; the error a previous refusal left is cleared because it
* described the old choice, not this one.
*/
export function selectChatDirectory(create, choice) {
const directory =
typeof choice === "string" ? choice : str(choice?.createDirectory ?? "");
if (isBlank(directory)) return { ...create };
return { ...create, directory, error: "" };
}
/** The create failed: stop sending and keep the server's own reason in the pane. */
export function chatCreateFailed(create, message) {
return { ...create, creating: false, error: str(message) };
}
/** The create succeeded: the new session goes to the head of the list, deduped by id. */
export function chatCreateSucceeded(sessions, session) {
const list = sessions ?? [];
if (!session) return list;
return [session, ...list.filter((entry) => entry?.id !== session.id)];
}
// ---------------------------------------------------------------------------
// Transcript (ChatFormat.kt)
// ---------------------------------------------------------------------------
+7
View File
@@ -64,6 +64,10 @@ export const Protocol = Object.freeze({
CHAT_PROMPT: "chat_prompt",
CHAT_INTERRUPT: "chat_interrupt",
CHAT_CREATE: "chat_create",
// The create flow's directory choices (C2): `chat_directories` has no body and
// replies in the `chat_directories` field, home first then recent operator
// directories (internal/protocol/chat.go ChatDirectories).
CHAT_DIRECTORIES: "chat_directories",
// The approval card (C10): the server pushes `chat_permission` frames (one
// pending request, later re-pushed with the resolution) and the phone answers
// with `chat_reply` (internal/protocol/chat.go ChatPermission/ChatReply).
@@ -102,6 +106,9 @@ export const ChatKeys = Object.freeze({
// separate field name here would put it on the wrong part of the envelope.
PROMPT: "chat_prompt",
CREATE: "chat_create",
// The `chat_directories` reply (C2), home first then recents; mirrors
// internal/protocol/message.go `ChatDirectories []string`.
DIRECTORIES: "chat_directories",
QUEUED: "chat_queued",
// C10: the pushed approval frame (`chat_permission`) and the answer body
// (`chat_reply`), both distinct Message fields in internal/protocol/message.go.
+12
View File
@@ -383,6 +383,18 @@ export class PipelinesRepository {
});
}
/**
* Lists the directories a new chat can live in (C2), mirroring
* `PipelinesRepository.chatDirectories`: a bare `{type:'chat_directories'}` with
* no body, replying in `chat_directories` (home first, then recent operator
* directories). An older server that returns no field answers with an empty
* list; the view still offers home so the picker is never empty.
*/
async chatDirectories() {
const response = await this.#client.call({ type: Protocol.CHAT_DIRECTORIES });
return response[ChatKeys.DIRECTORIES] ?? [];
}
/**
* Creates one session in an explicit directory (mirrors
* `PipelinesRepository.chatCreate`). The directory is always sent, so a chat is