Merge branch 'main' into web-routes

Resolve the L6 routes against the newer C2/C13/L5/R10 shell: keep both sides
(single client imports, the run-alert watch inside the reconnect path, the boot
route + popstate wiring alongside loadNotifyAsked, main's L5 row and L6 done).
This commit is contained in:
2026-10-19 14:47:49 +01:00
18 changed files with 3903 additions and 137 deletions
+6
View File
@@ -349,6 +349,12 @@ sessions pipeline runs create. The protocol types are:
value all resolve to the home directory). A relative or missing directory is value all resolve to the home directory). A relative or missing directory is
rejected before any OpenCode call. The created session is recorded with the rejected before any OpenCode call. The created session is recorded with the
stored tag `operator` and returned as the response's `chat_session`. stored tag `operator` and returned as the response's `chat_session`.
An optional `ephemeral: true` creates the session for automated verification:
it is created, bootstrapped and usable exactly like any other chat and can still
be closed and reopened, but its registry row is hidden, so `chat_sessions` never
lists it and a check that drives the real UI cannot leave a stray "New chat" in
the operator's list. The flag only removes a chat from the shared list, so it
cannot reveal or alter another session.
- `chat_directories` returns the operator's home first, then the directories of - `chat_directories` returns the operator's home first, then the directories of
previous operator sessions most-recently-used first, deduplicated and bounded previous operator sessions most-recently-used first, deduplicated and bounded
(currently 8). It is a dedicated request so the create dialog can load the (currently 8). It is a dedicated request so the create dialog can load the
+37 -10
View File
@@ -58,7 +58,7 @@ func (s *Store) initOperatorSessions() error {
_, err := s.db.Exec(`CREATE TABLE IF NOT EXISTS operator_sessions ( _, err := s.db.Exec(`CREATE TABLE IF NOT EXISTS operator_sessions (
session_id TEXT PRIMARY KEY, directory TEXT NOT NULL, title TEXT NOT NULL DEFAULT '', session_id TEXT PRIMARY KEY, directory TEXT NOT NULL, title TEXT NOT NULL DEFAULT '',
tag TEXT NOT NULL DEFAULT '', created_at INTEGER NOT NULL, last_used_at INTEGER NOT NULL, tag TEXT NOT NULL DEFAULT '', created_at INTEGER NOT NULL, last_used_at INTEGER NOT NULL,
closed_at INTEGER NOT NULL DEFAULT 0); closed_at INTEGER NOT NULL DEFAULT 0, ephemeral INTEGER NOT NULL DEFAULT 0);
CREATE INDEX IF NOT EXISTS operator_sessions_recent ON operator_sessions(last_used_at DESC);`) CREATE INDEX IF NOT EXISTS operator_sessions_recent ON operator_sessions(last_used_at DESC);`)
if err != nil { if err != nil {
return err return err
@@ -131,7 +131,13 @@ func (s *Store) AdvanceChatCreate(ctx context.Context, requestID, from, to strin
// row valid and open (0), so an upgrade is idempotent across repeated Open calls // row valid and open (0), so an upgrade is idempotent across repeated Open calls
// and no session is silently reported as closed. // and no session is silently reported as closed.
func (s *Store) migrateOperatorSessions() error { func (s *Store) migrateOperatorSessions() error {
return s.addColumnIfMissing("operator_sessions", "closed_at", "INTEGER NOT NULL DEFAULT 0") if err := s.addColumnIfMissing("operator_sessions", "closed_at", "INTEGER NOT NULL DEFAULT 0"); err != nil {
return err
}
// ephemeral marks a chat created for automated verification. It is hidden from
// OperatorSessions but still a real row, so the session stays usable and
// closable. Existing rows default to 0 (a normal, listed chat).
return s.addColumnIfMissing("operator_sessions", "ephemeral", "INTEGER NOT NULL DEFAULT 0")
} }
// RecordOperatorSession upserts one operator chat session in a single statement: // RecordOperatorSession upserts one operator chat session in a single statement:
@@ -139,13 +145,32 @@ func (s *Store) migrateOperatorSessions() error {
// repeated id updates directory/title/tag and moves last_used_at to now while // repeated id updates directory/title/tag and moves last_used_at to now while
// preserving the original created_at. CreatedAt is therefore stable across // preserving the original created_at. CreatedAt is therefore stable across
// re-records. Recording also clears any closed state: re-creating or adopting a // re-records. Recording also clears any closed state: re-creating or adopting a
// session is use, so it is open again. // session is use, so it is open again. The row is a normal listed operator chat
// (ephemeral = 0).
func (s *Store) RecordOperatorSession(ctx context.Context, sessionID, directory, title, tag string) error { func (s *Store) RecordOperatorSession(ctx context.Context, sessionID, directory, title, tag string) error {
return s.recordSession(ctx, sessionID, directory, title, tag, false)
}
// RecordVerificationSession upserts one chat created for automated verification
// (chat_create with ephemeral set). It is a real registry row — so the session
// can still be closed, reopened and looked up by id — but OperatorSessions, and
// therefore chat_sessions, never lists it. It exists so a check that drives the
// real UI cannot leave a permanent "New chat" in the operator's list, and a
// re-record always keeps it hidden.
func (s *Store) RecordVerificationSession(ctx context.Context, sessionID, directory, title, tag string) error {
return s.recordSession(ctx, sessionID, directory, title, tag, true)
}
func (s *Store) recordSession(ctx context.Context, sessionID, directory, title, tag string, ephemeral bool) error {
now := time.Now().UnixMilli() now := time.Now().UnixMilli()
_, err := s.db.ExecContext(ctx, `INSERT INTO operator_sessions(session_id,directory,title,tag,created_at,last_used_at,closed_at) hidden := 0
VALUES(?,?,?,?,?,?,0) if ephemeral {
ON CONFLICT(session_id) DO UPDATE SET directory=excluded.directory,title=excluded.title,tag=excluded.tag,last_used_at=excluded.last_used_at,closed_at=0`, hidden = 1
sessionID, directory, title, tag, now, now) }
_, err := s.db.ExecContext(ctx, `INSERT INTO operator_sessions(session_id,directory,title,tag,created_at,last_used_at,closed_at,ephemeral)
VALUES(?,?,?,?,?,?,0,?)
ON CONFLICT(session_id) DO UPDATE SET directory=excluded.directory,title=excluded.title,tag=excluded.tag,last_used_at=excluded.last_used_at,closed_at=0,ephemeral=excluded.ephemeral`,
sessionID, directory, title, tag, now, now, hidden)
return err return err
} }
@@ -196,13 +221,15 @@ FROM operator_sessions WHERE session_id=? AND tag <> ''`, sessionID)
// OperatorSessions reports the operator's chat sessions, most-recently-used // OperatorSessions reports the operator's chat sessions, most-recently-used
// first (ties broken by session id for a deterministic order), capped at // first (ties broken by session id for a deterministic order), capped at
// operatorSessionListLimit. Rows with no tag are omitted: a session with no // operatorSessionListLimit. Rows with no tag are omitted: a session with no
// recorded tag is not an operator session and must never be listed. Closed // recorded tag is not an operator session and must never be listed. Ephemeral
// sessions are included: the app groups or filters them as history, so the // rows are omitted too: a chat created for automated verification is usable and
// closable but never listed here, so it cannot clutter the operator's list.
// Closed sessions are included: the app groups or filters them as history, so the
// operator can still see and reopen what they finished. It is one bounded // operator can still see and reopen what they finished. It is one bounded
// statement; recency is never mutated here. // statement; recency is never mutated here.
func (s *Store) OperatorSessions(ctx context.Context) ([]OperatorSession, error) { func (s *Store) OperatorSessions(ctx context.Context) ([]OperatorSession, error) {
rows, err := s.db.QueryContext(ctx, `SELECT session_id,directory,title,tag,created_at,last_used_at,closed_at rows, err := s.db.QueryContext(ctx, `SELECT session_id,directory,title,tag,created_at,last_used_at,closed_at
FROM operator_sessions WHERE tag <> '' ORDER BY last_used_at DESC, session_id LIMIT ?`, operatorSessionListLimit) FROM operator_sessions WHERE tag <> '' AND ephemeral = 0 ORDER BY last_used_at DESC, session_id LIMIT ?`, operatorSessionListLimit)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -232,3 +232,91 @@ func TestOperatorSessionsSurviveRestart(t *testing.T) {
t.Fatalf("restarted row missing fields: %+v", after[0]) t.Fatalf("restarted row missing fields: %+v", after[0])
} }
} }
// TestRecordVerificationSessionIsRealButNeverListed proves the automated-
// verification contract: the row exists and is closable (so a check that drives
// the real page can still close its throwaway chat), but OperatorSessions — and
// therefore chat_sessions — never lists it.
func TestRecordVerificationSessionIsRealButNeverListed(t *testing.T) {
ctx := context.Background()
store, err := Open(filepath.Join(t.TempDir(), "verification-session.db"))
if err != nil {
t.Fatal(err)
}
defer store.Close()
if err := store.RecordOperatorSession(ctx, "ses_mine", "/work/mine", "Mine", "operator"); err != nil {
t.Fatal(err)
}
if err := store.RecordVerificationSession(ctx, "ses_check", "/work/check", "New chat", "operator"); err != nil {
t.Fatal(err)
}
listed, err := store.OperatorSessions(ctx)
if err != nil {
t.Fatal(err)
}
if len(listed) != 1 || listed[0].ID != "ses_mine" {
t.Fatalf("verification session was listed: %+v", listed)
}
session, found, err := store.OperatorSession(ctx, "ses_check")
if err != nil || !found {
t.Fatalf("verification session is not looked up: found=%v err=%v", found, err)
}
if session.ID != "ses_check" || session.Directory != "/work/check" {
t.Fatalf("verification session row = %+v", session)
}
if err := store.CloseOperatorSession(ctx, "ses_check"); err != nil {
t.Fatalf("close verification session: %v", err)
}
// Re-recording keeps it hidden, and a normal record of the same id lists it
// again (the flag is replaced, not sticky).
if err := store.RecordVerificationSession(ctx, "ses_check", "/work/check", "New chat", "operator"); err != nil {
t.Fatal(err)
}
if listed, err = store.OperatorSessions(ctx); err != nil || len(listed) != 1 {
t.Fatalf("re-recorded verification session listed: %+v err=%v", listed, err)
}
if err := store.RecordOperatorSession(ctx, "ses_check", "/work/check", "Kept", "operator"); err != nil {
t.Fatal(err)
}
if listed, err = store.OperatorSessions(ctx); err != nil || len(listed) != 2 {
t.Fatalf("a normal re-record did not list the session: %+v err=%v", listed, err)
}
}
// TestOperatorSessionsMigrationAddsEphemeral proves an existing database created
// before the ephemeral column opens cleanly and keeps every existing chat listed.
func TestOperatorSessionsMigrationAddsEphemeral(t *testing.T) {
ctx := context.Background()
path := filepath.Join(t.TempDir(), "migrate-ephemeral.db")
store, err := Open(path)
if err != nil {
t.Fatal(err)
}
if err := store.RecordOperatorSession(ctx, "ses_old", "/work/old", "Old", "operator"); err != nil {
t.Fatal(err)
}
if _, err := store.db.ExecContext(ctx, "ALTER TABLE operator_sessions DROP COLUMN ephemeral"); err != nil {
t.Fatalf("drop ephemeral: %v", err)
}
if err := store.Close(); err != nil {
t.Fatal(err)
}
store, err = Open(path)
if err != nil {
t.Fatalf("Open after drop: %v", err)
}
defer store.Close()
listed, err := store.OperatorSessions(ctx)
if err != nil {
t.Fatal(err)
}
if len(listed) != 1 || listed[0].ID != "ses_old" {
t.Fatalf("migrated session list = %+v", listed)
}
if err := store.RecordVerificationSession(ctx, "ses_new_check", "/work/new", "New chat", "operator"); err != nil {
t.Fatal(err)
}
if listed, err = store.OperatorSessions(ctx); err != nil || len(listed) != 1 {
t.Fatalf("verification session listed after migration: %+v err=%v", listed, err)
}
}
+8
View File
@@ -187,6 +187,14 @@ type ChatCreateRequest struct {
Title string `json:"title,omitempty"` Title string `json:"title,omitempty"`
Directory string `json:"directory,omitempty"` Directory string `json:"directory,omitempty"`
OperationID string `json:"operation_id,omitempty"` OperationID string `json:"operation_id,omitempty"`
// Ephemeral creates a chat for automated verification: the session is created,
// bootstrapped and usable exactly like a normal one, but no operator-registry
// row is written, so it can never appear in chat_sessions. It exists because a
// verification client drives the real UI and would otherwise leave a permanent
// "New chat" in the operator's list for every run. The flag is client-supplied
// and only ever *removes* a chat from the shared list, so a buggy or hostile
// client can hide its own chat but cannot reveal or alter another one.
Ephemeral bool `json:"ephemeral,omitempty"`
} }
// ChatAdoptRequest is the chat_adopt request body: the id of a session that // ChatAdoptRequest is the chat_adopt request body: the id of a session that
+3
View File
@@ -68,6 +68,9 @@ type operatorRegistry interface {
SetChatCreateSession(ctx context.Context, requestID, sessionID string) error SetChatCreateSession(ctx context.Context, requestID, sessionID string) error
AdvanceChatCreate(ctx context.Context, requestID, from, to string) error AdvanceChatCreate(ctx context.Context, requestID, from, to string) error
RecordOperatorSession(ctx context.Context, sessionID, directory, title, tag string) error RecordOperatorSession(ctx context.Context, sessionID, directory, title, tag string) error
// RecordVerificationSession records a chat created for automated verification:
// a real, closable row that OperatorSessions never lists.
RecordVerificationSession(ctx context.Context, sessionID, directory, title, tag string) error
TouchOperatorSession(ctx context.Context, sessionID string) error TouchOperatorSession(ctx context.Context, sessionID string) error
OperatorSessions(ctx context.Context) ([]pipeline.OperatorSession, error) OperatorSessions(ctx context.Context) ([]pipeline.OperatorSession, error)
OperatorDirectories(ctx context.Context, limit int) ([]string, error) OperatorDirectories(ctx context.Context, limit int) ([]string, error)
+19 -4
View File
@@ -90,7 +90,9 @@ func handleChatSessions(ctx context.Context, request protocol.Message, broker ch
// resolved directory, the title and the operator tag. A blank or omitted // resolved directory, the title and the operator tag. A blank or omitted
// directory defaults to the operator's home, never the server's working // directory defaults to the operator's home, never the server's working
// directory. A registry write failure answers an error naming the created id, so // directory. A registry write failure answers an error naming the created id, so
// an orphaned session is visible rather than silently reported as success. // an orphaned session is visible rather than silently reported as success. A
// request with Ephemeral set creates the session without any registry row, for
// automated verification that must never add a chat to the operator's list.
func handleChatCreate(ctx context.Context, request protocol.Message, broker chatBroker, registry operatorRegistry, write func(protocol.Message) error) { func handleChatCreate(ctx context.Context, request protocol.Message, broker chatBroker, registry operatorRegistry, write func(protocol.Message) error) {
if broker == nil { if broker == nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat is not configured on this server"}) _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat is not configured on this server"})
@@ -103,10 +105,12 @@ func handleChatCreate(ctx context.Context, request protocol.Message, broker chat
title := "" title := ""
directory := "" directory := ""
operationID := "" operationID := ""
ephemeral := false
if request.ChatCreate != nil { if request.ChatCreate != nil {
title = strings.TrimSpace(request.ChatCreate.Title) title = strings.TrimSpace(request.ChatCreate.Title)
directory = strings.TrimSpace(request.ChatCreate.Directory) directory = strings.TrimSpace(request.ChatCreate.Directory)
operationID = strings.TrimSpace(request.ChatCreate.OperationID) operationID = strings.TrimSpace(request.ChatCreate.OperationID)
ephemeral = request.ChatCreate.Ephemeral
} }
// Legacy clients did not carry a durable create identity. Give each received // Legacy clients did not carry a durable create identity. Give each received
// request its own server-generated scope so their connection-local envelope // request its own server-generated scope so their connection-local envelope
@@ -182,7 +186,14 @@ func handleChatCreate(ctx context.Context, request protocol.Message, broker chat
chatCreateConflictError(request, err, write) chatCreateConflictError(request, err, write)
return return
} }
if err := registry.RecordOperatorSession(ctx, session.ID, resolved, title, protocol.ChatSessionTagOperator); err != nil { // An ephemeral (verification) create records a real but hidden row: the chat
// stays usable and closable, and chat_sessions never lists it. Everything
// else about the session — its id, skill activation and use — is identical.
record := registry.RecordOperatorSession
if ephemeral {
record = registry.RecordVerificationSession
}
if err := record(ctx, session.ID, resolved, title, protocol.ChatSessionTagOperator); err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + session.ID + " was created but could not be recorded: " + err.Error()}) _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + session.ID + " was created but could not be recorded: " + err.Error()})
return return
} }
@@ -198,8 +209,12 @@ func handleChatCreate(ctx context.Context, request protocol.Message, broker chat
session.Tag = protocol.ChatSessionTagOperator session.Tag = protocol.ChatSessionTagOperator
response := protocol.Message{Type: protocol.ChatCreate, ID: request.ID, ChatSession: &session} response := protocol.Message{Type: protocol.ChatCreate, ID: request.ID, ChatSession: &session}
// The same registry row is echoed on the list field so a client can splice it // The same registry row is echoed on the list field so a client can splice it
// into chat_sessions without a re-list. // into chat_sessions without a re-list. An ephemeral create has no listed row
response.ChatSessions = []protocol.ChatSession{session} // to splice, so that field stays empty and the client that asked for it opens
// the session from the echoed ChatSession instead.
if !ephemeral {
response.ChatSessions = []protocol.ChatSession{session}
}
_ = write(response) _ = write(response)
} }
+54
View File
@@ -1451,6 +1451,60 @@ func TestChatCreateRecordsOperatorSession(t *testing.T) {
} }
} }
func TestChatCreateEphemeralSessionIsNeverListed(t *testing.T) {
store := newOperatorStore(t)
broker := scriptedChat()
broker.created = protocol.ChatSession{ID: "ses_verify", Title: "New chat"}
dir := t.TempDir()
ctx, _, conn := dialChatOptions(t, Options{Chat: broker, OperatorRegistry: store})
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatCreate, ID: "c1", ChatCreate: &protocol.ChatCreateRequest{Title: "New chat", Directory: dir, Ephemeral: true}}); err != nil {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
t.Fatal(err)
}
// The session is real and usable: it is created, bootstrapped and echoed.
if response.Type != protocol.ChatCreate || response.ChatSession == nil || response.ChatSession.ID != "ses_verify" {
t.Fatalf("ephemeral chat_create response = %+v", response)
}
if calls, _, _ := broker.createQuery(); calls != 1 {
t.Fatalf("broker.Create calls = %d, want 1", calls)
}
broker.mu.Lock()
activateCalls := broker.activateCalls
broker.mu.Unlock()
if activateCalls != 1 {
t.Fatalf("manager bootstrap calls = %d, want 1", activateCalls)
}
// No LISTED row was written, so no list row is echoed and chat_sessions cannot
// list the verification chat...
if len(response.ChatSessions) != 0 {
t.Fatalf("ephemeral chat echoed a registry row: %+v", response.ChatSessions)
}
recorded, err := store.OperatorSessions(ctx)
if err != nil {
t.Fatal(err)
}
if len(recorded) != 0 {
t.Fatalf("ephemeral chat recorded %d listed operator session(s): %+v", len(recorded), recorded)
}
// ...but the row is real, so the session stays closable like any other chat.
if _, found, err := store.OperatorSession(ctx, "ses_verify"); err != nil || !found {
t.Fatalf("ephemeral chat is not closable: found=%v err=%v", found, err)
}
if err := store.CloseOperatorSession(ctx, "ses_verify"); err != nil {
t.Fatalf("close ephemeral chat: %v", err)
}
listed, err := store.OperatorSessions(ctx)
if err != nil {
t.Fatal(err)
}
if len(listed) != 0 {
t.Fatalf("closing an ephemeral chat listed it: %+v", listed)
}
}
func TestChatCreateReportsManagerBootstrapFailure(t *testing.T) { func TestChatCreateReportsManagerBootstrapFailure(t *testing.T) {
broker := &fakeChat{created: protocol.ChatSession{ID: "ses_new"}, activateErr: errors.New("skill not found")} broker := &fakeChat{created: protocol.ChatSession{ID: "ses_new"}, activateErr: errors.New("skill not found")}
store := newOperatorStore(t) store := newOperatorStore(t)
+26 -19
View File
File diff suppressed because one or more lines are too long
+908 -63
View File
File diff suppressed because it is too large Load Diff
+416 -1
View File
@@ -16,11 +16,19 @@
// toolLongRunning (the chip and its panel) // toolLongRunning (the chip and its panel)
// ui/chat/ChatListFilter.kt sessionMatchesQuery, filterChatSessions, // ui/chat/ChatListFilter.kt sessionMatchesQuery, filterChatSessions,
// groupChatSessionsByDirectory // 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, // ui/chat/ChatScroll.kt chatBottomDistancePx, chatFollowsAt,
// chatShowJumpToLatest, chatOpensAtNewest, // chatShowJumpToLatest, chatOpensAtNewest,
// chatFirstScroll // chatFirstScroll
// ui/chat/ChatStore.kt the history page merge (dedupe by id, prepend an // ui/chat/ChatStore.kt the history page merge (dedupe by id, prepend an
// older page, replace nextCursor/hasMore) // older page, replace nextCursor/hasMore) and the
// local command notices (append, dismiss one,
// take an offer; ChatCommandNotice)
// ui/chat/ChatCommandUi.kt the Command / Command failed labels and the
// terminal glyph of one local notice line
// ui/chat/ChatComposer.kt composerAction, composerCanSend/composerSendEnabled, // ui/chat/ChatComposer.kt composerAction, composerCanSend/composerSendEnabled,
// the submit routing (command vs prompt) // the submit routing (command vs prompt)
// ui/chat/ChatCommands.kt CHAT_COMMANDS, parseChatInput, chatCommandSuggestions, // ui/chat/ChatCommands.kt CHAT_COMMANDS, parseChatInput, chatCommandSuggestions,
@@ -29,6 +37,10 @@
// ui/chat/ChatFormat.kt attachmentError, attachmentFiles, // ui/chat/ChatFormat.kt attachmentError, attachmentFiles,
// MAX_ATTACHMENT_BYTES, attachmentDisplayName // MAX_ATTACHMENT_BYTES, attachmentDisplayName
// ui/chat/ChatAttachments.kt the attachment display name/error rules // ui/chat/ChatAttachments.kt the attachment display name/error rules
// ui/chat/ChatOverrides.kt ChatSessionOverrides: local titles + hidden ids,
// applied over every server list refresh
// ui/chat/ChatSeen.kt ChatSeenState: the seen watermark and explicit
// unseen marks behind the row's "New" badge
// //
// Nothing here touches the DOM or imports the app: every wording and decision is // Nothing here touches the DOM or imports the app: every wording and decision is
// unit-tested without a browser. The caller sets each server string with // unit-tested without a browser. The caller sets each server string with
@@ -110,6 +122,25 @@ export const CONVERSATION_EMPTY = "This chat has no messages yet. Ask something
export const LOAD_OLDER_ACTION = "Load older messages"; export const LOAD_OLDER_ACTION = "Load older messages";
export const SELECT_CHAT_HINT = "Select a chat to open it."; 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}".` */ /** The listing's narrowed-to-nothing message: `No chats match "{query}".` */
export function chatNoMatchMessage(query) { export function chatNoMatchMessage(query) {
return `No chats match "${str(query).trim()}".`; return `No chats match "${str(query).trim()}".`;
@@ -557,6 +588,264 @@ export function closeChatConfirmation(title) {
); );
} }
// ---------------------------------------------------------------------------
// Local overrides and seen state (ChatOverrides.kt / ChatSeen.kt)
// ---------------------------------------------------------------------------
/** The row menu and the rename dialog, verbatim from ChatListPane.kt. */
export const CHAT_RENAME_ACTION = "Rename…";
export const CHAT_HIDE_ACTION = "Hide on this device";
export const CHAT_ACTIONS_LABEL = "Chat actions";
export const CHAT_REMOVED_MESSAGE = "Hidden on this device; the chat stays on the server.";
export const CHAT_UNDO_ACTION = "Undo";
export const CHAT_RENAME_TITLE = "Rename chat";
export const CHAT_RENAME_FIELD_LABEL = "Name";
export const CHAT_RENAME_HELPER =
"The server has no rename for a chat, so this name is kept on this device.";
export const CHAT_RENAME_SAVE = "Save";
export const CHAT_RENAME_DISMISS = "Cancel";
/** The empty override model: no local titles, nothing hidden. */
export function emptyChatOverrides() {
return { titles: {}, hidden: [] };
}
/** The empty seen model: no watermarks, no explicit unseen marks. */
export function emptyChatSeen() {
return { seenAt: {}, unseen: [] };
}
/** A positive finite epoch-millisecond value, else 0 (never NaN). */
function millis(value) {
const number = Number(value);
return Number.isFinite(number) && number > 0 ? number : 0;
}
/**
* Decode a stored overrides value. Blank text, `null`, corrupt JSON, an array and
* wrong-typed fields all fall back to the empty model; nothing here throws, so a
* bad preference can never break the list.
*/
export function decodeChatOverrides(stored) {
const empty = emptyChatOverrides();
if (stored == null || stored === "") return empty;
let parsed = stored;
if (typeof stored === "string") {
if (stored.trim() === "") return empty;
try {
parsed = JSON.parse(stored);
} catch {
return empty;
}
}
if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed)) return empty;
const titles = {};
const rawTitles = parsed.titles;
if (rawTitles != null) {
if (typeof rawTitles !== "object" || Array.isArray(rawTitles)) return empty;
for (const [id, title] of Object.entries(rawTitles)) {
if (isBlank(id) || typeof title !== "string" || isBlank(title)) continue;
titles[id] = title.trim();
}
}
const hidden = [];
const rawHidden = parsed.hidden;
if (rawHidden != null) {
if (!Array.isArray(rawHidden)) return empty;
for (const id of rawHidden) {
if (typeof id !== "string" || isBlank(id) || hidden.includes(id)) continue;
hidden.push(id);
}
}
return { titles, hidden };
}
/** The one-line JSON an overrides value is stored as. */
export function encodeChatOverrides(overrides) {
return JSON.stringify({
titles: { ...(overrides?.titles ?? {}) },
hidden: [...(overrides?.hidden ?? [])],
});
}
/**
* Decode a stored seen value with the same tolerance as the overrides: blank,
* corrupt or wrong-typed input is nothing seen, never an exception. Unseen ids
* are de-duplicated.
*/
export function decodeChatSeen(stored) {
const empty = emptyChatSeen();
if (stored == null || stored === "") return empty;
let parsed = stored;
if (typeof stored === "string") {
if (stored.trim() === "") return empty;
try {
parsed = JSON.parse(stored);
} catch {
return empty;
}
}
if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed)) return empty;
const seenAt = {};
const rawSeenAt = parsed.seenAt;
if (rawSeenAt != null) {
if (typeof rawSeenAt !== "object" || Array.isArray(rawSeenAt)) return empty;
for (const [id, value] of Object.entries(rawSeenAt)) {
const at = millis(value);
if (isBlank(id) || at <= 0) continue;
seenAt[id] = at;
}
}
const unseen = [];
const rawUnseen = parsed.unseen;
if (rawUnseen != null) {
if (!Array.isArray(rawUnseen)) return empty;
for (const id of rawUnseen) {
if (typeof id !== "string" || isBlank(id) || unseen.includes(id)) continue;
unseen.push(id);
}
}
return { seenAt, unseen };
}
/** The one-line JSON a seen value is stored as. */
export function encodeChatSeen(seen) {
return JSON.stringify({
seenAt: { ...(seen?.seenAt ?? {}) },
unseen: [...(seen?.unseen ?? [])],
});
}
/**
* Record a local rename. A blank id or a title that is blank after trimming
* changes nothing; a recorded title is trimmed, and it wins over the server's
* own on every later refresh.
*/
export function renameChatOverride(overrides, id, title) {
const current = overrides ?? emptyChatOverrides();
const trimmed = str(title).trim();
const key = str(id);
if (isBlank(key) || trimmed === "") return current;
if (current.titles?.[key] === trimmed) return current;
return { ...current, titles: { ...(current.titles ?? {}), [key]: trimmed } };
}
/**
* Hide a session on this device. A blank id or an already-hidden id changes
* nothing, and an id is never appended twice.
*/
export function hideChatOverride(overrides, id) {
const current = overrides ?? emptyChatOverrides();
const key = str(id);
const hidden = current.hidden ?? [];
if (isBlank(key) || hidden.includes(key)) return current;
return { ...current, hidden: [...hidden, key] };
}
/** Restore a hidden session, undoing [hideChatOverride]. */
export function restoreChatOverride(overrides, id) {
const current = overrides ?? emptyChatOverrides();
const key = str(id);
const hidden = current.hidden ?? [];
if (!hidden.includes(key)) return current;
return { ...current, hidden: hidden.filter((entry) => entry !== key) };
}
/**
* The server's sessions with this device's overrides applied: hidden ids are
* removed (the set is built once, so each row is O(1)) and a local title replaces
* the server's. A blank/absent server title still falls through to
* `sessionTitle` at render time.
*/
export function applyChatOverrides(sessions, overrides) {
const list = Array.isArray(sessions) ? sessions : [];
const titles = overrides?.titles ?? {};
const hiddenIds = new Set(overrides?.hidden ?? []);
if (hiddenIds.size === 0 && Object.keys(titles).length === 0) return list;
return list
.filter((session) => !hiddenIds.has(str(session?.id)))
.map((session) => {
const local = titles[str(session?.id)];
return typeof local === "string" && local.trim() !== ""
? { ...session, title: local.trim() }
: session;
});
}
/** The newest recency the operator has seen for [id], or 0 when never seen. */
export function chatSeenWatermark(seen, id) {
const value = seen?.seenAt?.[str(id)];
return millis(value);
}
/**
* Record the first sight of every listed session, so a pre-existing chat is not
* reported as new activity. The active session is read (it is on screen); every
* other session is seeded only when it has no watermark yet and its recency is a
* real timestamp. An explicit unseen mark is never cleared by seeding.
*/
export function seedChatSeen(seen, sessions, activeId) {
let next = seen ?? emptyChatSeen();
for (const session of Array.isArray(sessions) ? sessions : []) {
const id = str(session?.id);
const updatedAt = millis(session?.updated_at);
if (isBlank(id) || updatedAt <= 0) continue;
if (id === str(activeId)) {
next = readChatSeen(next, id, updatedAt);
} else if (chatSeenWatermark(next, id) === 0) {
next = { ...next, seenAt: { ...(next.seenAt ?? {}), [id]: updatedAt } };
}
}
return next;
}
/**
* Read [id] up to [updatedAt]: the watermark advances only when the value is
* strictly newer (a stale read can never rewind it) and any explicit unseen mark
* is cleared. A blank id changes nothing.
*/
export function readChatSeen(seen, id, updatedAt) {
const current = seen ?? emptyChatSeen();
const key = str(id);
if (isBlank(key)) return current;
const at = millis(updatedAt);
const advanced = at > chatSeenWatermark(current, key);
const unseen = current.unseen ?? [];
const marked = unseen.includes(key);
if (!advanced && !marked) return current;
return {
seenAt: advanced ? { ...(current.seenAt ?? {}), [key]: at } : { ...(current.seenAt ?? {}) },
unseen: marked ? unseen.filter((entry) => entry !== key) : [...unseen],
};
}
/** Mark [id] as moved on while it was not on screen; blank ids and duplicates no-op. */
export function markChatUnseen(seen, id) {
const current = seen ?? emptyChatSeen();
const key = str(id);
const unseen = current.unseen ?? [];
if (isBlank(key) || unseen.includes(key)) return current;
return { ...current, seenAt: { ...(current.seenAt ?? {}) }, unseen: [...unseen, key] };
}
/**
* The exact `ChatState.isUnseen` rule: a session is new only when it is not the
* active one and either an explicit unseen mark exists or it has never been
* opened here and its `updated_at` is strictly newer than the stored watermark.
*/
export function isChatSessionUnseen(session, { activeId = null, seen = null, opened = false } = {}) {
const id = str(session?.id);
if (isBlank(id) || id === str(activeId)) return false;
if ((seen?.unseen ?? []).includes(id)) return true;
if (opened) return false;
return millis(session?.updated_at) > chatSeenWatermark(seen, id);
}
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// Session narrowing and grouping (ChatListFilter.kt) // Session narrowing and grouping (ChatListFilter.kt)
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
@@ -606,6 +895,78 @@ export function directoryLabel(directory) {
return isBlank(directory) ? NO_DIRECTORY_LABEL : str(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) // Transcript (ChatFormat.kt)
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
@@ -1362,6 +1723,60 @@ export const CHAT_QUEUED_NOTICE = "Queued — it will send when the current turn
*/ */
export const CHAT_COMMAND_GLYPH = ">_"; export const CHAT_COMMAND_GLYPH = ">_";
/** The two labels a local command line can carry (ChatCommandUi.kt). */
export const CHAT_COMMAND_LABEL = "Command";
export const CHAT_COMMAND_FAILED_LABEL = "Command failed";
/** The accessible name of an offerless notice's dismiss control. */
export const CHAT_COMMAND_DISMISS_LABEL = "Dismiss command notice";
/**
* The label for one command notice: `Command failed` when the command could not
* be honoured, else `Command` (ChatCommandUi.kt's own choice). The same flag
* selects the error tint on the caller's row.
*/
export function chatNoticeLabel(failed) {
return failed === true ? CHAT_COMMAND_FAILED_LABEL : CHAT_COMMAND_LABEL;
}
/**
* One local command line, the app's `ChatCommandNotice` shape: it lives beside a
* conversation, never inside its messages, so it is never sent to the agent.
* [offer] is set only for an unrecognised command, whose draft the operator can
* still choose to send as a message.
*/
export function makeChatNotice(id, text, { failed = false, offer = null } = {}) {
return {
id: str(id),
text: str(text),
failed: failed === true,
offer: offer == null ? null : str(offer),
};
}
/** Append one notice to a conversation's list, preserving order. */
export function appendChatNotice(notices, notice) {
return [...(notices ?? []), notice];
}
/** Drop one notice by id, leaving every other notice and its order untouched. */
export function dismissChatNotice(notices, noticeId) {
return (notices ?? []).filter((notice) => notice?.id !== noticeId);
}
/**
* Take the draft an unrecognised-command notice offers, removing the notice
* first (mirrors `ChatStore.takeNoticeOffer`). Returns `{notices, offer}`:
* `offer` is null — and the list is returned untouched — when the notice is
* missing, already taken or carries no offer, so a stale tap sends nothing.
*/
export function takeChatNoticeOffer(notices, noticeId) {
const list = notices ?? [];
const notice = list.find((entry) => entry?.id === noticeId);
if (!notice || notice.offer == null) return { notices: list, offer: null };
return { notices: dismissChatNotice(list, noticeId), offer: notice.offer };
}
/** The two values of [composerAction]. */ /** The two values of [composerAction]. */
export const COMPOSER_SEND = "send"; export const COMPOSER_SEND = "send";
export const COMPOSER_STOP = "stop"; export const COMPOSER_STOP = "stop";
+315
View File
@@ -0,0 +1,315 @@
// Pure, DOM-free notification model for failed/waiting runs (L5). It mirrors
// android/.../notify/RunAlerts.kt: the same two qualifying kinds, the same
// headlines, the same run line and the same one-notification-per-run+kind rule.
//
// Everything here is pure: no DOM, no clock, no storage access. The page owns
// the Notification constructor, the permission request gesture and localStorage;
// the unit tests own the state machine. The attention model in `attention.js`
// is the single authority for which runs qualify and for the dismissal identity,
// so the in-page "Needs you" surface and the tray can never disagree.
import { AttentionKind, attentionKey, attentionKindOf } from "./attention.js";
// ---------------------------------------------------------------------------
// Kinds, headlines and the run line
// ---------------------------------------------------------------------------
/** The two run events that raise a notification (RunAlerts.kt RunAlertKind). */
export const RunAlertKind = Object.freeze({
Decision: AttentionKind.Decision,
Failed: AttentionKind.Failed,
});
/** `alertKindOf`: an attention kind is already exactly the notification kind. */
export function alertKindOf(kind) {
if (kind === AttentionKind.Decision || kind?.name === AttentionKind.Decision.name) {
return AttentionKind.Decision;
}
if (kind === AttentionKind.Failed || kind?.name === AttentionKind.Failed.name) {
return AttentionKind.Failed;
}
return null;
}
/** The short headline one kind shows (RunAlerts.alertTitle). */
export function alertTitle(kind) {
switch (alertKindOf(kind)?.name) {
case "Decision":
return "A run needs your decision";
case "Failed":
return "A run failed";
default:
return "";
}
}
/** The stable run+kind identity, the unit of dedupe (RunAlerts.alertKey). */
export function alertKey(runId, kind) {
const resolved = alertKindOf(kind);
return resolved ? attentionKey(runId, resolved) : "";
}
/**
* The line naming the run (RunAlerts.alertText): the attention label, then the
* pipeline it belongs to. The label is the run's trimmed title, falling back to
* the pipeline name; a blank or equal pipeline is never repeated, so there is no
* trailing separator.
*/
export function alertBody(run) {
const pipeline = String(run?.pipeline ?? run?.name ?? "");
const title = String(run?.label ?? run?.title ?? "").trim();
const label = title !== "" ? title : pipeline;
if (pipeline === "" || pipeline === label) return label;
return `${label} \u00b7 ${pipeline}`;
}
// ---------------------------------------------------------------------------
// The ledger: seed, observe, dedupe
// ---------------------------------------------------------------------------
/**
* Tracks the last status seen for every run and the run+kind alerts already
* raised in this page session.
*
* - `seed(runs)` records the authoritative list without raising anything, so a
* run that was already failed/waiting when the page loaded (or when the socket
* reconnected) never notifies.
* - `beginSeed()`/`endSeed()` bracket the `subscribe` snapshot: the server writes
* the current state of every watched run before its ack, and those frames are
* seeds too, not transitions.
* - `observe(frame)` raises only when a known run's status changes *into*
* `failed` or `waiting`. A duplicate frame (same status), an unchanged
* qualifying state, an unknown status and a first-seen run all return null.
* - A run+kind key is forgotten when the run leaves that qualifying state, so a
* genuinely new transition (for example failed -> running -> failed again) can
* notify once more; the same transition can never repeat.
* - A key present in the attention surface's dismissed set is suppressed. The
* dismissal is the attention model's own `{runId}:{kind}` identity.
* - `reset()` drops the status baseline on a socket drop but keeps the notified
* keys, so a gap that swallows a transition cannot raise a notification after
* the reconnect; the next seed establishes the new baseline.
*/
export function createAlertLedger() {
const lastStatus = new Map();
const notified = new Set();
let seeding = false;
function seed(runs) {
const next = new Map();
for (const run of runs ?? []) {
const runId = runIdOf(run?.id ?? run?.run_id);
if (runId == null) continue;
next.set(runId, normalizeStatus(run?.status));
}
lastStatus.clear();
for (const [runId, status] of next) lastStatus.set(runId, status);
pruneNotified(next);
}
function observe(frame, { dismissed } = {}) {
const runId = runIdOf(frame?.run_id ?? frame?.runId ?? frame?.id);
const status = normalizeStatus(frame?.status);
if (runId == null || status === "") return null;
const previous = lastStatus.get(runId);
lastStatus.set(runId, status);
const kind = attentionKindOf(status);
if (!kind) {
forget(runId, AttentionKind.Decision);
forget(runId, AttentionKind.Failed);
return null;
}
// A run can only be in one qualifying state; forget the other kind's key so
// a later transition back into it is a new event.
forget(runId, kind === AttentionKind.Decision ? AttentionKind.Failed : AttentionKind.Decision);
if (seeding) return null;
if (previous === undefined || previous === status) return null;
const key = alertKey(runId, kind);
if (notified.has(key)) return null;
notified.add(key);
const dismissedKeys =
dismissed instanceof Set ? dismissed : new Set(Array.isArray(dismissed) ? dismissed : []);
if (dismissedKeys.has(key)) return null;
return {
runId,
kind,
key,
title: alertTitle(kind),
body: alertBody(frame),
};
}
function reset() {
lastStatus.clear();
seeding = false;
}
function beginSeed() {
seeding = true;
}
function endSeed() {
seeding = false;
}
function forget(runId, kind) {
const key = alertKey(runId, kind);
if (key !== "") notified.delete(key);
}
function pruneNotified(statuses) {
for (const key of [...notified]) {
const split = key.lastIndexOf(":");
if (split < 0) continue;
const runId = runIdOf(key.slice(0, split));
const kindName = key.slice(split + 1);
const status = runId == null ? undefined : statuses.get(runId);
// A run that is absent from this read tells us nothing; keep its key.
if (status === undefined) continue;
const kind = attentionKindOf(status);
if (!kind || kind.name !== kindName) notified.delete(key);
}
}
return {
seed,
observe,
reset,
beginSeed,
endSeed,
/** Test/introspection helper; returns a copy, never the live set. */
notifiedKeys: () => [...notified],
statusOf: (runId) => lastStatus.get(runIdOf(runId)),
};
}
/** Trim/lowercase the server's status word; an absent value is "". */
function normalizeStatus(status) {
return String(status ?? "").trim().toLowerCase();
}
/** A positive run id as a number, or null for anything malformed. */
function runIdOf(value) {
const id = Number(value);
return Number.isFinite(id) && id > 0 ? id : null;
}
// ---------------------------------------------------------------------------
// Permission wording and persistence
// ---------------------------------------------------------------------------
/** Android's NOTIFICATION_RATIONALE, verbatim (RunAlerts.kt). */
export const NOTIFICATION_RATIONALE =
"Pipelines can notify you when a run is waiting for your decision or has failed. " +
"Without it, those runs still appear in the in-app Needs you surface.";
/** The explicit-gesture control's label; shown only when a request is possible. */
export const NOTIFICATION_REQUEST_LABEL = "Enable notifications";
export const NOTIFICATION_UNSUPPORTED =
"This browser does not support notifications. The in-app Needs you surface is the only channel.";
export const NOTIFICATION_INSECURE =
"Notifications need a secure context (https or localhost). This page is not secure, so the " +
"in-app Needs you surface is the only channel.";
export const NOTIFICATION_GRANTED =
"Notifications are on. Failed and waiting runs will raise a browser notification.";
export const NOTIFICATION_DENIED =
"Notifications are blocked for this site. Allow them in the browser's site settings to use them; " +
"until then the in-app Needs you surface is the only channel.";
export const NOTIFICATION_DEFAULT =
"Notifications are off. Enable them to be told when a run fails or needs your decision.";
export const NOTIFICATION_DEFAULT_ASKED =
"Notifications are still off. Your browser did not grant permission when asked; you can ask " +
"again, or the in-app Needs you surface remains the only channel.";
/**
* The total permission view for Settings. `supported` and `secureContext` are
* the browser's own facts; `permission` is the Notification API's own word
* (`default` | `granted` | `denied`, anything else treated as default).
*
* Only a supported, secure page whose permission is still `default` offers the
* request control. The request is always an explicit user gesture; nothing here
* asks on its own, and the `asked` flag only changes the honest wording.
*/
export function notificationPermissionState({
supported = true,
secureContext = true,
permission = "default",
asked = false,
} = {}) {
const state = !supported
? "unsupported"
: !secureContext
? "insecure"
: permission === "granted"
? "granted"
: permission === "denied"
? "denied"
: "default";
const canRequest = state === "default";
let body = NOTIFICATION_DEFAULT;
switch (state) {
case "unsupported":
body = NOTIFICATION_UNSUPPORTED;
break;
case "insecure":
body = NOTIFICATION_INSECURE;
break;
case "granted":
body = NOTIFICATION_GRANTED;
break;
case "denied":
body = NOTIFICATION_DENIED;
break;
default:
body = asked ? NOTIFICATION_DEFAULT_ASKED : NOTIFICATION_DEFAULT;
}
return {
state,
body,
canRequest,
actionLabel: canRequest ? NOTIFICATION_REQUEST_LABEL : null,
asked: Boolean(asked),
};
}
/**
* The browser facts the permission view needs. Pure enough to unit-test with a
* fake scope; the real page passes `globalThis`. An unrecognised permission
* value is read as `default` rather than guessed.
*/
export function notificationEnvironment(scope = globalThis) {
const ctor = scope?.Notification;
const supported = typeof ctor === "function";
const raw = supported ? ctor.permission : "default";
const permission = raw === "granted" || raw === "denied" ? raw : "default";
return { supported, secureContext: scope?.isSecureContext === true, permission };
}
/** The one localStorage key for this page's notification preference. */
export const NOTIFY_STORAGE_KEY = "pipelines.web.notify.v1";
/** Encode only the asked flag; no endpoint, credential or permission claim. */
export function encodeNotificationSettings(settings) {
return JSON.stringify({ asked: Boolean(settings?.asked) });
}
/**
* Decode the stored preference. Total: blank, unreadable JSON, a non-object, a
* non-boolean or a throwing getter all mean "never asked", so a malformed value
* can never throw into the page or claim the operator was asked.
*/
export function decodeNotificationSettings(stored) {
const text = stored == null ? "" : String(stored).trim();
if (text === "") return { asked: false };
let parsed;
try {
parsed = JSON.parse(text);
} catch {
return { asked: false };
}
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return { asked: false };
return { asked: parsed.asked === true };
}
+15
View File
@@ -27,6 +27,14 @@ export const Protocol = Object.freeze({
GET_RUN: "get_run", GET_RUN: "get_run",
RUN: "run", RUN: "run",
// Live run state (internal/protocol/runevents.go, L5/R10). `subscribe` sends
// the current state of the watched runs as `run_event` frames and then a
// compact delta on each transition; `unsubscribe` stops the watch. The page
// uses the frames for run notifications without changing R10's runs-list fold.
SUBSCRIBE: "subscribe",
UNSUBSCRIBE: "unsubscribe",
RUN_EVENT: "run_event",
// Omni-search (internal/protocol/search.go): the command and its reply type. // Omni-search (internal/protocol/search.go): the command and its reply type.
// The per-kind payloads and the kind/limit vocabulary live in src/search.js. // The per-kind payloads and the kind/limit vocabulary live in src/search.js.
SEARCH: "search", SEARCH: "search",
@@ -64,6 +72,10 @@ export const Protocol = Object.freeze({
CHAT_PROMPT: "chat_prompt", CHAT_PROMPT: "chat_prompt",
CHAT_INTERRUPT: "chat_interrupt", CHAT_INTERRUPT: "chat_interrupt",
CHAT_CREATE: "chat_create", 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 // The approval card (C10): the server pushes `chat_permission` frames (one
// pending request, later re-pushed with the resolution) and the phone answers // pending request, later re-pushed with the resolution) and the phone answers
// with `chat_reply` (internal/protocol/chat.go ChatPermission/ChatReply). // with `chat_reply` (internal/protocol/chat.go ChatPermission/ChatReply).
@@ -102,6 +114,9 @@ export const ChatKeys = Object.freeze({
// separate field name here would put it on the wrong part of the envelope. // separate field name here would put it on the wrong part of the envelope.
PROMPT: "chat_prompt", PROMPT: "chat_prompt",
CREATE: "chat_create", 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", QUEUED: "chat_queued",
// C10: the pushed approval frame (`chat_permission`) and the answer body // C10: the pushed approval frame (`chat_permission`) and the answer body
// (`chat_reply`), both distinct Message fields in internal/protocol/message.go. // (`chat_reply`), both distinct Message fields in internal/protocol/message.go.
+37 -2
View File
@@ -115,6 +115,24 @@ export class PipelinesRepository {
return response.run_detail; return response.run_detail;
} }
/**
* Watches run state (L5), mirroring `PipelinesRepository.subscribeRuns` for the
* blank "any workspace" scope the runs list shows: exactly `{type:'subscribe',
* workspace:''}` and no `run_ids` (an empty list would watch the whole scope,
* but omitting the field is the shape the Android client sends). The server
* replies with the current state of every matching run as unsolicited
* `run_event` frames, then an id-matched ack, then deltas. Awaiting the ack is
* how the page knows the snapshot has been delivered.
*/
async subscribeRuns() {
return this.#client.call({ type: Protocol.SUBSCRIBE, workspace: "" });
}
/** Stops this connection's run-state watch. Best effort; a disconnect drops it. */
async unsubscribeRuns() {
return this.#client.call({ type: Protocol.UNSUBSCRIBE });
}
/** /**
* Omni-search. Sends exactly `SearchRequest{query, kind, limit}` from * Omni-search. Sends exactly `SearchRequest{query, kind, limit}` from
* internal/protocol/search.go: `kind` is the empty string for every kind, and * internal/protocol/search.go: `kind` is the empty string for every kind, and
@@ -383,17 +401,34 @@ 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 * Creates one session in an explicit directory (mirrors
* `PipelinesRepository.chatCreate`). The directory is always sent, so a chat is * `PipelinesRepository.chatCreate`). The directory is always sent, so a chat is
* never created in whatever directory the server happens to be running in. The * never created in whatever directory the server happens to be running in. The
* reply's `chat_session` is returned, or a `ProtocolError` when the server did * reply's `chat_session` is returned, or a `ProtocolError` when the server did
* not return one. * not return one.
*
* `ephemeral` creates a verification chat: the server makes and bootstraps the
* session but records no operator-registry row, so the chat never appears in
* `chat_sessions` for the operator. Automated checks that drive this real page
* set it, so a run can never leave a stray "New chat" in the operator's list.
*/ */
async chatCreate(title, directory, operationId = newChatOperationId()) { async chatCreate(title, directory, operationId = newChatOperationId(), { ephemeral = false } = {}) {
const response = await this.#client.call({ const response = await this.#client.call({
type: Protocol.CHAT_CREATE, type: Protocol.CHAT_CREATE,
[ChatKeys.CREATE]: { title, directory, operation_id: operationId }, [ChatKeys.CREATE]: { title, directory, operation_id: operationId, ...(ephemeral ? { ephemeral: true } : {}) },
}); });
const session = response[ChatKeys.SESSION]; const session = response[ChatKeys.SESSION];
if (!session) { if (!session) {
+141 -2
View File
@@ -1437,7 +1437,76 @@ code { background: var(--surface-2); padding: 1px 6px; border-radius: 6px; font-
--------------------------------------------------------------------------- */ --------------------------------------------------------------------------- */
.chat-list { display: flex; flex-direction: column; } .chat-list { display: flex; flex-direction: column; }
/* A row's Chat actions menu hangs below the button. `.list` clips its children
for the rounded corners, which cut the panel off at the list's bottom edge and
made the final rows' Hide/Rename items unclickable. Unclip only while a menu is
open, mirroring `.list.runs`' filter-menu treatment. */
.chat-list.menu-open { overflow: visible; }
.chat-search { flex: 1 1 auto; min-width: 0; } .chat-search { flex: 1 1 auto; min-width: 0; }
.chat-toolbar .chat-new { white-space: nowrap; }
/* C2: the create pane — the directory picker, the model note and the footer that
names the value chat_create will send. */
.chat-create { gap: 12px; }
.chat-bar.chat-create-bar { align-items: center; justify-content: flex-start; gap: 10px; }
.chat-create-back {
display: inline-flex;
align-items: center;
justify-content: center;
width: 32px;
height: 32px;
padding: 0;
flex: none;
}
.chat-create-back-glyph { font-size: 16px; line-height: 1; }
.detail .chat-create-title { margin: 0; }
.chat-create-loading { padding: 18px 4px; }
.chat-create-prompt { padding: 2px 2px 0; font-size: 13px; }
.chat-create-choices {
display: flex;
flex-direction: column;
border: 1px solid var(--border);
border-radius: 10px;
overflow: hidden;
}
.chat-create-choice { cursor: pointer; }
.chat-create-choice-path {
font-family: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace;
font-size: 11px;
}
.chat-create-directories-error { color: var(--bad); }
.chat-create-error { color: var(--bad); font-size: 13px; }
.chat-create-model-note { margin: 0; font-size: 12px; line-height: 1.5; max-width: 64ch; }
.chat-create-footer {
display: flex;
gap: 10px;
align-items: center;
margin-top: auto;
padding: 12px;
background: var(--surface-2);
border: 1px solid var(--border);
border-radius: 10px;
}
.chat-create-start {
flex: 1 1 auto;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: 13px;
}
.chat-create-confirm {
min-width: 88px;
display: inline-flex;
align-items: center;
justify-content: center;
border-color: var(--accent);
color: var(--accent);
font-weight: 600;
}
.chat-create-confirm:disabled,
.chat-create-cancel:disabled { opacity: 0.55; }
.chat-create-spinner { width: 14px; height: 14px; border-width: 2px; }
.chat-group-header { .chat-group-header {
padding: 8px 12px 4px; padding: 8px 12px 4px;
@@ -1460,10 +1529,67 @@ code { background: var(--surface-2); padding: 1px 6px; border-radius: 6px; font-
.chat-row .row-meta { grid-column: 1; } .chat-row .row-meta { grid-column: 1; }
.chat-row-actions { grid-column: 2; grid-row: 1 / span 2; align-self: center; } .chat-row-actions { grid-column: 2; grid-row: 1 / span 2; align-self: center; }
.chat-row-actions button { padding: 3px 10px; font-size: 12px; } .chat-row-actions button { padding: 3px 10px; font-size: 12px; }
.chat-close { border-color: var(--warn); color: var(--warn); } .chat-menu-wrap { position: relative; }
.chat-reopen { border-color: var(--accent); color: var(--accent); } .chat-menu-button { min-width: 30px; font-size: 15px; line-height: 1; }
.chat-menu-panel {
position: absolute;
top: calc(100% + 4px);
right: 0;
z-index: 25;
display: grid;
min-width: 190px;
padding: 4px;
background: var(--surface-2);
border: 1px solid var(--border);
border-radius: 10px;
box-shadow: 0 16px 40px rgba(0, 0, 0, 0.5);
}
.chat-menu-item {
justify-content: flex-start;
padding: 7px 10px;
text-align: left;
font-size: 13px;
border: none;
white-space: nowrap;
}
.chat-menu-item:hover { background: var(--surface); }
.chat-menu-close { color: var(--warn); }
.chat-menu-reopen { color: var(--accent); }
.chat-closed-chip { opacity: 0.8; } .chat-closed-chip { opacity: 0.8; }
/* The Rename chat dialog (C13): a name kept on this device only. */
.chat-rename-field { display: grid; gap: 4px; }
.chat-rename-label { font-size: 12px; color: var(--muted); }
.chat-rename-helper { margin: 0; line-height: 1.5; font-size: 13px; color: var(--muted); }
.chat-rename-save:disabled { opacity: 0.5; }
/* The one hide report (C13): fixed above the pane, replaced rather than queued. */
.chat-snackbar {
position: fixed;
left: 50%;
bottom: 20px;
z-index: 35;
transform: translateX(-50%);
display: flex;
gap: 16px;
align-items: center;
max-width: min(560px, calc(100vw - 32px));
padding: 12px 16px;
background: var(--surface-2);
border: 1px solid var(--border);
border-radius: 10px;
box-shadow: 0 16px 40px rgba(0, 0, 0, 0.55);
font-size: 13px;
}
.chat-snackbar-message { line-height: 1.4; }
.chat-snackbar-undo {
flex: none;
border-color: var(--accent);
color: var(--accent);
font-weight: 600;
font-size: 13px;
}
.chat-activity { display: inline-flex; align-items: center; gap: 5px; font-size: 11px; color: var(--muted); } .chat-activity { display: inline-flex; align-items: center; gap: 5px; font-size: 11px; color: var(--muted); }
.chat-activity-dot { width: 7px; height: 7px; border-radius: 50%; background: currentColor; } .chat-activity-dot { width: 7px; height: 7px; border-radius: 50%; background: currentColor; }
.chat-activity-streaming { color: var(--accent); } .chat-activity-streaming { color: var(--accent); }
@@ -2031,6 +2157,19 @@ code { background: var(--surface-2); padding: 1px 6px; border-radius: 6px; font-
} }
.settings-warning-title { margin: 0; font-weight: 600; color: var(--bad); } .settings-warning-title { margin: 0; font-weight: 600; color: var(--bad); }
.settings-warning-body { margin: 0; font-size: 12.5px; color: var(--muted); } .settings-warning-body { margin: 0; font-size: 12.5px; color: var(--muted); }
.settings-notify-state {
margin: 0;
border: 1px solid var(--border);
border-radius: 10px;
background: var(--surface-2);
padding: 12px 14px;
font-size: 13px;
color: var(--muted);
}
.settings-notify-granted { border-color: color-mix(in srgb, var(--ok) 45%, var(--border)); color: var(--ok); }
.settings-notify-denied,
.settings-notify-insecure,
.settings-notify-unsupported { color: var(--warn); }
.settings-saved { margin: 0; font-size: 12px; color: var(--muted); } .settings-saved { margin: 0; font-size: 12px; color: var(--muted); }
.settings-save { justify-self: start; } .settings-save { justify-self: start; }
.settings-card { .settings-card {
+425
View File
@@ -7,10 +7,30 @@ import assert from "node:assert/strict";
import { import {
BACKGROUND_TASKS_TITLE, BACKGROUND_TASKS_TITLE,
BACKGROUND_TASK_VISIBLE_ROWS, BACKGROUND_TASK_VISIBLE_ROWS,
CHAT_ACTIONS_LABEL,
CHAT_COMMANDS, CHAT_COMMANDS,
CHAT_COMMAND_DISMISS_LABEL,
CHAT_COMMAND_FAILED_LABEL,
CHAT_COMMAND_GLYPH, 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_FOLLOW_THRESHOLD_PX,
CHAT_HIDE_ACTION,
CHAT_QUEUED_NOTICE, CHAT_QUEUED_NOTICE,
CHAT_REMOVED_MESSAGE,
CHAT_RENAME_ACTION,
CHAT_RENAME_DISMISS,
CHAT_RENAME_FIELD_LABEL,
CHAT_RENAME_HELPER,
CHAT_RENAME_SAVE,
CHAT_RENAME_TITLE,
CHAT_UNDO_ACTION,
COMPOSER_SEND, COMPOSER_SEND,
COMPOSER_STOP, COMPOSER_STOP,
ChatTurn, ChatTurn,
@@ -48,7 +68,9 @@ import {
TURN_PHASE_TOOL, TURN_PHASE_TOOL,
TURN_PHASE_WAITING, TURN_PHASE_WAITING,
TURN_THINKING_WINDOW_MILLIS, TURN_THINKING_WINDOW_MILLIS,
appendChatNotice,
applyChatEvent, applyChatEvent,
applyChatOverrides,
applyChatPermission, applyChatPermission,
approvalCard, approvalCard,
approvalResources, approvalResources,
@@ -56,18 +78,25 @@ import {
attachmentDisplayName, attachmentDisplayName,
attachmentError, attachmentError,
attachmentFiles, attachmentFiles,
HOME_DIRECTORY,
HOME_LABEL,
backgroundTasksRunningLabel, backgroundTasksRunningLabel,
chatBottomDistancePx, chatBottomDistancePx,
chatCommandEffect, chatCommandEffect,
chatCommandForEnter, chatCommandForEnter,
chatCommandHelp, chatCommandHelp,
chatCommandSuggestions, chatCommandSuggestions,
chatCreateFailed,
chatCreateSucceeded,
chatFirstScroll, chatFirstScroll,
chatFollowsAt, chatFollowsAt,
chatHeaderMeta, chatHeaderMeta,
chatNoMatchMessage, chatNoMatchMessage,
chatNoticeLabel,
chatOpensAtNewest, chatOpensAtNewest,
chatSeenWatermark,
chatShowJumpToLatest, chatShowJumpToLatest,
chatStartInLabel,
chatStreamState, chatStreamState,
closeChatConfirmation, closeChatConfirmation,
composerAction, composerAction,
@@ -75,28 +104,47 @@ import {
composerSendEnabled, composerSendEnabled,
composerSubmit, composerSubmit,
decisionLabel, decisionLabel,
decodeChatOverrides,
decodeChatSeen,
defaultDirectoryChoice,
deltaPartId, deltaPartId,
directoryChoices,
directoryLabel, directoryLabel,
dismissChatNotice,
emptyChatOverrides,
emptyChatSeen,
encodeChatOverrides,
encodeChatSeen,
filterSessions, filterSessions,
formatToolDuration, formatToolDuration,
groupSessionsByDirectory, groupSessionsByDirectory,
hideChatOverride,
historyResync, historyResync,
isChatSessionUnseen,
lineDiff, lineDiff,
makeChatNotice,
markChatUnseen,
mergeHistoryPage, mergeHistoryPage,
mergeShellFrame, mergeShellFrame,
mergeToolPart, mergeToolPart,
newChatCreateState,
newChatThread, newChatThread,
parseChatInput, parseChatInput,
partRendering, partRendering,
permissionRiskText, permissionRiskText,
prettyToolInput, prettyToolInput,
queuedAfterFrame, queuedAfterFrame,
readChatSeen,
reasoningLabel, reasoningLabel,
renameChatOverride,
restoreChatOverride,
resumedThread, resumedThread,
runningAfterFrame, runningAfterFrame,
runningBackgroundShells, runningBackgroundShells,
runningToolElapsedMillis, runningToolElapsedMillis,
runningToolStamps, runningToolStamps,
seedChatSeen,
selectChatDirectory,
sessionActivity, sessionActivity,
sessionActivityBadge, sessionActivityBadge,
sessionChipLabel, sessionChipLabel,
@@ -109,6 +157,7 @@ import {
shellCommandSummary, shellCommandSummary,
shellOutputState, shellOutputState,
shellsLoaded, shellsLoaded,
takeChatNoticeOffer,
threadElapsedMillis, threadElapsedMillis,
threadPhase, threadPhase,
threadRunningTools, threadRunningTools,
@@ -833,6 +882,103 @@ test("a command notice carries one terminal glyph for both states", () => {
assert.equal(CHAT_COMMAND_GLYPH, ">_"); assert.equal(CHAT_COMMAND_GLYPH, ">_");
}); });
// ---------------------------------------------------------------------------
// Local command notices (C12) — ChatStore.kt notice/dismissNotice/takeNoticeOffer
// and ChatCommandUi.kt's labels
// ---------------------------------------------------------------------------
test("chatNoticeLabel names a command and its failure", () => {
assert.equal(CHAT_COMMAND_LABEL, "Command");
assert.equal(CHAT_COMMAND_FAILED_LABEL, "Command failed");
assert.equal(chatNoticeLabel(false), "Command");
assert.equal(chatNoticeLabel(true), "Command failed");
// Anything that is not the literal failed flag keeps the ordinary label.
assert.equal(chatNoticeLabel(undefined), "Command");
assert.equal(chatNoticeLabel("failed"), "Command");
});
test("the offerless notice's dismiss control has an accessible name", () => {
assert.equal(CHAT_COMMAND_DISMISS_LABEL, "Dismiss command notice");
});
test("makeChatNotice keeps the id, text, failure flag and offer", () => {
assert.deepEqual(makeChatNotice("notice-1", "No turn is running in this chat."), {
id: "notice-1",
text: "No turn is running in this chat.",
failed: false,
offer: null,
});
assert.deepEqual(
makeChatNotice("notice-2", "Started a new session.", { failed: true, offer: "/nope" }),
{ id: "notice-2", text: "Started a new session.", failed: true, offer: "/nope" },
);
});
test("appendChatNotice appends one notice and preserves order", () => {
const first = makeChatNotice("notice-1", "Command one");
const second = makeChatNotice("notice-2", "Command two", { failed: true });
const afterFirst = appendChatNotice([], first);
const afterSecond = appendChatNotice(afterFirst, second);
assert.deepEqual(afterSecond, [first, second]);
// The previous list is never mutated.
assert.deepEqual(afterFirst, [first]);
assert.deepEqual(appendChatNotice(undefined, first), [first]);
});
test("dismissChatNotice removes exactly the named notice", () => {
const first = makeChatNotice("notice-1", "Command one");
const second = makeChatNotice("notice-2", "Command two", { failed: true });
const third = makeChatNotice("notice-3", "Command three");
assert.deepEqual(dismissChatNotice([first, second, third], "notice-2"), [first, third]);
// An unknown id leaves the list as it was.
assert.deepEqual(dismissChatNotice([first, third], "notice-9"), [first, third]);
assert.deepEqual(dismissChatNotice(undefined, "notice-1"), []);
});
test("takeChatNoticeOffer removes the notice and returns its draft", () => {
const offerless = makeChatNotice("notice-1", "Command one");
const offered = makeChatNotice("notice-2", "Not a command.", { failed: true, offer: "/nope" });
const taken = takeChatNoticeOffer([offerless, offered], "notice-2");
assert.equal(taken.offer, "/nope");
assert.deepEqual(taken.notices, [offerless]);
});
test("takeChatNoticeOffer returns null and leaves the list for a stale or offerless notice", () => {
const offerless = makeChatNotice("notice-1", "Command one");
const offered = makeChatNotice("notice-2", "Not a command.", { failed: true, offer: "/nope" });
for (const id of ["notice-1", "notice-9"]) {
const taken = takeChatNoticeOffer([offerless, offered], id);
assert.equal(taken.offer, null);
assert.deepEqual(taken.notices, [offerless, offered]);
}
// A second take of an already-taken id is stale and sends nothing.
const firstTake = takeChatNoticeOffer([offered], "notice-2");
const secondTake = takeChatNoticeOffer(firstTake.notices, "notice-2");
assert.equal(secondTake.offer, null);
assert.deepEqual(secondTake.notices, []);
});
test("notice lists are scoped per conversation and never share state", () => {
// Two conversations' notice lists are independent arrays: appending or
// dismissing in one cannot touch the other (the app keeps one per thread).
const operator = [];
const throwaway = [];
const operatorNotice = makeChatNotice("notice-1", "Operator command");
const throwawayNotice = makeChatNotice("notice-2", "Throwaway command", { failed: true });
const operatorAfter = appendChatNotice(operator, operatorNotice);
const throwawayAfter = appendChatNotice(throwaway, throwawayNotice);
assert.deepEqual(operatorAfter, [operatorNotice]);
assert.deepEqual(throwawayAfter, [throwawayNotice]);
assert.deepEqual(dismissChatNotice(operatorAfter, "notice-1"), []);
assert.deepEqual(throwawayAfter, [throwawayNotice]);
const taken = takeChatNoticeOffer(
appendChatNotice(throwawayAfter, makeChatNotice("notice-3", "Offer", { offer: "/help" })),
"notice-3",
);
assert.equal(taken.offer, "/help");
assert.deepEqual(operatorAfter, [operatorNotice]);
});
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// Slash commands (C9) // Slash commands (C9)
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
@@ -1507,3 +1653,282 @@ test("a step that ends does not clear a background shell that outlives the turn"
assert.equal(resumed.selectedShellId, null); assert.equal(resumed.selectedShellId, null);
assert.equal(resumed.shellOutput, 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");
});
// ---------------------------------------------------------------------------
// C13: the local overrides and the seen state (ChatOverrides.kt / ChatSeen.kt)
// ---------------------------------------------------------------------------
const sess = (id, title, updated_at) => ({ id, title, updated_at });
test("local overrides: a local title wins on every refresh, trimmed, blanks ignored", () => {
const sessions = [sess("a", "Server A", 100), sess("b", "Server B", 200)];
// No overrides: the server's own list is returned untouched.
assert.equal(applyChatOverrides(sessions, emptyChatOverrides()), sessions);
let overrides = renameChatOverride(emptyChatOverrides(), "a", " My A ");
assert.deepEqual(overrides.titles, { a: "My A" });
const applied = applyChatOverrides(sessions, overrides);
assert.equal(applied[0].title, "My A");
assert.equal(applied[1].title, "Server B");
// A later refresh (the server's own title still "Server A") keeps the local name.
assert.equal(applyChatOverrides(sessions, overrides)[0].title, "My A");
// A blank id or a blank/whitespace title changes nothing (identity preserved).
assert.equal(renameChatOverride(overrides, "a", " "), overrides);
assert.equal(renameChatOverride(overrides, " ", "Nope"), overrides);
// A rename for another id is recorded without touching the first.
const both = renameChatOverride(overrides, "b", "Bee");
assert.deepEqual(both.titles, { a: "My A", b: "Bee" });
assert.equal(applyChatOverrides(sessions, both)[1].title, "Bee");
// Re-recording the same trimmed title is a no-op (same object).
assert.equal(renameChatOverride(both, "b", " Bee "), both);
});
test("hide + undo: one entry per id, blank ignored, restore returns the prior state", () => {
const overrides = emptyChatOverrides();
const hidden = hideChatOverride(overrides, "s1");
assert.deepEqual(hidden.hidden, ["s1"]);
// Already hidden: nothing changes, and no duplicate is appended.
assert.equal(hideChatOverride(hidden, "s1"), hidden);
assert.equal(hideChatOverride(hidden, " "), hidden);
const sessions = [sess("s1", "One", 1), sess("s2", "Two", 2)];
assert.deepEqual(applyChatOverrides(sessions, hidden).map((s) => s.id), ["s2"]);
const restored = restoreChatOverride(hidden, "s1");
assert.deepEqual(restored.hidden, []);
assert.deepEqual(applyChatOverrides(sessions, restored).map((s) => s.id), ["s1", "s2"]);
// Restoring something that was never hidden changes nothing.
assert.equal(restoreChatOverride(restored, "s9"), restored);
// Hide then undo returns the original model.
assert.deepEqual(restoreChatOverride(hideChatOverride(overrides, "s1"), "s1"), overrides);
});
test("overrides JSON round-trips, and unreadable/wrong-typed input decodes to empty", () => {
const overrides = renameChatOverride(hideChatOverride(emptyChatOverrides(), "gone"), "kept", "Name");
assert.deepEqual(decodeChatOverrides(encodeChatOverrides(overrides)), overrides);
for (const corrupt of [null, "", "not json", "{", "[]", '"x"', "42"]) {
assert.deepEqual(decodeChatOverrides(corrupt), emptyChatOverrides());
}
// Wrong-typed fields fall back to the empty model rather than throwing.
assert.deepEqual(decodeChatOverrides('{"titles":[],"hidden":"x"}'), emptyChatOverrides());
assert.deepEqual(decodeChatOverrides('{"titles":{"a":3},"hidden":[7,"ok","ok"]}').hidden, ["ok"]);
assert.deepEqual(decodeChatOverrides('{"titles":{"":"x","b":" B "}}'), { titles: { b: "B" }, hidden: [] });
});
test("seen JSON round-trips, de-duplicates unseen, and tolerates corrupt input", () => {
let seen = markChatUnseen(emptyChatSeen(), "s1");
seen = markChatUnseen(seen, "s1"); // duplicate
seen = readChatSeen(seen, "s2", 500);
const decoded = decodeChatSeen(encodeChatSeen(seen));
assert.deepEqual(decoded.seenAt, { s2: 500 });
assert.deepEqual(decoded.unseen, ["s1"]);
for (const corrupt of [null, "", "not json", "{", "[]", "true"]) {
assert.deepEqual(decodeChatSeen(corrupt), emptyChatSeen());
}
assert.deepEqual(decodeChatSeen('{"seenAt":[],"unseen":"x"}'), emptyChatSeen());
const tolerated = decodeChatSeen('{"seenAt":{"a":10,"b":"x","":5},"unseen":["u","u",""]}');
assert.deepEqual(tolerated.seenAt, { a: 10 });
assert.deepEqual(tolerated.unseen, ["u"]);
});
test("first sight seeding: a baseline is set once and never clears an explicit unseen", () => {
const sessions = [sess("a", "A", 100), sess("b", "B", 0)];
const seeded = seedChatSeen(emptyChatSeen(), sessions, null);
assert.deepEqual(seeded.seenAt, { a: 100 });
// An absent or zero recency is never recorded.
assert.equal(seeded.seenAt.b, undefined);
// A later, higher recency is not re-seeded over the existing baseline.
const later = seedChatSeen(seeded, [sess("a", "A", 300)], null);
assert.deepEqual(later.seenAt, { a: 100 });
// Seeding never clears an unseen mark.
const marked = markChatUnseen(seeded, "a");
const reseeded = seedChatSeen(marked, [sess("a", "A", 400)], null);
assert.deepEqual(reseeded.unseen, ["a"]);
// The active session is read (watermark advances, the mark clears).
const active = seedChatSeen(markChatUnseen(emptyChatSeen(), "a"), [sess("a", "A", 900)], "a");
assert.deepEqual(active.seenAt, { a: 900 });
assert.deepEqual(active.unseen, []);
});
test("reading advances the watermark monotonically and always clears the mark", () => {
const first = readChatSeen(emptyChatSeen(), "s", 100);
assert.equal(chatSeenWatermark(first, "s"), 100);
// A stale read cannot rewind it...
assert.equal(readChatSeen(first, "s", 50), first);
// ...an equal read is not "newer" either...
assert.equal(readChatSeen(first, "s", 100), first);
// ...but a strictly newer one advances.
assert.equal(chatSeenWatermark(readChatSeen(first, "s", 101), "s"), 101);
// A mark is cleared even when the recency does not advance.
const marked = markChatUnseen(first, "s");
const read = readChatSeen(marked, "s", 100);
assert.deepEqual(read.unseen, []);
assert.equal(read.seenAt.s, 100);
// A blank id is a no-op.
assert.equal(readChatSeen(first, " ", 500), first);
});
test("the unseen rule: not active, explicit mark or never-opened-and-strictly-newer", () => {
let seen = readChatSeen(emptyChatSeen(), "opened", 100);
seen = readChatSeen(seen, "equal", 100);
// A watermark ahead of the session's own recency: not newer, so not new.
seen = readChatSeen(seen, "old", 120);
const opened = sess("opened", "Opened", 200); // moved on after it was read
const fresh = sess("fresh", "Fresh", 150);
const equal = sess("equal", "Equal", 100);
const old = sess("old", "Old", 50);
// The active session is never new, even with an explicit mark.
assert.equal(
isChatSessionUnseen(opened, { activeId: "opened", seen: markChatUnseen(seen, "opened"), opened: true }),
false,
);
// A never-opened session is new only while strictly newer than the watermark.
assert.equal(isChatSessionUnseen(fresh, { seen, opened: false }), true);
assert.equal(isChatSessionUnseen(equal, { seen, opened: false }), false);
assert.equal(isChatSessionUnseen(old, { seen, opened: false }), false);
// A session already opened here is judged by the explicit mark alone.
assert.equal(isChatSessionUnseen(opened, { seen, opened: true }), false);
assert.equal(isChatSessionUnseen(opened, { seen: markChatUnseen(seen, "opened"), opened: true }), true);
});
test("the C13 wording matches the Android sources verbatim", () => {
assert.equal(CHAT_RENAME_ACTION, "Rename…");
assert.equal(CHAT_HIDE_ACTION, "Hide on this device");
assert.equal(CHAT_ACTIONS_LABEL, "Chat actions");
assert.equal(CHAT_REMOVED_MESSAGE, "Hidden on this device; the chat stays on the server.");
assert.equal(CHAT_UNDO_ACTION, "Undo");
assert.equal(CHAT_RENAME_TITLE, "Rename chat");
assert.equal(CHAT_RENAME_FIELD_LABEL, "Name");
assert.equal(
CHAT_RENAME_HELPER,
"The server has no rename for a chat, so this name is kept on this device.",
);
assert.equal(CHAT_RENAME_SAVE, "Save");
assert.equal(CHAT_RENAME_DISMISS, "Cancel");
// The badge precedence words, with Open only while the conversation is open.
assert.equal(sessionActivityBadge(sessionActivity(true, true), true), "Streaming");
assert.equal(sessionActivityBadge(sessionActivity(false, true), true), "New");
assert.equal(sessionActivityBadge(sessionActivity(false, false), true), "Open");
assert.equal(sessionActivityBadge(sessionActivity(false, false), false), null);
});
+214
View File
@@ -0,0 +1,214 @@
// The pure notification model (L5): qualifying transitions, exactly-once
// dedupe, pre-existing/dismissed suppression, the app's exact wording and the
// total permission/storage helpers. No DOM, no timer, no live server.
import { test } from "node:test";
import assert from "node:assert/strict";
import { AttentionKind, attentionKey } from "../src/attention.js";
import {
NOTIFICATION_DEFAULT,
NOTIFICATION_DEFAULT_ASKED,
NOTIFICATION_DENIED,
NOTIFICATION_GRANTED,
NOTIFICATION_INSECURE,
NOTIFICATION_UNSUPPORTED,
NOTIFY_STORAGE_KEY,
alertBody,
alertKey,
alertTitle,
createAlertLedger,
decodeNotificationSettings,
encodeNotificationSettings,
notificationEnvironment,
notificationPermissionState,
} from "../src/notify.js";
const frame = (runId, status, extra = {}) => ({
run_id: runId,
status,
name: "release",
title: "Ship it",
...extra,
});
test("headlines are exactly the app's two, and unknown kinds are blank", () => {
assert.equal(alertTitle(AttentionKind.Failed), "A run failed");
assert.equal(alertTitle(AttentionKind.Decision), "A run needs your decision");
assert.equal(alertTitle({ name: "Failed" }), "A run failed");
assert.equal(alertTitle({ name: "Other" }), "");
});
test("the alert identity is the attention identity", () => {
assert.equal(alertKey(7, AttentionKind.Failed), attentionKey(7, AttentionKind.Failed));
assert.equal(alertKey(7, AttentionKind.Decision), "7:Decision");
});
test("alert body is the title then the pipeline, with the pipeline fallback", () => {
assert.equal(alertBody({ label: "Ship it", pipeline: "release" }), "Ship it \u00b7 release");
assert.equal(alertBody({ title: " Ship it ", name: "release" }), "Ship it \u00b7 release");
assert.equal(alertBody({ title: " ", name: "release" }), "release");
assert.equal(alertBody({ label: "release", pipeline: "release" }), "release");
assert.equal(alertBody({ label: "Ship it", pipeline: "" }), "Ship it");
assert.equal(alertBody(frame(7, "failed")), "Ship it \u00b7 release");
});
test("queued -> failed raises one alert and duplicate frames never repeat it", () => {
const ledger = createAlertLedger();
ledger.seed([{ id: 4, status: "queued", name: "release", title: "Ship it" }]);
const alert = ledger.observe(frame(4, "failed"));
assert.equal(alert.title, "A run failed");
assert.equal(alert.body, "Ship it \u00b7 release");
assert.equal(alert.key, "4:Failed");
assert.equal(ledger.observe(frame(4, "failed")), null);
assert.equal(ledger.observe(frame(4, "failed")), null);
});
test("running -> waiting raises the decision alert; unchanged waiting raises none", () => {
const ledger = createAlertLedger();
ledger.seed([{ id: 9, status: "running", name: "release", title: "Ship it" }]);
const alert = ledger.observe(frame(9, "waiting"));
assert.equal(alert.title, "A run needs your decision");
assert.equal(alert.key, "9:Decision");
assert.equal(ledger.observe(frame(9, "waiting")), null);
});
test("succeeded, canceled, interrupted and unknown statuses raise nothing", () => {
for (const status of ["succeeded", "canceled", "interrupted", "mystery", ""]) {
const ledger = createAlertLedger();
ledger.seed([{ id: 11, status: "running" }]);
assert.equal(ledger.observe(frame(11, status)), null, `status ${status}`);
}
});
test("a first-seen failed/waiting run (a snapshot seed) raises nothing", () => {
const ledger = createAlertLedger();
assert.equal(ledger.observe(frame(21, "failed")), null);
assert.equal(ledger.observe(frame(22, "waiting")), null);
});
test("a run already failed/waiting in the seed raises nothing", () => {
const ledger = createAlertLedger();
ledger.seed([
{ id: 31, status: "failed" },
{ id: 32, status: "waiting" },
]);
assert.equal(ledger.observe(frame(31, "failed")), null);
assert.equal(ledger.observe(frame(32, "waiting")), null);
});
test("the subscribe snapshot is seeded, so a queued run that failed in the gap does not notify", () => {
const ledger = createAlertLedger();
ledger.seed([{ id: 41, status: "queued" }]);
ledger.beginSeed();
assert.equal(ledger.observe(frame(41, "failed")), null);
ledger.endSeed();
assert.equal(ledger.observe(frame(41, "failed")), null);
// A later real transition still raises exactly once.
assert.equal(ledger.observe(frame(41, "running")), null);
assert.equal(ledger.observe(frame(41, "failed")).key, "41:Failed");
});
test("leaving the qualifying state forgets the key for a genuinely new transition", () => {
const ledger = createAlertLedger();
ledger.seed([{ id: 51, status: "queued" }]);
assert.equal(ledger.observe(frame(51, "failed")).key, "51:Failed");
assert.equal(ledger.observe(frame(51, "running")), null);
assert.equal(ledger.observe(frame(51, "failed")).key, "51:Failed");
// And a failed -> waiting hand-off raises the other kind once.
assert.equal(ledger.observe(frame(51, "waiting")).key, "51:Decision");
assert.equal(ledger.observe(frame(51, "waiting")), null);
});
test("a dismissed attention key notifies nothing, even on a real transition", () => {
const ledger = createAlertLedger();
ledger.seed([{ id: 61, status: "queued" }]);
const alert = ledger.observe(frame(61, "failed"), {
dismissed: new Set([attentionKey(61, AttentionKind.Failed)]),
});
assert.equal(alert, null);
assert.deepEqual(ledger.notifiedKeys(), ["61:Failed"]);
});
test("reset drops the status baseline but keeps the page session's dedupe", () => {
const ledger = createAlertLedger();
ledger.seed([{ id: 71, status: "queued" }]);
assert.equal(ledger.observe(frame(71, "failed")).key, "71:Failed");
ledger.reset();
// Re-seeding the fresh (still failed) list is not a transition.
ledger.seed([{ id: 71, status: "failed" }]);
assert.equal(ledger.observe(frame(71, "failed")), null);
assert.deepEqual(ledger.notifiedKeys(), ["71:Failed"]);
});
test("a malformed frame is ignored, never crashed on", () => {
const ledger = createAlertLedger();
assert.equal(ledger.observe(null), null);
assert.equal(ledger.observe({}), null);
assert.equal(ledger.observe({ run_id: 0, status: "failed" }), null);
});
test("permission wording is honest for every browser state", () => {
assert.equal(notificationPermissionState({ supported: false }).body, NOTIFICATION_UNSUPPORTED);
assert.equal(
notificationPermissionState({ supported: true, secureContext: false }).body,
NOTIFICATION_INSECURE,
);
assert.equal(notificationPermissionState({ permission: "denied" }).body, NOTIFICATION_DENIED);
assert.equal(notificationPermissionState({ permission: "granted" }).body, NOTIFICATION_GRANTED);
assert.equal(notificationPermissionState({ asked: false }).body, NOTIFICATION_DEFAULT);
assert.equal(notificationPermissionState({ asked: true }).body, NOTIFICATION_DEFAULT_ASKED);
});
test("only a supported, secure default permission offers the request control", () => {
const defaultView = notificationPermissionState({ asked: false });
assert.equal(defaultView.state, "default");
assert.equal(defaultView.canRequest, true);
assert.equal(defaultView.actionLabel, "Enable notifications");
for (const options of [
{ supported: false },
{ supported: true, secureContext: false },
{ permission: "granted" },
{ permission: "denied" },
]) {
const view = notificationPermissionState(options);
assert.equal(view.canRequest, false, JSON.stringify(options));
assert.equal(view.actionLabel, null, JSON.stringify(options));
}
// Having been asked once does not remove the control while permission stays
// default (the browser itself decides whether it may prompt again).
assert.equal(notificationPermissionState({ asked: true }).canRequest, true);
});
test("the asked flag round-trips and malformed storage decodes safely", () => {
assert.equal(NOTIFY_STORAGE_KEY, "pipelines.web.notify.v1");
const stored = encodeNotificationSettings({ asked: true });
assert.deepEqual(JSON.parse(stored), { asked: true });
assert.equal(decodeNotificationSettings(stored).asked, true);
assert.equal(decodeNotificationSettings(encodeNotificationSettings({ asked: false })).asked, false);
for (const bad of ["", " ", "not json", "[]", "null", '"asked"', "{", '{"asked":"yes"}', "42"]) {
assert.deepEqual(decodeNotificationSettings(bad), { asked: false }, bad);
}
assert.deepEqual(decodeNotificationSettings(null), { asked: false });
});
test("notificationEnvironment reads the browser facts without guessing", () => {
const granted = notificationEnvironment({
Notification: Object.assign(function Notification() {}, { permission: "granted" }),
isSecureContext: true,
});
assert.deepEqual(granted, { supported: true, secureContext: true, permission: "granted" });
assert.deepEqual(notificationEnvironment({}), {
supported: false,
secureContext: false,
permission: "default",
});
const odd = notificationEnvironment({
Notification: Object.assign(function Notification() {}, { permission: "maybe" }),
isSecureContext: false,
});
assert.deepEqual(odd, { supported: true, secureContext: false, permission: "default" });
});
+59
View File
@@ -293,6 +293,30 @@ test("a run action throws when the reply has no run detail", async () => {
await assert.rejects(() => repo.cancelRun(7), ProtocolError); await assert.rejects(() => repo.cancelRun(7), ProtocolError);
}); });
test("subscribeRuns sends exactly the blank any-workspace watch and no run_ids", async () => {
const { repo, ws } = connected();
ws.reply = (frame) => ({ id: frame.id, type: "subscribe" });
await repo.subscribeRuns();
assert.deepEqual(lastFrame(ws), { type: "subscribe", workspace: "" });
});
test("unsubscribeRuns sends exactly {type:'unsubscribe'}", async () => {
const { repo, ws } = connected();
ws.reply = (frame) => ({ id: frame.id, type: "unsubscribe" });
await repo.unsubscribeRuns();
assert.deepEqual(lastFrame(ws), { type: "unsubscribe" });
});
test("subscribeRuns is not sent while the page is not connected", async () => {
FakeWebSocket.instances = [];
const client = new PipelinesClient({ WebSocketImpl: FakeWebSocket });
const repo = new PipelinesRepository(client);
await assert.rejects(() => repo.subscribeRuns(), { name: "NotConnectedError" });
assert.equal(FakeWebSocket.instances.length, 0);
});
// ---- The composer's own commands (C8/C9) ---------------------------------- // ---- The composer's own commands (C8/C9) ----------------------------------
test("chatPrompt trims the text, sends the operation and native message ids, and omits files when empty", async () => { test("chatPrompt trims the text, sends the operation and native message ids, and omits files when empty", async () => {
@@ -345,6 +369,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" } }); 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 () => { test("chatCreate sends title/directory/operation_id and returns chat_session", async () => {
const { repo, ws } = connected(); const { repo, ws } = connected();
const created = { id: "ses_new", title: "New chat" }; const created = { id: "ses_new", title: "New chat" };
+1132 -36
View File
File diff suppressed because it is too large Load Diff