Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

perf: batches 12-14 (SQLite statement cache, lazy UI chunks, hot-path store selectors)

milind-soni173f6235e97e
diff --git a/server/message-db.test.ts b/server/message-db.test.ts
index bbcc695fea..09b0313457 100644
--- a/server/message-db.test.ts
+++ b/server/message-db.test.ts
@@ -705,3 +705,20 @@ describe("notification_log", () => {
expect(rows.map((r) => r.id)).toContain("n3");
});
});
+
+describe("SQLite cache and prepared statement reuse", () => {
+ beforeEach(() => {
+ closeMessageDb();
+ rmSync(DATA_DIR, { recursive: true, force: true });
+ mkdirSync(DATA_DIR, { recursive: true });
+ });
+
+ it("applies the 16 MiB page cache PRAGMA and reuses cached statements until closed", () => {
+ const row = prepared("PRAGMA cache_size").get() as { cache_size: number };
+ expect(row.cache_size).toBe(-16384);
+ const first = prepared("SELECT 1 AS n");
+ expect(prepared("SELECT 1 AS n")).toBe(first);
+ closeMessageDb();
+ expect(prepared("SELECT 1 AS n") === first).toBe(false);
+ });
+});
diff --git a/server/message-db.ts b/server/message-db.ts
index f39a782b6c..6656139104 100644
--- a/server/message-db.ts
+++ b/server/message-db.ts
@@ -48,7 +48,7 @@ function open(): DatabaseSync {
chmodSync(file, 0o600);
} catch {}
const db = new DatabaseSync(file);
- db.exec("PRAGMA busy_timeout = 5000; PRAGMA journal_mode = WAL; PRAGMA synchronous = NORMAL; PRAGMA journal_size_limit = 67108864; PRAGMA temp_store = MEMORY");
+ db.exec("PRAGMA busy_timeout = 5000; PRAGMA journal_mode = WAL; PRAGMA synchronous = NORMAL; PRAGMA journal_size_limit = 67108864; PRAGMA temp_store = MEMORY; PRAGMA cache_size = -16384");
db.exec(`
CREATE TABLE IF NOT EXISTS messages (
thread_id TEXT NOT NULL,
@@ -160,12 +160,12 @@ function db(): DatabaseSync {
}
/** One prepared statement per SQL text for the life of the open database. */
-export function prepared(sql: string): StatementSync {
- const database = db();
+function preparedOn(database: DatabaseSync, sql: string): StatementSync {
let statement = statements.get(sql);
if (!statement) statements.set(sql, statement = database.prepare(sql));
return statement;
}
+export function prepared(sql: string): StatementSync { return preparedOn(db(), sql); }
let transactionDepth = 0;
function transaction<T>(fn: (database: DatabaseSync) => T): T {
@@ -246,8 +246,7 @@ export interface StoredCommandReceipt {
}
export function readCommandReceipt(kind: string, key: string): StoredCommandReceipt | null {
- const row = db()
- .prepare("SELECT kind, key, at, result FROM command_receipts WHERE kind = ? AND key = ?")
+ const row = prepared("SELECT kind, key, at, result FROM command_receipts WHERE kind = ? AND key = ?")
.get(kind, key) as StoredCommandReceipt | undefined;
return row ?? null;
}
@@ -260,13 +259,11 @@ export function withCommandReceipt(
at: number,
): { result: string; replayed: boolean } {
return transaction((database) => {
- const existing = database
- .prepare("SELECT result FROM command_receipts WHERE kind = ? AND key = ?")
+ const existing = preparedOn(database, "SELECT result FROM command_receipts WHERE kind = ? AND key = ?")
.get(kind, key) as { result: string } | undefined;
if (existing) return { result: existing.result, replayed: true };
const result = apply();
- database
- .prepare("INSERT INTO command_receipts(kind, key, at, result) VALUES (?, ?, ?, ?)")
+ preparedOn(database, "INSERT INTO command_receipts(kind, key, at, result) VALUES (?, ?, ?, ?)")
.run(kind, key, at, result);
return { result, replayed: false };
});
@@ -294,10 +291,10 @@ const rowToNotificationLogEntry = (row: {
export function insertNotificationLog(entry: NotificationLogEntry): void {
transaction((database) => {
- database.prepare(
+ preparedOn(database,
"INSERT INTO notification_log(id, at, kind, bot_id, bot_name, thread_id, group_id, title, body, avatar_url, for_person, read) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0)",
).run(entry.id, entry.at, entry.kind, entry.botId, entry.botName, entry.threadId, entry.groupId ?? null, entry.title, entry.body, entry.avatarUrl ?? null, entry.forPerson ?? null);
- database.prepare(
+ preparedOn(database,
"DELETE FROM notification_log WHERE id NOT IN (SELECT id FROM notification_log ORDER BY at DESC, rowid DESC LIMIT ?)",
).run(NOTIFICATION_LOG_LIMIT);
});
@@ -316,18 +313,18 @@ export function logNotification(notification: Notification): NotificationLogEntr
export function recentNotificationLog(limit = NOTIFICATION_LOG_LIMIT, reader?: string): NotificationLogEntry[] {
const [read, kept] = reader === undefined ? ["read", ""] : ["(read = 1 OR EXISTS (SELECT 1 FROM json_each(coalesce(read_by, '[]')) WHERE value = ?1)) AS read", "WHERE NOT EXISTS (SELECT 1 FROM json_each(coalesce(cleared_by, '[]')) WHERE value = ?1)"];
- const rows = db().prepare(`SELECT id, at, kind, bot_id, bot_name, thread_id, group_id, title, body, avatar_url, for_person, ${read} FROM notification_log ${kept} ORDER BY at DESC, rowid DESC LIMIT ${reader === undefined ? "?1" : "?2"}`).all(...(reader === undefined ? [] : [reader]), limit) as Array<Parameters<typeof rowToNotificationLogEntry>[0]>;
+ const rows = prepared(`SELECT id, at, kind, bot_id, bot_name, thread_id, group_id, title, body, avatar_url, for_person, ${read} FROM notification_log ${kept} ORDER BY at DESC, rowid DESC LIMIT ${reader === undefined ? "?1" : "?2"}`).all(...(reader === undefined ? [] : [reader]), limit) as Array<Parameters<typeof rowToNotificationLogEntry>[0]>;
return rows.map(rowToNotificationLogEntry);
}
export function markNotificationLogRead(ids: readonly string[], reader?: string): void {
- if (reader === undefined) db().prepare("UPDATE notification_log SET read = 1 WHERE read = 0 AND id IN (SELECT value FROM json_each(?))").run(JSON.stringify(ids));
- else db().prepare("UPDATE notification_log SET read_by = json_insert(coalesce(read_by, '[]'), '$[#]', ?1) WHERE id IN (SELECT value FROM json_each(?2)) AND NOT EXISTS (SELECT 1 FROM json_each(coalesce(read_by, '[]')) WHERE value = ?1)").run(reader, JSON.stringify(ids));
+ if (reader === undefined) prepared("UPDATE notification_log SET read = 1 WHERE read = 0 AND id IN (SELECT value FROM json_each(?))").run(JSON.stringify(ids));
+ else prepared("UPDATE notification_log SET read_by = json_insert(coalesce(read_by, '[]'), '$[#]', ?1) WHERE id IN (SELECT value FROM json_each(?2)) AND NOT EXISTS (SELECT 1 FROM json_each(coalesce(read_by, '[]')) WHERE value = ?1)").run(reader, JSON.stringify(ids));
}
-export function clearNotificationLog(ids: readonly string[], reader?: string): void { if (reader === undefined) db().prepare("DELETE FROM notification_log WHERE id IN (SELECT value FROM json_each(?))").run(JSON.stringify(ids)); else db().prepare("UPDATE notification_log SET cleared_by = json_insert(coalesce(cleared_by, '[]'), '$[#]', ?1) WHERE id IN (SELECT value FROM json_each(?2)) AND NOT EXISTS (SELECT 1 FROM json_each(coalesce(cleared_by, '[]')) WHERE value = ?1)").run(reader, JSON.stringify(ids)); }
-export function forgetNotificationReader(person: string): void { for (const column of ["read_by", "cleared_by"]) db().prepare(`UPDATE notification_log SET ${column} = (SELECT json_group_array(value) FROM json_each(${column}) WHERE value <> ?1) WHERE EXISTS (SELECT 1 FROM json_each(coalesce(${column}, '[]')) WHERE value = ?1)`).run(person); }
+export function clearNotificationLog(ids: readonly string[], reader?: string): void { if (reader === undefined) prepared("DELETE FROM notification_log WHERE id IN (SELECT value FROM json_each(?))").run(JSON.stringify(ids)); else prepared("UPDATE notification_log SET cleared_by = json_insert(coalesce(cleared_by, '[]'), '$[#]', ?1) WHERE id IN (SELECT value FROM json_each(?2)) AND NOT EXISTS (SELECT 1 FROM json_each(coalesce(cleared_by, '[]')) WHERE value = ?1)").run(reader, JSON.stringify(ids)); }
+export function forgetNotificationReader(person: string): void { for (const column of ["read_by", "cleared_by"]) prepared(`UPDATE notification_log SET ${column} = (SELECT json_group_array(value) FROM json_each(${column}) WHERE value <> ?1) WHERE EXISTS (SELECT 1 FROM json_each(coalesce(${column}, '[]')) WHERE value = ?1)`).run(person); }
export function saveChatFollowup(followup: Omit<ChatFollowup, "status">): void {
- writeFollowups((connection) => connection.prepare(
+ writeFollowups((connection) => preparedOn(connection,
"INSERT INTO chat_followups(id, kind, owner_id, thread_id, send_id, status, payload) VALUES (?, ?, ?, ?, ?, 'pending', ?)",
).run(followup.id, followup.kind, followup.ownerId, followup.threadId, followup.payload.sendId ?? null, JSON.stringify(followup.payload)));
}
@@ -336,7 +333,7 @@ export function saveChatFollowup(followup: Omit<ChatFollowup, "status">): void {
export function settleChatFollowups(ids: string[], status: FollowupStatus | null): void {
if (!ids.length) return;
writeFollowups((connection) => {
- const statement = connection.prepare(status === null
+ const statement = preparedOn(connection, status === null
? "DELETE FROM chat_followups WHERE id = ?"
: status === "cancelled"
? "UPDATE chat_followups SET status = ?, payload = '{\"text\":\"\"}' WHERE id = ?"
@@ -350,8 +347,8 @@ export function settleChatFollowups(ids: string[], status: FollowupStatus | null
export function chatFollowups(kind?: ChatFollowup["kind"]): ChatFollowup[] {
const rows = (kind
- ? db().prepare("SELECT * FROM chat_followups WHERE kind = ? ORDER BY rowid").all(kind)
- : db().prepare("SELECT * FROM chat_followups ORDER BY rowid").all()) as Array<{
+ ? prepared("SELECT * FROM chat_followups WHERE kind = ? ORDER BY rowid").all(kind)
+ : prepared("SELECT * FROM chat_followups ORDER BY rowid").all()) as Array<{
id: string; kind: ChatFollowup["kind"]; owner_id: string; thread_id: string; status: FollowupStatus; payload: string;
}>;
return rows.map((row) => ({ id: row.id, kind: row.kind, ownerId: row.owner_id, threadId: row.thread_id,
@@ -359,7 +356,7 @@ export function chatFollowups(kind?: ChatFollowup["kind"]): ChatFollowup[] {
}
export function cancelledChatFollowup(kind: ChatFollowup["kind"], ownerId: string, threadId: string, sendId: string): boolean {
- return Boolean(db().prepare(
+ return Boolean(prepared(
"SELECT 1 FROM chat_followups WHERE kind = ? AND owner_id = ? AND thread_id = ? AND send_id = ? AND status = 'cancelled'",
).get(kind, ownerId, threadId, sendId));
}
@@ -384,7 +381,7 @@ export function readThread(threadId: string, legacyFile: string): ThreadRows {
}
export function readMessage(threadId: string, messageId: string): Message | null {
- const row = db().prepare("SELECT json FROM messages WHERE thread_id = ? AND id = ?").get(threadId, messageId);
+ const row = prepared("SELECT json FROM messages WHERE thread_id = ? AND id = ?").get(threadId, messageId);
return row ? rowToMessage(row as { json: string }) : null;
}
@@ -418,7 +415,7 @@ function importLegacy(threadId: string, legacyFile: string): ThreadRows {
messages = ((raw as { messages?: Message[] }).messages ?? []) as Message[];
activeLeafId = (raw as { activeLeafId?: string | null }).activeLeafId ?? null;
}
- const insert = db().prepare(UPSERT_MESSAGE);
+ const insert = prepared(UPSERT_MESSAGE);
db().exec("BEGIN");
try {
for (const message of messages) { const row = messageRow(threadId, message); insert.run(...row); attachmentNameIndex.written(threadId, message.id, row[6]); }
@@ -444,16 +441,16 @@ export function insertMessage(threadId: string, message: Message): void {
/** `relinked`: adds `messages` to a conversation that has rows; each row it names changes only its parentId, and an id it already has fails the whole import. */
export function importThread(threadId: string, messages: Message[], activeLeafId: string | null, relinked?: ReadonlyArray<{ id: string; parentId: string | null }>): void {
transaction((database) => {
- if (!relinked && (database.prepare("SELECT 1 FROM messages WHERE thread_id = ? LIMIT 1").get(threadId) ||
- database.prepare("SELECT 1 FROM thread_state WHERE thread_id = ?").get(threadId))) {
+ if (!relinked && (preparedOn(database, "SELECT 1 FROM messages WHERE thread_id = ? LIMIT 1").get(threadId) ||
+ preparedOn(database, "SELECT 1 FROM thread_state WHERE thread_id = ?").get(threadId))) {
throw new Error("Cannot import over an existing conversation");
}
- const insert = relinked && database.prepare("INSERT INTO messages (thread_id, id, at, role, kind, text, json, search_text) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
+ const insert = relinked && preparedOn(database, "INSERT INTO messages (thread_id, id, at, role, kind, text, json, search_text) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
for (const message of messages) {
if (insert) { const row = messageRow(threadId, message); insert.run(...row); messageWritten(row[6]); attachmentNameIndex.written(threadId, message.id, row[6]); }
else insertMessage(threadId, message);
}
- const link = database.prepare("UPDATE messages SET json = json_set(json, '$.parentId', ?) WHERE thread_id = ? AND id = ?");
+ const link = preparedOn(database, "UPDATE messages SET json = json_set(json, '$.parentId', ?) WHERE thread_id = ? AND id = ?");
for (const row of relinked ?? []) { link.run(row.parentId, threadId, row.id); messageWritten(JSON.stringify(row.parentId)); }
setActiveLeaf(threadId, activeLeafId);
});
@@ -472,8 +469,7 @@ export function updateMessage(threadId: string, message: Message): void {
/** First-reply rescue rows that never settled or ended: at boot, every one of them belongs to a turn that is gone. */
export function openRescueMessages(): Array<{ threadId: string; message: Message }> {
- const rows = db()
- .prepare(
+ const rows = prepared(
"SELECT thread_id, json FROM messages WHERE kind = 'activity' AND json_extract(json, '$.tool.rescue') IS NOT NULL " +
"AND json_extract(json, '$.tool.rescue.settled') IS NULL AND json_extract(json, '$.tool.rescue.over') IS NULL",
)
@@ -500,7 +496,7 @@ export interface WorkRow {
}
export function workRows(since: number, until: number): WorkRow[] {
- return db().prepare(
+ return prepared(
"SELECT thread_id AS threadId, id, at, kind, json_extract(json, '$.tool.name') AS name, json_extract(json, '$.tool.ok') AS ok, " +
"json_extract(json, '$.turnId') AS turnId, json_extract(json, '$.from.botId') AS fromBotId, " +
"json_extract(json, '$.turnSucceeded') AS turnSucceeded, json_extract(json, '$.requestMessageId') AS requestMessageId, " +
@@ -530,7 +526,7 @@ export interface AttentionRow {
export function attentionRows(since: number): AttentionRow[] {
const columns = attentionSelect(MULTI_EXECUTE_INPUT);
- return db().prepare(
+ return prepared(
`${columns} FROM messages INDEXED BY messages_work_at WHERE ${WORK_KINDS} AND kind = 'options' AND at >= ? ` +
"AND json_extract(json, '$.card.answered') IS NULL AND coalesce(json_extract(json, '$.card.dismissed'), 0) = 0 " +
"AND coalesce(json_extract(json, '$.card.expired'), 0) = 0 AND json_extract(json, '$.helperIntro') IS NULL AND json_extract(json, '$.inbox') IS NULL " +
@@ -542,7 +538,7 @@ export function attentionRows(since: number): AttentionRow[] {
/** Every card still open, oldest first, whenever it was asked. */
export function openCardRows(): Array<{ threadId: string; id: string; at: number; card: string | null; fromBotId: string | null; copyOf: string | null }> {
- return db().prepare(
+ return prepared(
`SELECT thread_id AS threadId, id, at, json_extract(json, '$.card') AS card, json_extract(json, '$.from.botId') AS fromBotId, json_extract(json, '$.automation.copyOf') AS copyOf FROM messages INDEXED BY messages_work_at WHERE ${WORK_KINDS} AND kind = 'options' ` +
"AND json_extract(json, '$.card.requestId') IS NOT NULL AND json_extract(json, '$.card.answered') IS NULL AND coalesce(json_extract(json, '$.card.dismissed'), 0) = 0 " +
"AND coalesce(json_extract(json, '$.card.expired'), 0) = 0 AND json_extract(json, '$.helperIntro') IS NULL AND json_extract(json, '$.inbox') IS NULL ORDER BY at",
@@ -551,7 +547,7 @@ export function openCardRows(): Array<{ threadId: string; id: string; at: number
/** The conversations with a card asked since `since` that has not been answered, oldest first; the caller reads each card. */
export function threadsWithCardsSince(since: number): string[] {
- const rows = db().prepare(
+ const rows = prepared(
`SELECT DISTINCT thread_id AS threadId FROM messages INDEXED BY messages_cards_at WHERE ${CARD_KINDS} AND at >= ? ` +
`UNION SELECT DISTINCT thread_id AS threadId FROM messages INDEXED BY messages_work_at WHERE ${WORK_KINDS} AND kind = 'options' AND at >= ? ` +
"AND json_extract(json, '$.card.requestId') IS NOT NULL AND json_extract(json, '$.card.answered') IS NULL AND coalesce(json_extract(json, '$.card.dismissed'), 0) = 0",
@@ -561,7 +557,7 @@ export function threadsWithCardsSince(since: number): string[] {
/** Successful tool calls after a time whose row mentions `word` (case-insensitive), newest last. */
export function successfulCallsMentioning(since: number, word: string): Array<{ at: number; name: string; input: string | null }> {
- return db().prepare(
+ return prepared(
`SELECT at, json_extract(json, '$.tool.name') AS name, ${MULTI_EXECUTE_INPUT} FROM messages ` +
`INDEXED BY messages_work_at WHERE ${WORK_KINDS} AND kind = 'activity' AND at > ? AND json LIKE ? ESCAPE '\\' ` +
"AND json_extract(json, '$.tool.ok') = 1 ORDER BY at",
@@ -588,7 +584,7 @@ export function setActiveLeaf(threadId: string, leafId: string | null): void {
/** Each conversation's newest stored row, by its row number, and how many rows it has: what Send to My Cloud compares with what it sent. */
export function threadHeads(): Map<string, { last: number; lastId: string; rows: number }> {
- const rows = db().prepare("SELECT m.thread_id AS threadId, m.rowid AS last, m.id AS lastId, h.rows AS rows FROM messages m " +
+ const rows = prepared("SELECT m.thread_id AS threadId, m.rowid AS last, m.id AS lastId, h.rows AS rows FROM messages m " +
"JOIN (SELECT thread_id, MAX(rowid) AS head, COUNT(*) AS rows FROM messages GROUP BY thread_id) h ON m.rowid = h.head").all() as Array<{ threadId: string; last: number; lastId: string; rows: number }>;
return new Map(rows.map((row) => [row.threadId, { last: Number(row.last), lastId: row.lastId, rows: Number(row.rows) }]));
}
@@ -596,14 +592,14 @@ export function threadHeads(): Map<string, { last: number; lastId: string; rows:
/** A conversation's rows numbered past `after`, oldest first, each with its stored size: `limit` of them, or all up to `through`. */
export function threadRowsFrom(threadId: string, after: number, upTo: { limit: number } | { through: number }): Array<{ at: number; bytes: number; message: Message }> {
const rows = ("limit" in upTo
- ? db().prepare("SELECT rowid AS at, json FROM messages WHERE thread_id = ? AND rowid > ? ORDER BY rowid LIMIT ?").all(threadId, after, upTo.limit)
- : db().prepare("SELECT rowid AS at, json FROM messages WHERE thread_id = ? AND rowid > ? AND rowid <= ? ORDER BY rowid").all(threadId, after, upTo.through)) as Array<{ at: number; json: string }>;
+ ? prepared("SELECT rowid AS at, json FROM messages WHERE thread_id = ? AND rowid > ? ORDER BY rowid LIMIT ?").all(threadId, after, upTo.limit)
+ : prepared("SELECT rowid AS at, json FROM messages WHERE thread_id = ? AND rowid > ? AND rowid <= ? ORDER BY rowid").all(threadId, after, upTo.through)) as Array<{ at: number; json: string }>;
return rows.map((row) => ({ at: Number(row.at), bytes: Buffer.byteLength(row.json, "utf8"), message: rowToMessage(row) }));
}
/** Each of a conversation's stored rows by id, with its row number. */
export function threadRowNumbers(threadId: string): Map<string, number> {
- const rows = db().prepare("SELECT rowid AS at, id FROM messages WHERE thread_id = ?").all(threadId) as Array<{ at: number; id: string }>;
+ const rows = prepared("SELECT rowid AS at, id FROM messages WHERE thread_id = ?").all(threadId) as Array<{ at: number; id: string }>;
return new Map(rows.map((row) => [row.id, Number(row.at)]));
}
@@ -646,10 +642,10 @@ export function deleteThreads(threadIds: readonly string[], beforeCommit?: () =>
if (threadIds.length === 0 && !beforeCommit) return;
writeFollowups((connection) => {
const statements = [
- connection.prepare("DELETE FROM chat_followups WHERE thread_id = ?"),
- connection.prepare("DELETE FROM messages WHERE thread_id = ?"),
- connection.prepare("DELETE FROM thread_state WHERE thread_id = ?"),
- connection.prepare("DELETE FROM notification_log WHERE thread_id = ?"),
+ preparedOn(connection, "DELETE FROM chat_followups WHERE thread_id = ?"),
+ preparedOn(connection, "DELETE FROM messages WHERE thread_id = ?"),
+ preparedOn(connection, "DELETE FROM thread_state WHERE thread_id = ?"),
+ preparedOn(connection, "DELETE FROM notification_log WHERE thread_id = ?"),
];
for (const id of threadIds) for (const statement of statements) statement.run(id);
beforeCommit?.();
@@ -666,19 +662,19 @@ export function optionCardsForTools(tools: readonly string[]): Array<{ threadId:
}
export function appDocRefs(): string[] {
- const rows = db().prepare("SELECT json_extract(json, '$.app.doc') AS doc FROM messages WHERE kind = 'app' UNION SELECT h.value FROM messages m, json_each(m.json, '$.app.history') h WHERE m.kind = 'app'").all() as Array<{ doc: unknown }>;
+ const rows = prepared("SELECT json_extract(json, '$.app.doc') AS doc FROM messages WHERE kind = 'app' UNION SELECT h.value FROM messages m, json_each(m.json, '$.app.history') h WHERE m.kind = 'app'").all() as Array<{ doc: unknown }>;
return rows.flatMap((row) => (typeof row.doc === "string" && row.doc ? [row.doc] : []));
}
/** Pages shown with show_html `live`, newest first: the rows a server picks up again after a restart. */
export function liveAppRows(limit = 100): Array<{ threadId: string; messageId: string }> {
- return db().prepare("SELECT thread_id AS threadId, id AS messageId FROM messages WHERE kind = 'app' AND json_extract(json, '$.app.live') = 1 ORDER BY rowid DESC LIMIT ?").all(limit) as Array<{ threadId: string; messageId: string }>;
+ return prepared("SELECT thread_id AS threadId, id AS messageId FROM messages WHERE kind = 'app' AND json_extract(json, '$.app.live') = 1 ORDER BY rowid DESC LIMIT ?").all(limit) as Array<{ threadId: string; messageId: string }>;
}
export const attachmentNameIndex = createAttachmentNameIndex({ prepare: (sql) => prepared(sql) }); // threadsReferencing's stored upload names; exported so tests can count builds
export function threadsReferencing(fragment: string): string[] {
if (!fragment) return []; if (STORED_UPLOAD_NAME.test(fragment)) return attachmentNameIndex.threadsFor(fragment);
- return (db().prepare("SELECT DISTINCT thread_id FROM messages WHERE instr(json, ?) > 0").all(fragment) as Array<{ thread_id: string }>).map((row) => row.thread_id);
+ return (prepared("SELECT DISTINCT thread_id FROM messages WHERE instr(json, ?) > 0").all(fragment) as Array<{ thread_id: string }>).map((row) => row.thread_id);
}
export function searchMessages(query: string, limit = 40, threadId?: string): SearchHit[] {
@@ -768,8 +764,7 @@ export function readMessageText(
threadId: string,
messageId: string,
): { threadId: string; messageId: string; at: number; role: string; text: string; from?: string; peer?: string } | null {
- const row = db()
- .prepare(
+ const row = prepared(
"SELECT at, role, text, json_extract(json, '$.from.name') AS from_name, " +
"json_extract(json, '$.peerAsk.name') AS peer_name FROM messages " +
"WHERE thread_id = ? AND id = ? AND kind IN ('text', 'digest') AND text IS NOT NULL",
@@ -906,8 +901,7 @@ export const LATEST_SAID_BY_BOT_SQL =
export function latestSaidByBot(threadIds: readonly string[], botId: string, since: number, limit = 20): ThreadLatest[] {
if (!threadIds.length) return [];
- const rows = db()
- .prepare(LATEST_SAID_BY_BOT_SQL)
+ const rows = prepared(LATEST_SAID_BY_BOT_SQL)
.all(since, botId, JSON.stringify([...new Set(threadIds)]), limit) as Array<{ thread_id: string; id: string; at: number; head: string }>;
return rows.map((row) => ({
threadId: row.thread_id,
@@ -924,8 +918,7 @@ export interface MemoryFileStat {
}
export function indexMemoryFile(botId: string, path: string, text: string, stat: { mtimeMs: number; bytes: number }): void {
- db()
- .prepare(
+ prepared(
"INSERT INTO memory_files (bot_id, path, text, mtime_ms, bytes, search_text) VALUES (?, ?, ?, ?, ?, ?) " +
"ON CONFLICT(bot_id, path) DO UPDATE SET text = excluded.text, mtime_ms = excluded.mtime_ms, bytes = excluded.bytes, " +
"search_text = excluded.search_text",
@@ -934,16 +927,15 @@ export function indexMemoryFile(botId: string, path: string, text: string, stat:
}
export function removeMemoryFile(botId: string, path: string): void {
- db().prepare("DELETE FROM memory_files WHERE bot_id = ? AND path = ?").run(botId, path);
+ prepared("DELETE FROM memory_files WHERE bot_id = ? AND path = ?").run(botId, path);
}
export function deleteBotMemoryFiles(botId: string): void {
- db().prepare("DELETE FROM memory_files WHERE bot_id = ?").run(botId);
+ prepared("DELETE FROM memory_files WHERE bot_id = ?").run(botId);
}
export function indexedMemoryFiles(botId: string): MemoryFileStat[] {
- const rows = db()
- .prepare("SELECT path, mtime_ms, bytes FROM memory_files WHERE bot_id = ?")
+ const rows = prepared("SELECT path, mtime_ms, bytes FROM memory_files WHERE bot_id = ?")
// SAFETY: the SELECT names exactly these three NOT NULL columns
.all(botId) as Array<{ path: string; mtime_ms: number; bytes: number }>;
return rows.map((row) => ({ path: row.path, mtimeMs: row.mtime_ms, bytes: row.bytes }));
@@ -958,8 +950,7 @@ export interface MemoryHit {
export function recallMemory(query: string, botId: string, limit = 12, mode: SearchMode = "all"): MemoryHit[] {
const match = ftsQuery(query, mode);
if (!match) return [];
- const rows = db()
- .prepare(
+ const rows = prepared(
"SELECT f.path, f.mtime_ms, " +
`snippet(memory_fts, 0, '[', ']', '…', ${SNIPPET_TOKENS}) AS snippet ` +
"FROM memory_fts JOIN memory_files f ON f.rowid = memory_fts.rowid " +
diff --git a/src/components/CallView.tsx b/src/components/CallView.tsx
index 21c516c162..b06e08667c 100644
--- a/src/components/CallView.tsx
+++ b/src/components/CallView.tsx
@@ -5,7 +5,9 @@ import { useCallback, useEffect, useId, useRef, useState } from "react";
import { AudioLines, Check, ChevronDown, Loader2, Phone, PhoneOff, X } from "lucide-react";
import { useShowThreads } from "@/lib/thread-preferences";
-import { openBot, useStore, visibleMessages, type Bot } from "@/state/store"; import { isNewChatThread } from "@/state/new-chat";
+import { openBot, visibleMessages, type Bot } from "@/state/store";
+import { useStoreRef } from "@/state/store-ref";
+import { sameFields, useStoreActions, useStoreDispatch, useStoreSelector } from "@/state/store-select"; import { isNewChatThread } from "@/state/new-chat";
import { cn } from "@/lib/cn";
import { useMenuMotion } from "./MenuMotion";
import { currentCall, deferCallCleanup, endCall, startCall, useOnCall } from "@/lib/call";
@@ -53,7 +55,7 @@ function liveStartOf(botId: string): { request: number; waiting: number } {
/** `inverse` (phone composer): a round ink-coloured button with an app-coloured glyph: white on Midnight, dark on Meadow. */
/** `modeMenu: false` drops the call-mode chevron beside the button, for a composer whose + menu offers the modes. */
export function CallButton({ bot, placement = "header", fill, ink, inverse, modeMenu }: { bot: Bot; placement?: CallButtonPlacement; fill?: string; ink?: string; inverse?: boolean; modeMenu?: boolean }) {
- const { state } = useStore();
+ const store = useStoreRef();
return (
<CallTargetButton
placement={placement}
@@ -69,7 +71,7 @@ export function CallButton({ bot, placement = "header", fill, ink, inverse, mode
setupBotId={bot.id}
requireExplicitVoices={false}
liveCapable
- onStart={(mode) => callStarted(state.instances, bot.modelSelection?.instanceId, mode)}
+ onStart={(mode) => callStarted(store.state().instances, bot.modelSelection?.instanceId, mode)}
/>
);
}
@@ -105,7 +107,8 @@ export function CallTargetButton({
liveCapable?: boolean;
onStart: (mode: CallMode) => void;
}) {
- const { state, dispatch, flushBotPatches } = useStore();
+ const { config, liveCall } = useStoreSelector((state) => ({ config: state.config, liveCall: state.liveCall }), sameFields);
+ const { dispatch, flushBotPatches } = useStoreActions();
const showThreads = useShowThreads();
const { capabilities, ready: capabilitiesReady } = useDesktopCapabilities();
const media = useLiveMedia();
@@ -119,29 +122,33 @@ export function CallTargetButton({
const active = onCall || onLiveCall;
const remoteClient = globalThis.window?.ogb?.remoteClient?.active === true;
const capabilityHelp = capabilitiesReady
- ? callCapabilityHelp(capabilities, Boolean(speechBridge(state.config)?.speechStart), missingListenKey(capabilities, state.config))
+ ? callCapabilityHelp(capabilities, Boolean(speechBridge(config)?.speechStart), missingListenKey(capabilities, config))
: null;
const supported = capabilitiesReady && !capabilityHelp;
const localVoice = localSystemVoiceActive();
- const configured = localVoice || Boolean(state.config?.tts?.configured);
+ const configured = localVoice || Boolean(config?.tts?.configured);
const everyTargetHasVoice = voices.length > 0 && voices.every((voice) => Boolean(voice));
const voiceReady =
localVoice ||
- (configured && (requireExplicitVoices ? everyTargetHasVoice : Boolean(state.config?.tts?.ready || everyTargetHasVoice)));
- const turnsHere = !capabilitiesReady || listensHere(capabilities, state.config);
+ (configured && (requireExplicitVoices ? everyTargetHasVoice : Boolean(config?.tts?.ready || everyTargetHasVoice)));
+ const turnsHere = !capabilitiesReady || listensHere(capabilities, config);
const mode = effectiveCallMode(useCallMode(), { turnsHere, canLive });
const liveMode = canLive && mode === "live";
const turnsReady = capabilitiesReady && supported && voiceReady;
const unavailable = !active && !liveElsewhere && !liveMode && !turnsReady;
- const lineHeldElsewhere = liveMode && !onCall && liveLineHeldElsewhere(media, state.liveCall);
+ const lineHeldElsewhere = liveMode && !onCall && liveLineHeldElsewhere(media, liveCall);
const voiceSetupRequired = capabilitiesReady && supported && !voiceReady;
- const cloudHome = state.config?.cloudHome === true;
+ const cloudHome = config?.cloudHome === true;
const [helpOpen, setHelpOpen] = useState(false);
const [voiceSetupOpen, setVoiceSetupOpen] = useState(false);
const [voiceSetupBotId, setVoiceSetupBotId] = useState(setupBotId);
if (voiceSetupRequired && setupBotId !== voiceSetupBotId) setVoiceSetupBotId(setupBotId);
const shownSetupBotId = voiceSetupRequired ? setupBotId : voiceSetupBotId;
- const setupBot = shownSetupBotId ? state.bots.find((candidate) => candidate.id === shownSetupBotId) : undefined;
+ const needSetupBot = Boolean((voiceSetupRequired || voiceSetupOpen) && shownSetupBotId);
+ const { setupBot, elsewhereName } = useStoreSelector((state) => ({
+ setupBot: needSetupBot ? state.bots.find((candidate) => candidate.id === shownSetupBotId) : undefined,
+ elsewhereName: liveElsewhere ? state.bots.find((candidate) => candidate.id === media.botId)?.name : undefined,
+ }), sameFields);
const helpMotion = useMenuMotion(Boolean(unavailable && helpOpen));
const [menuOpen, setMenuOpen] = useState(false);
const startPrompt = canLive && !active && media.needsKey && media.botId === targetId;
@@ -152,7 +159,6 @@ export function CallTargetButton({
const helpId = useId();
const menuId = useId();
const keyId = useId();
- const elsewhereName = liveElsewhere ? state.bots.find((candidate) => candidate.id === media.botId)?.name : undefined;
const composer = placement === "composer";
const round = Boolean(fill) || Boolean(inverse) || placement === "panel" || !modeMenu;
const label = active
@@ -211,7 +217,7 @@ export function CallTargetButton({
const live = async (thread: string) => {
const saved = await flushBotPatches?.(targetId);
if (pending.waiting === request) pending.waiting = 0;
- const provider = (saved ? saved.liveOverride?.provider : liveOverride) ?? state.config?.live?.provider;
+ const provider = (saved ? saved.liveOverride?.provider : liveOverride) ?? config?.live?.provider;
if (pending.request === request) void startLiveCall({ botId: targetId, threadId: thread, provider });
};
pending.waiting = request;
@@ -392,7 +398,7 @@ export function CallTargetButton({
start("live");
}}
className="mt-2.5 mr-2 rounded-lg border border-hairline px-3 py-1.5 text-[12px] font-medium text-ink hover:bg-raised"
- title={callModeHint("live", { cloudHome, config: state.config })}
+ title={callModeHint("live", { cloudHome, config })}
>
{t("call.live.startInstead")}
</button>
@@ -445,7 +451,7 @@ export function CallModeMenu({ id, mode, onChoose, onClose, placement = "header"
onChoose: (mode: CallMode) => void;
onClose: () => void;
}) {
- const { state } = useStore();
+ const config = useStoreSelector((state) => state.config);
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
ref.current?.querySelector<HTMLButtonElement>('[aria-checked="true"]')?.focus();
@@ -483,7 +489,7 @@ export function CallModeMenu({ id, mode, onChoose, onClose, placement = "header"
<span className="min-w-0 flex-1">
<span className={cn("block text-[14px] leading-[18px]", unavailable ? "text-ink-tertiary" : "text-ink")}>{t(entry.label)}</span>
<span className="mt-0.5 block text-[12px] leading-[1.4] text-ink-secondary">
- {unavailable ? `${unavailable.label}. ${unavailable.reason}` : callModeHint(entry.id, { cloudHome, config: state.config })}
+ {unavailable ? `${unavailable.label}. ${unavailable.reason}` : callModeHint(entry.id, { cloudHome, config })}
</span>
</span>
{mode === entry.id && <Check size={14} className="mt-0.5 shrink-0 text-accent" aria-hidden="true" />}
@@ -507,9 +513,10 @@ export function CallOverlay({ bot }: { bot: Bot }) {
}
function Call({ bot }: { bot: Bot }) {
- const { state, dispatch } = useStore();
+ const config = useStoreSelector((state) => state.config);
+ const dispatch = useStoreDispatch();
// One bridge for the whole call: a voice change mid-call must not stop or hear through another.
- const [bridge] = useState(() => speechBridge(state.config));
+ const [bridge] = useState(() => speechBridge(config));
const speech = useSpeech();
const initialPhase: Phase = bot.busy ? "working" : "listening";
const [phase, setPhase] = useState<Phase>(initialPhase);
@@ -572,8 +579,8 @@ function Call({ bot }: { bot: Bot }) {
});
}, [bridge, bot.id, move]);
- const playbackRate = useRef(bot.voicePlaybackRate ?? state.config?.tts?.playbackRate ?? 1);
- playbackRate.current = bot.voicePlaybackRate ?? state.config?.tts?.playbackRate ?? 1;
+ const playbackRate = useRef(bot.voicePlaybackRate ?? config?.tts?.playbackRate ?? 1);
+ playbackRate.current = bot.voicePlaybackRate ?? config?.tts?.playbackRate ?? 1;
const say = useCallback(
async (text: string) => {
if (!alive.current || currentCall() !== bot.id) return false;
diff --git a/src/components/CloudRoomCard.tsx b/src/components/CloudRoomCard.tsx
index 93d46377c1..7609503cb6 100644
--- a/src/components/CloudRoomCard.tsx
+++ b/src/components/CloudRoomCard.tsx
@@ -8,7 +8,7 @@ import { cloudPlanLabel } from "@/lib/cloud-plan";
import { t } from "@/lib/i18n";
import { readRoomCardHidden, rememberRoomCardHidden, roomCardBusy, roomCardView, type RoomCardView } from "@/lib/room-card";
import { readUsageCardDismissed, upgradePath, usageCardView } from "@/lib/usage-meter";
-import { useStore } from "@/state/store";
+import { sameFields, useStoreSelector } from "@/state/store-select";
type Restart = "asking" | "restarting" | "current" | "failed";
const RESTART_NOTE: Record<Exclude<Restart, "asking">, string> = {
@@ -64,9 +64,9 @@ export function CloudRoomCardView({ view, upgrade, browser, upgraded, restart, o
/** The plan's snapshot as the room card reads it, with the bridge that acts on it. */
export function useCloudRoom(): { snapshot: CloudPlanSnapshot | null; bridge: CloudPlanBridge | undefined; teamHome: boolean } {
- const { state } = useStore();
- const bridge = usageBridge(state.config?.cloudHome === true);
- return { snapshot: useCloudPlanSnapshot(bridge), bridge, teamHome: Boolean(state.config?.cloudHome && state.config?.team) };
+ const { cloudHome, teamHome } = useStoreSelector((state) => ({ cloudHome: state.config?.cloudHome === true, teamHome: Boolean(state.config?.cloudHome && state.config?.team) }), sameFields);
+ const bridge = usageBridge(cloudHome);
+ return { snapshot: useCloudPlanSnapshot(bridge), bridge, teamHome };
}
/**
@@ -74,7 +74,7 @@ export function useCloudRoom(): { snapshot: CloudPlanSnapshot | null; bridge: Cl
* Upgrade is the usual one (its preview, then the person's confirmation); Not now holds it back (the Admin, for two weeks).
*/
export function CloudRoomCard() {
- const { state } = useStore();
+ const busy = useStoreSelector((state) => roomCardBusy(state.bots, state.config?.waitingForRoom));
const { snapshot, bridge, teamHome } = useCloudRoom();
const usage = snapshot?.status === "paid" ? snapshot.usage ?? null : null;
const [hidden, setHidden] = useState(readRoomCardHidden);
@@ -84,7 +84,7 @@ export function CloudRoomCard() {
// Restart now acts on the session's own Cloud: once that session ends, an upgrade made in it is no longer this card's.
const paid = snapshot?.status === "paid";
useEffect(() => { if (!paid) { setUpgraded(null); setRestart(null); } }, [paid]);
- const view = roomCardView({ room: snapshot?.status === "paid" ? snapshot.room : null, usage, busy: roomCardBusy(state.bots, state.config?.waitingForRoom), hidden, teamHome,
+ const view = roomCardView({ room: snapshot?.status === "paid" ? snapshot.room : null, usage, busy, hidden, teamHome,
usageCardShown: Boolean(usageCardView({ usage, teamHome, dismissed: readUsageCardDismissed() })) });
const notNow = () => {
if (!view) return;
diff --git a/src/components/FirstReplyRescueRow.tsx b/src/components/FirstReplyRescueRow.tsx
index 0d1ccbccd0..e4b28a8e5f 100644
--- a/src/components/FirstReplyRescueRow.tsx
+++ b/src/components/FirstReplyRescueRow.tsx
@@ -4,7 +4,7 @@ import { requestAiSwitch, useAiSwitchRow } from "@/lib/ai-switch";
import { t } from "@/lib/i18n";
import { useAdvancedMode } from "@/lib/interface-mode";
import { useLiveTurn } from "@/lib/stop-turn";
-import { useStore } from "@/state/store";
+import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select";
import type { FirstReplyRescue } from "../../shared/first-reply-rescue";
const pill = "rounded-full border border-hairline/40 px-2.5 py-1 text-[13px] text-ink hover:bg-raised";
@@ -13,19 +13,22 @@ const pill = "rounded-full border border-hairline/40 px-2.5 py-1 text-[13px] tex
* goes once the AI starts answering, and keeps no live buttons once its own turn is no longer the one running.
* `text` is the row's stored sentence, for a bot this client no longer has; `at` is when the row was posted. */
export function FirstReplyRescueRow({ rescue, text, at }: { rescue: FirstReplyRescue; text: string; at: number }) {
- const { state, dispatch } = useStore();
+ const { bot, group, aiName } = useStoreSelector((state) => ({
+ bot: state.bots.find((candidate) => candidate.id === rescue.botId),
+ group: rescue.groupId ? state.groups.find((candidate) => candidate.id === rescue.groupId) : undefined,
+ aiName: state.instances.find((instance) => instance.instanceId === rescue.instanceId)?.displayName,
+ }), sameFields);
+ const dispatch = useStoreDispatch();
const advanced = useAdvancedMode();
const seen = useLiveTurn(rescue.threadId);
- const bot = state.bots.find((candidate) => candidate.id === rescue.botId);
const task = bot?.tasks?.find((candidate) => candidate.threadId === rescue.threadId);
- const group = rescue.groupId ? state.groups.find((candidate) => candidate.id === rescue.groupId) : undefined;
const busy = rescue.groupId ? group?.busyBotId === rescue.botId : Boolean(task ? task.busy : bot?.threadId === rescue.threadId && bot.busy);
const startedAt = rescue.groupId ? group?.turnStartedAt : task?.turnStartedAt;
// The row's own turn: the one this client saw start, or (it saw none, as after a reload) one running since before the row.
const live = !rescue.settled && !rescue.over && busy && (seen !== undefined ? seen === rescue.turnId : startedAt == null || startedAt <= at);
useAiSwitchRow({ threadId: rescue.threadId, turnId: rescue.turnId, live });
if (rescue.settled) return null;
- const ai = state.instances.find((instance) => instance.instanceId === rescue.instanceId)?.displayName || rescue.ai;
+ const ai = aiName || rescue.ai;
// Where this bot's AI is chosen: the bot panel in Simple mode, the chat header in Advanced. A room's header and a
// remote client's Advanced header have no model chip.
const remote = window.ogb?.remoteClient?.active === true;
diff --git a/src/components/GroupCallBody.tsx b/src/components/GroupCallBody.tsx
new file mode 100644
index 0000000000..9e0c094ee5
--- /dev/null
+++ b/src/components/GroupCallBody.tsx
@@ -0,0 +1,542 @@
+// Half-duplex like CallView: the native recognizer has no echo cancellation. Replies are queued so a fast second member
+// never cuts off the first.
+import { useCallback, useEffect, useRef, useState } from "react";
+import { Loader2, PhoneOff, X } from "lucide-react";
+
+import { currentCall, deferCallCleanup, endCall } from "@/lib/call";
+import { routeSpokenGroupMessage } from "@/lib/group-call";
+import { normalizeState } from "@/lib/mascot";
+import { speaker } from "@/lib/tts";
+import { useSpeech } from "@/lib/tts/useSpeech";
+import { pushToTalkKeys, usePushToTalk } from "@/lib/push-to-talk";
+import type { Bot, Group, Message } from "@/state/store";
+import { useStoreDispatch, useStoreSelector } from "@/state/store-select";
+import { t } from "@/lib/i18n";
+import { cn } from "@/lib/cn";
+import { BotAvatar } from "./Avatar";
+import { CALL_ENDPOINT_MS, callSpeechEndNote, speechBridge } from "@/lib/speech";
+import { isRoutineApproval, isSkillApproval, pendingApprovals, spokenApprovalPrompt } from "./PendingApproval";
+import { titledCard } from "./ApprovalCard";
+import { chineseConsent, NO, YES } from "../../shared/call-consent";
+import { DismissWarning } from "./DismissWarning";
+
+type Phase = "listening" | "sending" | "working" | "speaking";
+
+function questionIn(messages: Message[]): Message | undefined {
+ return messages.find(
+ (message) =>
+ message.kind === "options" &&
+ message.card?.requestId &&
+ !message.card.tool &&
+ !message.card.answered &&
+ !message.card.dismissed,
+ );
+}
+
+export default function GroupCall({ group, members }: { group: Group; members: Bot[] }) {
+ const config = useStoreSelector((state) => state.config);
+ const dispatch = useStoreDispatch();
+ // One bridge for the whole call: a voice change mid-call must not stop or hear through another.
+ const [bridge] = useState(() => speechBridge(config));
+ const speech = useSpeech();
+ const initialPhase: Phase = group.working || group.busyBotId ? "working" : "listening";
+ const [phase, setPhase] = useState<Phase>(initialPhase);
+ const [heard, setHeard] = useState("");
+ const [note, setNote] = useState<string | null>(null);
+ // The × hides this note's words only; "Try microphone" stays, since the call has stopped listening.
+ const [dismissedNote, setDismissedNote] = useState<string | null>(null);
+ const [speakingMemberId, setSpeakingMemberId] = useState<string | null>(null);
+ const pushToTalk = usePushToTalk(group.id, bridge, phase === "listening", () => {
+ setNote(t("call.turns.pushToTalkFailed"));
+ });
+
+ const messages = group.messages;
+ const approval = pendingApprovals(messages)[0];
+ const question = questionIn(messages);
+ const membersRef = useRef(members);
+ const busyRef = useRef(Boolean(group.working || group.busyBotId));
+ const defaultResponderRef = useRef(group.defaultResponder);
+ membersRef.current = members;
+ busyRef.current = Boolean(group.working || group.busyBotId);
+ defaultResponderRef.current = group.defaultResponder;
+
+ const spokenIds = useRef<Set<string>>(new Set());
+ const started = useRef(false);
+ if (!started.current) {
+ started.current = true;
+ for (const message of messages) spokenIds.current.add(message.id);
+ }
+
+ const askedApproval = useRef<{
+ requestId: string;
+ member?: Bot;
+ routine: boolean;
+ skill: boolean;
+ submitted: boolean;
+ } | null>(null);
+ const askedQuestion = useRef<{ requestId: string; member?: Bot } | null>(null);
+ const phaseRef = useRef<Phase>(initialPhase);
+ const alive = useRef(true);
+ const sayGeneration = useRef(0);
+ const queueGeneration = useRef(0);
+ const queue = useRef<Promise<void>>(Promise.resolve());
+ const queuedJobs = useRef(new Set<number>());
+ const nextJobId = useRef(0);
+ const listenWhenDrained = useRef(false);
+ const listenTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const allowBargeIn = useRef(false);
+
+ const move = useCallback((next: Phase) => {
+ phaseRef.current = next;
+ if (alive.current) setPhase(next);
+ }, []);
+
+ const hush = useCallback(() => {
+ void bridge?.speechStop();
+ }, [bridge]);
+
+ const listen = useCallback(() => {
+ if (!alive.current || currentCall() !== group.id) return;
+ move("listening");
+ setSpeakingMemberId(null);
+ setHeard("");
+ setNote(null);
+ void bridge?.speechStart({ endpointMs: CALL_ENDPOINT_MS }).catch(() => {
+ if (alive.current && currentCall() === group.id) {
+ setNote(t("call.turns.micFailed"));
+ }
+ });
+ }, [bridge, group.id, move]);
+
+ const scheduleListen = useCallback(
+ (force = false, delay = 140) => {
+ if (listenTimer.current) clearTimeout(listenTimer.current);
+ listenTimer.current = setTimeout(() => {
+ listenTimer.current = null;
+ if (!alive.current || currentCall() !== group.id || queuedJobs.current.size) return;
+ if (force || allowBargeIn.current || !busyRef.current) listen();
+ }, delay);
+ },
+ [group.id, listen],
+ );
+
+ const defaultPlaybackRate = useRef(config?.tts?.playbackRate ?? 1);
+ defaultPlaybackRate.current = config?.tts?.playbackRate ?? 1;
+ const say = useCallback(
+ async (text: string, member?: Bot) => {
+ if (!alive.current || currentCall() !== group.id) return false;
+ const mine = ++sayGeneration.current;
+ move("speaking");
+ setSpeakingMemberId(member?.id ?? null);
+ hush();
+ await speaker.speak(text, { botId: member?.id, voiceId: member?.voice, playbackRate: member?.voicePlaybackRate ?? defaultPlaybackRate.current });
+ return alive.current && currentCall() === group.id && sayGeneration.current === mine;
+ },
+ [group.id, hush, move],
+ );
+
+ const enqueueSpeech = useCallback(
+ (text: string, member?: Bot, answerAfter = false) => {
+ const generation = queueGeneration.current;
+ const jobId = ++nextJobId.current;
+ queuedJobs.current.add(jobId);
+ if (answerAfter) listenWhenDrained.current = true;
+ queue.current = queue.current
+ .catch(() => {})
+ .then(async () => {
+ if (generation !== queueGeneration.current) return;
+ await say(text, member);
+ })
+ .finally(() => {
+ if (generation !== queueGeneration.current) return;
+ queuedJobs.current.delete(jobId);
+ if (queuedJobs.current.size) return;
+ setSpeakingMemberId(null);
+ const force = listenWhenDrained.current;
+ listenWhenDrained.current = false;
+ scheduleListen(force);
+ });
+ },
+ [say, scheduleListen],
+ );
+
+ const interruptSpeech = useCallback(() => {
+ const wasBusy = busyRef.current;
+ queueGeneration.current += 1;
+ queue.current = Promise.resolve();
+ queuedJobs.current.clear();
+ listenWhenDrained.current = false;
+ sayGeneration.current += 1;
+ speaker.stop();
+ setSpeakingMemberId(null);
+ allowBargeIn.current = true;
+ if (wasBusy) dispatch({ type: "interruptGroup", groupId: group.id });
+ listen();
+ }, [dispatch, group.id, listen]);
+
+ useEffect(() => {
+ alive.current = true;
+ return () => {
+ alive.current = false;
+ queueGeneration.current += 1;
+ sayGeneration.current += 1;
+ if (listenTimer.current) clearTimeout(listenTimer.current);
+ deferCallCleanup(group.id, () => alive.current);
+ };
+ }, [group.id]);
+
+ useEffect(() => {
+ if (!bridge) return;
+ const offTranscript = bridge.onSpeechTranscript((line) => {
+ if (!alive.current || currentCall() !== group.id || phaseRef.current !== "listening") return;
+ if (line.error) {
+ setNote(t("call.turns.dictationStopped"));
+ return;
+ }
+ if (typeof line.text !== "string") return;
+ setHeard(line.text);
+ if (line.partial !== false) return;
+ const said = line.text.trim();
+ if (!said) return listen();
+
+ const openApproval = askedApproval.current;
+ if (openApproval) {
+ if (openApproval.submitted) {
+ move("working");
+ hush();
+ return;
+ }
+ // English is read exactly as before; chineseConsent only adds the Chinese answers.
+ const decision = YES.test(said) ? "allow" : NO.test(said) ? "deny" : chineseConsent(said);
+ if (decision) {
+ const allow = decision === "allow";
+ if (allow && openApproval.skill) {
+ setHeard("");
+ enqueueSpeech(
+ "Open the group thread to review the complete skill before approving it. You can say no now to deny it.",
+ openApproval.member,
+ true,
+ );
+ return;
+ }
+ // In flight until its server patch arrives, so a slow response cannot reopen the microphone and submit it
+ // twice.
+ openApproval.submitted = true;
+ allowBargeIn.current = false;
+ move("working");
+ hush();
+ setHeard("");
+ dispatch({
+ type: "decideRequest",
+ threadId: group.threadId,
+ requestId: openApproval.requestId,
+ behavior: allow ? "allow" : "deny",
+ message: allow ? undefined : "Denied by the user, on a group call.",
+ onError: (error: string) => {
+ const pending = askedApproval.current;
+ if (
+ !alive.current ||
+ currentCall() !== group.id ||
+ pending?.requestId !== openApproval.requestId ||
+ !pending.submitted
+ ) return;
+ pending.submitted = false;
+ const detail = error.trim().slice(0, 240);
+ const decision = openApproval.routine ? "routine decision" : "approval";
+ enqueueSpeech(
+ `I couldn't save that ${decision}${detail ? `: ${detail}` : "."} Please try again.`,
+ openApproval.member,
+ true,
+ );
+ },
+ });
+ return;
+ }
+ enqueueSpeech("Sorry — is that a yes or a no?", openApproval.member, true);
+ return;
+ }
+
+ const openQuestion = askedQuestion.current;
+ if (openQuestion) {
+ askedQuestion.current = null;
+ allowBargeIn.current = false;
+ dispatch({
+ type: "decideRequest",
+ threadId: group.threadId,
+ requestId: openQuestion.requestId,
+ behavior: "answer",
+ message: said,
+ });
+ move("working");
+ return;
+ }
+
+ const routed = routeSpokenGroupMessage(said, membersRef.current);
+ if (defaultResponderRef.current.kind === "mentions" && !routed.addressed) {
+ listen();
+ const names = membersRef.current.map((member) => member.name).join(", ");
+ setNote(names ? t("call.group.sayNameOf", { names }) : t("call.group.sayName"));
+ return;
+ }
+
+ allowBargeIn.current = false;
+ move(busyRef.current ? "working" : "sending");
+ dispatch({ type: "sendGroup", groupId: group.id, text: routed.text, threadId: group.threadId });
+ scheduleListen(false, 600);
+ });
+ const offEnd = bridge.onSpeechEnd(({ code, reason, message }) => {
+ if (!alive.current || currentCall() !== group.id) return;
+ if (code === 2) {
+ setNote(t("call.turns.needsDictation"));
+ return;
+ }
+ if (code === 1) {
+ setNote(
+ message ?? t(callSpeechEndNote(reason)),
+ );
+ return;
+ }
+ if (phaseRef.current === "listening") listen();
+ });
+ if ((group.working || group.busyBotId) && !approval && !question) move("working");
+ else listen();
+ return () => {
+ offTranscript();
+ offEnd();
+ void bridge.speechStop();
+ };
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [bridge, dispatch, enqueueSpeech, group.id, group.threadId, hush, listen, move, scheduleListen]);
+
+ useEffect(() => {
+ let resumeAfterRoutine = false;
+ if (askedApproval.current && approval?.requestId !== askedApproval.current.requestId) {
+ resumeAfterRoutine = askedApproval.current.routine && askedApproval.current.submitted;
+ askedApproval.current = null;
+ }
+ if (askedQuestion.current && question?.card?.requestId !== askedQuestion.current.requestId) {
+ askedQuestion.current = null;
+ }
+
+ if (resumeAfterRoutine && !approval && !question && !group.working && !group.busyBotId) {
+ scheduleListen(true);
+ return;
+ }
+ // Voice queue and microphone stay closed until this exact decision settles or its request errors.
+ if (askedApproval.current?.submitted) return;
+
+ if (approval && askedApproval.current?.requestId !== approval.requestId) {
+ const member = members.find((candidate) => candidate.id === approval.message.from?.botId);
+ askedApproval.current = {
+ requestId: approval.requestId,
+ member,
+ routine: isRoutineApproval(approval),
+ skill: isSkillApproval(approval),
+ submitted: false,
+ };
+ spokenIds.current.add(approval.message.id);
+ const name = member?.name ?? approval.message.from?.name ?? "A group member";
+ const skillPrompt = approval.message.card?.skillRequest?.action === "update"
+ ? `${name} wants to update a learned skill. Open the group thread to review the complete skill before replacing the current version. You can say no to deny it.`
+ : `${name} wants to enable a new learned skill. Open the group thread to review the complete skill before enabling it. You can say no to deny it.`;
+ enqueueSpeech(isSkillApproval(approval) && !titledCard(approval.message.card) ? skillPrompt : spokenApprovalPrompt(approval, name), member, true);
+ }
+
+ if (question?.card?.requestId && askedQuestion.current?.requestId !== question.card.requestId) {
+ const member = members.find((candidate) => candidate.id === question.from?.botId);
+ askedQuestion.current = { requestId: question.card.requestId, member };
+ spokenIds.current.add(question.id);
+ const name = member?.name ?? question.from?.name ?? "A group member";
+ const detail = question.card.subtitle.trim();
+ const choices = question.card.options.length
+ ? " The options are " + question.card.options.join(", ") + "."
+ : "";
+ enqueueSpeech(
+ name + " asks: " + detail + (/[.!?]$/.test(detail) ? "" : ".") + choices,
+ member,
+ true,
+ );
+ }
+
+ const fresh = messages.filter((message) => !spokenIds.current.has(message.id));
+ if (!fresh.length) return;
+ for (const message of fresh) spokenIds.current.add(message.id);
+
+ const replies = fresh.filter(
+ (message) => message.role === "bot" && message.kind === "text" && message.text?.trim(),
+ );
+ for (const reply of replies) {
+ const member = members.find((candidate) => candidate.id === reply.from?.botId);
+ enqueueSpeech(reply.text!, member);
+ }
+ if (!replies.length) {
+ const chip = [...fresh].reverse().find((message) => message.kind === "activity" && message.tool?.spoken);
+ if (chip?.tool?.spoken) {
+ const member = members.find((candidate) => candidate.id === chip.from?.botId);
+ enqueueSpeech(chip.tool.spoken, member);
+ }
+ }
+ }, [approval, enqueueSpeech, group.busyBotId, group.working, members, messages, question, scheduleListen]);
+
+ useEffect(() => {
+ const busy = Boolean(group.working || group.busyBotId);
+ busyRef.current = busy;
+ if (busy) {
+ if (
+ (phaseRef.current === "listening" || phaseRef.current === "sending") &&
+ !askedApproval.current &&
+ !askedQuestion.current &&
+ !allowBargeIn.current
+ ) {
+ move("working");
+ hush();
+ }
+ return;
+ }
+ allowBargeIn.current = false;
+ if (
+ (phaseRef.current === "working" || phaseRef.current === "sending") &&
+ !askedApproval.current &&
+ !askedQuestion.current
+ ) {
+ scheduleListen();
+ }
+ }, [group.busyBotId, group.working, hush, move, scheduleListen]);
+
+ useEffect(() => {
+ const onKey = (event: KeyboardEvent) => {
+ if (event.key === "Escape") {
+ event.preventDefault();
+ endCall(group.id);
+ } else if (event.code === "Space" && speaker.isSpeaking()) {
+ event.preventDefault();
+ interruptSpeech();
+ }
+ };
+ window.addEventListener("keydown", onKey);
+ return () => window.removeEventListener("keydown", onKey);
+ }, [group.id, interruptSpeech]);
+
+ const speakingMember = members.find((member) => member.id === speakingMemberId);
+ const workingMember = members.find((member) => member.id === group.busyBotId);
+ const focusId = speakingMember?.id ?? workingMember?.id;
+ const status =
+ phase === "listening"
+ ? pushToTalk
+ ? t("call.turns.pushToTalk")
+ : t("call.turns.listening")
+ : phase === "sending"
+ ? t("call.group.bringingIn")
+ : phase === "speaking"
+ ? t("call.group.speaking", { name: speakingMember?.name ?? t("call.group.member") })
+ : workingMember
+ ? t("call.group.working", { name: workingMember.name })
+ : t("chat.activity.working");
+
+ return (
+ <div className="absolute inset-0 z-30 flex flex-col items-center justify-center gap-6 bg-app/95 px-8 backdrop-blur-sm">
+ <button
+ onClick={() => endCall(group.id)}
+ aria-label={t("call.live.hangUp")}
+ className="absolute right-5 top-5 rounded-md p-2 text-ink-secondary hover:bg-raised hover:text-ink"
+ >
+ <X size={18} />
+ </button>
+
+ <div className="max-w-full overflow-x-auto px-4 py-3">
+ <div className="flex min-w-max items-end justify-center gap-3">
+ {members.map((member) => {
+ const focused = member.id === focusId;
+ const state =
+ speakingMember?.id === member.id
+ ? "sending"
+ : workingMember?.id === member.id
+ ? "working"
+ : phase === "listening"
+ ? "listening"
+ : normalizeState(member.mascotExpression) ?? "happy";
+ return (
+ <div
+ key={member.id}
+ className={cn(
+ "flex w-[124px] flex-col items-center gap-2 rounded-2xl px-2 py-3 transition-all duration-200",
+ focused ? "scale-105 bg-raised/70 shadow-lg" : "opacity-75",
+ )}
+ >
+ <BotAvatar
+ bot={member}
+ state={state}
+ size={94}
+ animated
+ motion={workingMember?.id === member.id ? "working" : "none"}
+ motionKey={workingMember?.id === member.id ? 1 : 0}
+ />
+ <span className={cn("text-[13px] font-medium", focused ? "text-ink" : "text-ink-secondary")}>
+ {member.name}
+ </span>
+ </div>
+ );
+ })}
+ </div>
+ </div>
+
+ <div className="flex flex-col items-center gap-1.5 text-center">
+ <div className="text-[20px] font-medium text-ink">{group.name}</div>
+ <div className="flex items-center gap-2 text-[14px] text-ink-secondary">
+ {(phase === "working" || phase === "sending") && <Loader2 size={13} className="animate-spin" />}
+ {status}
+ </div>
+ </div>
+
+ <div className="min-h-[3.5rem] max-w-[620px] text-center text-[15px] leading-relaxed text-ink">
+ {phase === "listening" ? (
+ heard || (
+ <span className="text-ink-secondary">
+ {pushToTalk
+ ? t("call.turns.releaseToSend", { keys: pushToTalkKeys() })
+ : t("call.group.sayPrompt")}
+ </span>
+ )
+ ) : phase === "speaking" ? (
+ speech.caption
+ ) : (
+ <span className="text-ink-secondary">{workingMember ? t("call.group.inTurn") : ""}</span>
+ )}
+ </div>
+
+ {note && (
+ <div className="flex max-w-[520px] flex-col items-center gap-2 text-center text-[13px] text-warning">
+ {note !== dismissedNote && <span className="flex items-start gap-1.5"><span className="min-w-0 break-words">{note}</span><DismissWarning onDismiss={() => setDismissedNote(note)} /></span>}
+ <button
+ onClick={listen}
+ className="rounded-full border border-warning/40 px-3 py-1.5 text-[12px] hover:bg-warning/10"
+ >
+ {t("call.turns.tryMicrophone")}
+ </button>
+ </div>
+ )}
+ {speech.error && <div className="max-w-[460px] text-center text-[13px] text-danger">{speech.error}</div>}
+
+ <div className="flex items-center gap-3">
+ {speaker.isSpeaking() && (
+ <button
+ onClick={interruptSpeech}
+ className="rounded-full border border-hairline/50 px-4 py-2 text-[14px] text-ink hover:bg-raised"
+ >
+ {t("call.turns.interrupt")}
+ </button>
+ )}
+ <button
+ onClick={() => endCall(group.id)}
+ className="flex items-center gap-2 rounded-full bg-danger px-5 py-2.5 text-[14px] font-medium text-white hover:brightness-110"
+ >
+ <PhoneOff size={16} /> {t("call.live.hangUp")}
+ </button>
+ </div>
+
+ <div className="text-[12px] text-ink-tertiary">
+ {t("call.group.keysHint", { keys: pushToTalkKeys() })}
+ </div>
+ </div>
+ );
+}
diff --git a/src/components/GroupCallView.tsx b/src/components/GroupCallView.tsx
index b8fa17b54d..1cc8a92736 100644
--- a/src/components/GroupCallView.tsx
+++ b/src/components/GroupCallView.tsx
@@ -1,29 +1,12 @@
-// Half-duplex like CallView: the native recognizer has no echo cancellation. Replies are queued so a fast second member
-// never cuts off the first.
-import { useCallback, useEffect, useRef, useState } from "react";
-import { Loader2, PhoneOff, X } from "lucide-react";
-
-import { currentCall, deferCallCleanup, endCall, useOnCall } from "@/lib/call";
-import { routeSpokenGroupMessage } from "@/lib/group-call";
+import { lazy, Suspense } from "react";
+import { useOnCall } from "@/lib/call";
import { track } from "@/lib/analytics";
-import { normalizeState } from "@/lib/mascot";
-import { speaker } from "@/lib/tts";
-import { useSpeech } from "@/lib/tts/useSpeech";
-import { pushToTalkKeys, usePushToTalk } from "@/lib/push-to-talk";
-import { useStore, type Bot, type Group, type Message } from "@/state/store";
-import { t } from "@/lib/i18n";
-import { cn } from "@/lib/cn";
-import { BotAvatar } from "./Avatar";
+import type { Bot, Group } from "@/state/store";
import { CallTargetButton, type CallButtonPlacement } from "./CallView";
import { useAdvancedMode } from "@/lib/interface-mode";
-import { CALL_ENDPOINT_MS, callSpeechEndNote, speechBridge } from "@/lib/speech";
import { useDesktopCapabilities } from "./DesktopCapabilities";
-import { isRoutineApproval, isSkillApproval, pendingApprovals, spokenApprovalPrompt } from "./PendingApproval";
-import { titledCard } from "./ApprovalCard";
-import { chineseConsent, NO, YES } from "../../shared/call-consent";
-import { DismissWarning } from "./DismissWarning";
-type Phase = "listening" | "sending" | "working" | "speaking";
+const GroupCall = lazy(() => import("./GroupCallBody"));
/** `fill` (Simple composer): a round button in that colour, with its glyph in `ink`. */
export function GroupCallButton({ group, members, placement, fill, ink }: { group: Group; members: Bot[]; placement?: CallButtonPlacement; fill?: string; ink?: string }) {
@@ -54,523 +37,9 @@ export function RoomHeaderCallButton({ group, members }: { group: Group; members
export function GroupCallOverlay({ group, members }: { group: Group; members: Bot[] }) {
const active = useOnCall() === group.id;
if (!active) return null;
- return <GroupCall group={group} members={members} />;
-}
-
-function questionIn(messages: Message[]): Message | undefined {
- return messages.find(
- (message) =>
- message.kind === "options" &&
- message.card?.requestId &&
- !message.card.tool &&
- !message.card.answered &&
- !message.card.dismissed,
- );
-}
-
-function GroupCall({ group, members }: { group: Group; members: Bot[] }) {
- const { state, dispatch } = useStore();
- // One bridge for the whole call: a voice change mid-call must not stop or hear through another.
- const [bridge] = useState(() => speechBridge(state.config));
- const speech = useSpeech();
- const initialPhase: Phase = group.working || group.busyBotId ? "working" : "listening";
- const [phase, setPhase] = useState<Phase>(initialPhase);
- const [heard, setHeard] = useState("");
- const [note, setNote] = useState<string | null>(null);
- // The × hides this note's words only; "Try microphone" stays, since the call has stopped listening.
- const [dismissedNote, setDismissedNote] = useState<string | null>(null);
- const [speakingMemberId, setSpeakingMemberId] = useState<string | null>(null);
- const pushToTalk = usePushToTalk(group.id, bridge, phase === "listening", () => {
- setNote(t("call.turns.pushToTalkFailed"));
- });
-
- const messages = group.messages;
- const approval = pendingApprovals(messages)[0];
- const question = questionIn(messages);
- const membersRef = useRef(members);
- const busyRef = useRef(Boolean(group.working || group.busyBotId));
- const defaultResponderRef = useRef(group.defaultResponder);
- membersRef.current = members;
- busyRef.current = Boolean(group.working || group.busyBotId);
- defaultResponderRef.current = group.defaultResponder;
-
- const spokenIds = useRef<Set<string>>(new Set());
- const started = useRef(false);
- if (!started.current) {
- started.current = true;
- for (const message of messages) spokenIds.current.add(message.id);
- }
-
- const askedApproval = useRef<{
- requestId: string;
- member?: Bot;
- routine: boolean;
- skill: boolean;
- submitted: boolean;
- } | null>(null);
- const askedQuestion = useRef<{ requestId: string; member?: Bot } | null>(null);
- const phaseRef = useRef<Phase>(initialPhase);
- const alive = useRef(true);
- const sayGeneration = useRef(0);
- const queueGeneration = useRef(0);
- const queue = useRef<Promise<void>>(Promise.resolve());
- const queuedJobs = useRef(new Set<number>());
- const nextJobId = useRef(0);
- const listenWhenDrained = useRef(false);
- const listenTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
- const allowBargeIn = useRef(false);
-
- const move = useCallback((next: Phase) => {
- phaseRef.current = next;
- if (alive.current) setPhase(next);
- }, []);
-
- const hush = useCallback(() => {
- void bridge?.speechStop();
- }, [bridge]);
-
- const listen = useCallback(() => {
- if (!alive.current || currentCall() !== group.id) return;
- move("listening");
- setSpeakingMemberId(null);
- setHeard("");
- setNote(null);
- void bridge?.speechStart({ endpointMs: CALL_ENDPOINT_MS }).catch(() => {
- if (alive.current && currentCall() === group.id) {
- setNote(t("call.turns.micFailed"));
- }
- });
- }, [bridge, group.id, move]);
-
- const scheduleListen = useCallback(
- (force = false, delay = 140) => {
- if (listenTimer.current) clearTimeout(listenTimer.current);
- listenTimer.current = setTimeout(() => {
- listenTimer.current = null;
- if (!alive.current || currentCall() !== group.id || queuedJobs.current.size) return;
- if (force || allowBargeIn.current || !busyRef.current) listen();
- }, delay);
- },
- [group.id, listen],
- );
-
- const defaultPlaybackRate = useRef(state.config?.tts?.playbackRate ?? 1);
- defaultPlaybackRate.current = state.config?.tts?.playbackRate ?? 1;
- const say = useCallback(
- async (text: string, member?: Bot) => {
- if (!alive.current || currentCall() !== group.id) return false;
- const mine = ++sayGeneration.current;
- move("speaking");
- setSpeakingMemberId(member?.id ?? null);
- hush();
- await speaker.speak(text, { botId: member?.id, voiceId: member?.voice, playbackRate: member?.voicePlaybackRate ?? defaultPlaybackRate.current });
- return alive.current && currentCall() === group.id && sayGeneration.current === mine;
- },
- [group.id, hush, move],
- );
-
- const enqueueSpeech = useCallback(
- (text: string, member?: Bot, answerAfter = false) => {
- const generation = queueGeneration.current;
- const jobId = ++nextJobId.current;
- queuedJobs.current.add(jobId);
- if (answerAfter) listenWhenDrained.current = true;
- queue.current = queue.current
- .catch(() => {})
- .then(async () => {
- if (generation !== queueGeneration.current) return;
- await say(text, member);
- })
- .finally(() => {
- if (generation !== queueGeneration.current) return;
- queuedJobs.current.delete(jobId);
- if (queuedJobs.current.size) return;
- setSpeakingMemberId(null);
- const force = listenWhenDrained.current;
- listenWhenDrained.current = false;
- scheduleListen(force);
- });
- },
- [say, scheduleListen],
- );
-
- const interruptSpeech = useCallback(() => {
- const wasBusy = busyRef.current;
- queueGeneration.current += 1;
- queue.current = Promise.resolve();
- queuedJobs.current.clear();
- listenWhenDrained.current = false;
- sayGeneration.current += 1;
- speaker.stop();
- setSpeakingMemberId(null);
- allowBargeIn.current = true;
- if (wasBusy) dispatch({ type: "interruptGroup", groupId: group.id });
- listen();
- }, [dispatch, group.id, listen]);
-
- useEffect(() => {
- alive.current = true;
- return () => {
- alive.current = false;
- queueGeneration.current += 1;
- sayGeneration.current += 1;
- if (listenTimer.current) clearTimeout(listenTimer.current);
- deferCallCleanup(group.id, () => alive.current);
- };
- }, [group.id]);
-
- useEffect(() => {
- if (!bridge) return;
- const offTranscript = bridge.onSpeechTranscript((line) => {
- if (!alive.current || currentCall() !== group.id || phaseRef.current !== "listening") return;
- if (line.error) {
- setNote(t("call.turns.dictationStopped"));
- return;
- }
- if (typeof line.text !== "string") return;
- setHeard(line.text);
- if (line.partial !== false) return;
- const said = line.text.trim();
- if (!said) return listen();
-
- const openApproval = askedApproval.current;
- if (openApproval) {
- if (openApproval.submitted) {
- move("working");
- hush();
- return;
- }
- // English is read exactly as before; chineseConsent only adds the Chinese answers.
- const decision = YES.test(said) ? "allow" : NO.test(said) ? "deny" : chineseConsent(said);
- if (decision) {
- const allow = decision === "allow";
- if (allow && openApproval.skill) {
- setHeard("");
- enqueueSpeech(
- "Open the group thread to review the complete skill before approving it. You can say no now to deny it.",
- openApproval.member,
- true,
- );
- return;
- }
- // In flight until its server patch arrives, so a slow response cannot reopen the microphone and submit it
- // twice.
- openApproval.submitted = true;
- allowBargeIn.current = false;
- move("working");
- hush();
- setHeard("");
- dispatch({
- type: "decideRequest",
- threadId: group.threadId,
- requestId: openApproval.requestId,
- behavior: allow ? "allow" : "deny",
- message: allow ? undefined : "Denied by the user, on a group call.",
- onError: (error: string) => {
- const pending = askedApproval.current;
- if (
- !alive.current ||
- currentCall() !== group.id ||
- pending?.requestId !== openApproval.requestId ||
- !pending.submitted
- ) return;
- pending.submitted = false;
- const detail = error.trim().slice(0, 240);
- const decision = openApproval.routine ? "routine decision" : "approval";
- enqueueSpeech(
- `I couldn't save that ${decision}${detail ? `: ${detail}` : "."} Please try again.`,
- openApproval.member,
- true,
- );
- },
- });
- return;
- }
- enqueueSpeech("Sorry — is that a yes or a no?", openApproval.member, true);
- return;
- }
-
- const openQuestion = askedQuestion.current;
- if (openQuestion) {
- askedQuestion.current = null;
- allowBargeIn.current = false;
- dispatch({
- type: "decideRequest",
- threadId: group.threadId,
- requestId: openQuestion.requestId,
- behavior: "answer",
- message: said,
- });
- move("working");
- return;
- }
-
- const routed = routeSpokenGroupMessage(said, membersRef.current);
- if (defaultResponderRef.current.kind === "mentions" && !routed.addressed) {
- listen();
- const names = membersRef.current.map((member) => member.name).join(", ");
- setNote(names ? t("call.group.sayNameOf", { names }) : t("call.group.sayName"));
- return;
- }
-
- allowBargeIn.current = false;
- move(busyRef.current ? "working" : "sending");
- dispatch({ type: "sendGroup", groupId: group.id, text: routed.text, threadId: group.threadId });
- scheduleListen(false, 600);
- });
- const offEnd = bridge.onSpeechEnd(({ code, reason, message }) => {
- if (!alive.current || currentCall() !== group.id) return;
- if (code === 2) {
- setNote(t("call.turns.needsDictation"));
- return;
- }
- if (code === 1) {
- setNote(
- message ?? t(callSpeechEndNote(reason)),
- );
- return;
- }
- if (phaseRef.current === "listening") listen();
- });
- if ((group.working || group.busyBotId) && !approval && !question) move("working");
- else listen();
- return () => {
- offTranscript();
- offEnd();
- void bridge.speechStop();
- };
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [bridge, dispatch, enqueueSpeech, group.id, group.threadId, hush, listen, move, scheduleListen]);
-
- useEffect(() => {
- let resumeAfterRoutine = false;
- if (askedApproval.current && approval?.requestId !== askedApproval.current.requestId) {
- resumeAfterRoutine = askedApproval.current.routine && askedApproval.current.submitted;
- askedApproval.current = null;
- }
- if (askedQuestion.current && question?.card?.requestId !== askedQuestion.current.requestId) {
- askedQuestion.current = null;
- }
-
- if (resumeAfterRoutine && !approval && !question && !group.working && !group.busyBotId) {
- scheduleListen(true);
- return;
- }
- // Voice queue and microphone stay closed until this exact decision settles or its request errors.
- if (askedApproval.current?.submitted) return;
-
- if (approval && askedApproval.current?.requestId !== approval.requestId) {
- const member = members.find((candidate) => candidate.id === approval.message.from?.botId);
- askedApproval.current = {
- requestId: approval.requestId,
- member,
- routine: isRoutineApproval(approval),
- skill: isSkillApproval(approval),
- submitted: false,
- };
- spokenIds.current.add(approval.message.id);
- const name = member?.name ?? approval.message.from?.name ?? "A group member";
- const skillPrompt = approval.message.card?.skillRequest?.action === "update"
- ? `${name} wants to update a learned skill. Open the group thread to review the complete skill before replacing the current version. You can say no to deny it.`
- : `${name} wants to enable a new learned skill. Open the group thread to review the complete skill before enabling it. You can say no to deny it.`;
- enqueueSpeech(isSkillApproval(approval) && !titledCard(approval.message.card) ? skillPrompt : spokenApprovalPrompt(approval, name), member, true);
- }
-
- if (question?.card?.requestId && askedQuestion.current?.requestId !== question.card.requestId) {
- const member = members.find((candidate) => candidate.id === question.from?.botId);
- askedQuestion.current = { requestId: question.card.requestId, member };
- spokenIds.current.add(question.id);
- const name = member?.name ?? question.from?.name ?? "A group member";
- const detail = question.card.subtitle.trim();
- const choices = question.card.options.length
- ? " The options are " + question.card.options.join(", ") + "."
- : "";
- enqueueSpeech(
- name + " asks: " + detail + (/[.!?]$/.test(detail) ? "" : ".") + choices,
- member,
- true,
- );
- }
-
- const fresh = messages.filter((message) => !spokenIds.current.has(message.id));
- if (!fresh.length) return;
- for (const message of fresh) spokenIds.current.add(message.id);
-
- const replies = fresh.filter(
- (message) => message.role === "bot" && message.kind === "text" && message.text?.trim(),
- );
- for (const reply of replies) {
- const member = members.find((candidate) => candidate.id === reply.from?.botId);
- enqueueSpeech(reply.text!, member);
- }
- if (!replies.length) {
- const chip = [...fresh].reverse().find((message) => message.kind === "activity" && message.tool?.spoken);
- if (chip?.tool?.spoken) {
- const member = members.find((candidate) => candidate.id === chip.from?.botId);
- enqueueSpeech(chip.tool.spoken, member);
- }
- }
- }, [approval, enqueueSpeech, group.busyBotId, group.working, members, messages, question, scheduleListen]);
-
- useEffect(() => {
- const busy = Boolean(group.working || group.busyBotId);
- busyRef.current = busy;
- if (busy) {
- if (
- (phaseRef.current === "listening" || phaseRef.current === "sending") &&
- !askedApproval.current &&
- !askedQuestion.current &&
- !allowBargeIn.current
- ) {
- move("working");
- hush();
- }
- return;
- }
- allowBargeIn.current = false;
- if (
- (phaseRef.current === "working" || phaseRef.current === "sending") &&
- !askedApproval.current &&
- !askedQuestion.current
- ) {
- scheduleListen();
- }
- }, [group.busyBotId, group.working, hush, move, scheduleListen]);
-
- useEffect(() => {
- const onKey = (event: KeyboardEvent) => {
- if (event.key === "Escape") {
- event.preventDefault();
- endCall(group.id);
- } else if (event.code === "Space" && speaker.isSpeaking()) {
- event.preventDefault();
- interruptSpeech();
- }
- };
- window.addEventListener("keydown", onKey);
- return () => window.removeEventListener("keydown", onKey);
- }, [group.id, interruptSpeech]);
-
- const speakingMember = members.find((member) => member.id === speakingMemberId);
- const workingMember = members.find((member) => member.id === group.busyBotId);
- const focusId = speakingMember?.id ?? workingMember?.id;
- const status =
- phase === "listening"
- ? pushToTalk
- ? t("call.turns.pushToTalk")
- : t("call.turns.listening")
- : phase === "sending"
- ? t("call.group.bringingIn")
- : phase === "speaking"
- ? t("call.group.speaking", { name: speakingMember?.name ?? t("call.group.member") })
- : workingMember
- ? t("call.group.working", { name: workingMember.name })
- : t("chat.activity.working");
-
return (
- <div className="absolute inset-0 z-30 flex flex-col items-center justify-center gap-6 bg-app/95 px-8 backdrop-blur-sm">
- <button
- onClick={() => endCall(group.id)}
- aria-label={t("call.live.hangUp")}
- className="absolute right-5 top-5 rounded-md p-2 text-ink-secondary hover:bg-raised hover:text-ink"
- >
- <X size={18} />
- </button>
-
- <div className="max-w-full overflow-x-auto px-4 py-3">
- <div className="flex min-w-max items-end justify-center gap-3">
- {members.map((member) => {
- const focused = member.id === focusId;
- const state =
- speakingMember?.id === member.id
- ? "sending"
- : workingMember?.id === member.id
- ? "working"
- : phase === "listening"
- ? "listening"
- : normalizeState(member.mascotExpression) ?? "happy";
- return (
- <div
- key={member.id}
- className={cn(
- "flex w-[124px] flex-col items-center gap-2 rounded-2xl px-2 py-3 transition-all duration-200",
- focused ? "scale-105 bg-raised/70 shadow-lg" : "opacity-75",
- )}
- >
- <BotAvatar
- bot={member}
- state={state}
- size={94}
- animated
- motion={workingMember?.id === member.id ? "working" : "none"}
- motionKey={workingMember?.id === member.id ? 1 : 0}
- />
- <span className={cn("text-[13px] font-medium", focused ? "text-ink" : "text-ink-secondary")}>
- {member.name}
- </span>
- </div>
- );
- })}
- </div>
- </div>
-
- <div className="flex flex-col items-center gap-1.5 text-center">
- <div className="text-[20px] font-medium text-ink">{group.name}</div>
- <div className="flex items-center gap-2 text-[14px] text-ink-secondary">
- {(phase === "working" || phase === "sending") && <Loader2 size={13} className="animate-spin" />}
- {status}
- </div>
- </div>
-
- <div className="min-h-[3.5rem] max-w-[620px] text-center text-[15px] leading-relaxed text-ink">
- {phase === "listening" ? (
- heard || (
- <span className="text-ink-secondary">
- {pushToTalk
- ? t("call.turns.releaseToSend", { keys: pushToTalkKeys() })
- : t("call.group.sayPrompt")}
- </span>
- )
- ) : phase === "speaking" ? (
- speech.caption
- ) : (
- <span className="text-ink-secondary">{workingMember ? t("call.group.inTurn") : ""}</span>
- )}
- </div>
-
- {note && (
- <div className="flex max-w-[520px] flex-col items-center gap-2 text-center text-[13px] text-warning">
- {note !== dismissedNote && <span className="flex items-start gap-1.5"><span className="min-w-0 break-words">{note}</span><DismissWarning onDismiss={() => setDismissedNote(note)} /></span>}
- <button
- onClick={listen}
- className="rounded-full border border-warning/40 px-3 py-1.5 text-[12px] hover:bg-warning/10"
- >
- {t("call.turns.tryMicrophone")}
- </button>
- </div>
- )}
- {speech.error && <div className="max-w-[460px] text-center text-[13px] text-danger">{speech.error}</div>}
-
- <div className="flex items-center gap-3">
- {speaker.isSpeaking() && (
- <button
- onClick={interruptSpeech}
- className="rounded-full border border-hairline/50 px-4 py-2 text-[14px] text-ink hover:bg-raised"
- >
- {t("call.turns.interrupt")}
- </button>
- )}
- <button
- onClick={() => endCall(group.id)}
- className="flex items-center gap-2 rounded-full bg-danger px-5 py-2.5 text-[14px] font-medium text-white hover:brightness-110"
- >
- <PhoneOff size={16} /> {t("call.live.hangUp")}
- </button>
- </div>
-
- <div className="text-[12px] text-ink-tertiary">
- {t("call.group.keysHint", { keys: pushToTalkKeys() })}
- </div>
- </div>
+ <Suspense fallback={null}>
+ <GroupCall group={group} members={members} />
+ </Suspense>
);
}
diff --git a/src/components/PlaceTint.tsx b/src/components/PlaceTint.tsx
index 1557d31044..a35f89bec7 100644
--- a/src/components/PlaceTint.tsx
+++ b/src/components/PlaceTint.tsx
@@ -1,7 +1,7 @@
import { useState, type CSSProperties } from "react";
import { bannerSrc, type BannerSummary } from "@/lib/place-banner";
import { placeTint, usePlaceLook } from "@/lib/place-look";
-import { useStore } from "@/state/store";
+import { useStoreSelector } from "@/state/store-select";
/** What the top of the sidebar shows, first that applies: the workspace's banner picture (kept on its own server), the
* place's colour, or nothing as it always was. Under the picture the colour waits for a picture that won't load, and
@@ -21,6 +21,6 @@ export function PlaceTop({ banner, color }: { banner: BannerSummary | null | und
/** The sidebar's own: this page's banner from its server's settings, and its place's colour from the app. */
export function PlaceTint() {
- const { state } = useStore();
- return <PlaceTop banner={state.config?.workspaceBanner} color={usePlaceLook()?.color} />;
+ const banner = useStoreSelector((state) => state.config?.workspaceBanner);
+ return <PlaceTop banner={banner} color={usePlaceLook()?.color} />;
}
diff --git a/src/components/RoomHeader.tsx b/src/components/RoomHeader.tsx
index 2ffc8d0fa5..9e5c6103b8 100644
--- a/src/components/RoomHeader.tsx
+++ b/src/components/RoomHeader.tsx
@@ -11,7 +11,8 @@ import { openRoomPanel } from "@/lib/room-panel";
import { chosenResponder, responderChoice, responderTitle } from "@/lib/room-responder";
import { busyPlaceOf, roomSpeakerIds } from "@/lib/room-threads";
import { formatTokens } from "@/lib/usage";
-import { useStore, type Bot, type Group } from "@/state/store";
+import type { Bot, Group } from "@/state/store";
+import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select";
import type { RoomQueueEntry } from "../../shared/wire";
import { BotAvatar } from "./Avatar";
import { RoomContextBadge } from "./ContextWarning";
@@ -29,8 +30,8 @@ import { GroupTaskPicker } from "./TaskPicker";
import { ThreadPresenceFaces } from "./TeamPresence";
export function DefaultResponderSelect({ group, members }: { group: Group; members: Bot[] }) {
- const { state, dispatch } = useStore();
- const jevOn = jevRoomRoutingOn(state.config);
+ const jevOn = useStoreSelector((state) => jevRoomRoutingOn(state.config));
+ const dispatch = useStoreDispatch();
const responder = effectiveDefaultResponder(group, members);
const change = (nextValue: string) => {
@@ -152,8 +153,9 @@ export function RoomHeader({
feed?: boolean;
}) {
const { dragProps: headerDragProps, noDragStyle: headerNoDragStyle } = useCaptionChrome();
- const { state, dispatch } = useStore();
- const faces = memberMauses(group, members, busyPlaceOf(state.groups, state.bots));
+ const { groups, bots } = useStoreSelector((state) => ({ groups: state.groups, bots: state.bots }), sameFields);
+ const dispatch = useStoreDispatch();
+ const faces = memberMauses(group, members, busyPlaceOf(groups, bots));
const pinned = (
<PinnedMessagesMenu
pins={pinnedPreview(group.messages, group.pinnedMessageId, t("room.aBot"), false)}
diff --git a/src/components/RoomQueueList.tsx b/src/components/RoomQueueList.tsx
index ab5a2c1631..3233e0a8a5 100644
--- a/src/components/RoomQueueList.tsx
+++ b/src/components/RoomQueueList.tsx
@@ -1,15 +1,16 @@
import { t } from "@/lib/i18n";
import { busyPlaceOf, roomQueueLabel, roomThreadQueue } from "@/lib/room-threads";
import type { RoomQueueEntry } from "../../shared/wire";
-import { useStore, type Bot, type Group, type Message } from "@/state/store";
+import type { Bot, Group, Message } from "@/state/store";
+import { sameFields, useStoreSelector } from "@/state/store-select";
const nameIn = (members: Bot[]) => (botId: string) => members.find((member) => member.id === botId)?.name;
export function RoomQueueList({ group, members }: { group: Group; members: Bot[] }) {
- const { state } = useStore();
const queued = roomThreadQueue(group, group.threadId);
+ const { groups, bots } = useStoreSelector((state) => (queued.length ? { groups: state.groups, bots: state.bots } : { groups: undefined, bots: undefined }), sameFields);
if (!queued.length) return null;
- const nameOf = nameIn(members), placeOf = busyPlaceOf(state.groups, state.bots);
+ const nameOf = nameIn(members), placeOf = busyPlaceOf(groups ?? [], bots ?? []);
return (
<ul data-testid="room-queue" className="flex flex-col gap-0.5 pl-12 text-[13px] text-ink-secondary">
{queued.map((entry) => (
diff --git a/src/components/SavedStepsRow.tsx b/src/components/SavedStepsRow.tsx
index 9cc3544b88..e7a464f9f2 100644
--- a/src/components/SavedStepsRow.tsx
+++ b/src/components/SavedStepsRow.tsx
@@ -2,16 +2,18 @@ import { useState } from "react";
import { savedStepsEnabled, savedStepsHere } from "@/lib/feature-flags";
import { t } from "@/lib/i18n";
-import { api, useStore, type ConfigStatus } from "@/state/store";
+import { api, type ConfigStatus } from "@/state/store";
+import { useStoreDispatch, useStoreSelector } from "@/state/store-select";
import { SettingRow, Switch } from "./SettingsPrimitives";
export function SavedStepsRow() {
- const { state, dispatch } = useStore();
- const on = savedStepsEnabled(state.config);
+ const config = useStoreSelector((state) => state.config);
+ const dispatch = useStoreDispatch();
+ const on = savedStepsEnabled(config);
const [saving, setSaving] = useState(false);
const [error, setError] = useState("");
- if (!savedStepsHere(state.config)) return null;
+ if (!savedStepsHere(config)) return null;
const toggle = async () => {
if (saving) return;
setSaving(true);
diff --git a/src/components/SearchResults.tsx b/src/components/SearchResults.tsx
index 7bea66eded..7a519c7989 100644
--- a/src/components/SearchResults.tsx
+++ b/src/components/SearchResults.tsx
@@ -1,6 +1,8 @@
import { useEffect, useState } from "react";
import { GitBranch, Wrench } from "lucide-react";
-import { api, useStore, formatTime } from "@/state/store";
+import { api, formatTime } from "@/state/store";
+import { useStoreRef } from "@/state/store-ref";
+import { useStoreSelector } from "@/state/store-select";
import { BotAvatar } from "./Avatar";
import { cn } from "@/lib/cn";
import type { SearchHit } from "@/lib/search-hit";
@@ -12,7 +14,8 @@ export const MIN_QUERY = 2;
const DEBOUNCE_MS = 250;
export function SearchResults({ query, onLanded }: { query: string; onLanded: () => void }) {
- const { state, dispatch } = useStore();
+ const bots = useStoreSelector((state) => state.bots);
+ const store = useStoreRef();
const showThreads = useShowThreads();
const [hits, setHits] = useState<SearchHit[] | null>(null);
const [error, setError] = useState<string | null>(null);
@@ -42,10 +45,10 @@ export function SearchResults({ query, onLanded }: { query: string; onLanded: ()
const land = async (hit: SearchHit) => {
try {
- await landOnSearchHit(hit, state, dispatch, showThreads);
+ await landOnSearchHit(hit, store.state(), store.dispatch, showThreads);
onLanded();
} catch (e) {
- dispatch({ type: "error", message: e instanceof Error ? e.message : String(e) });
+ store.dispatch({ type: "error", message: e instanceof Error ? e.message : String(e) });
}
};
@@ -57,7 +60,7 @@ export function SearchResults({ query, onLanded }: { query: string; onLanded: ()
{error && <div className="px-3 py-2 text-[13px] text-danger">{t("search.failed", { error })}</div>}
{hits && hits.length === 0 && !error && <div className="px-3 py-3 text-[13px] text-ink-secondary">{t("search.noMatch", { query: q })}</div>}
{hits?.map((hit) => {
- const bot = hit.botId ? state.bots.find((b) => b.id === hit.botId) : undefined;
+ const bot = hit.botId ? bots.find((b) => b.id === hit.botId) : undefined;
const before = hit.snippet.slice(0, hit.matchStart);
const match = hit.snippet.slice(hit.matchStart, hit.matchStart + hit.matchLength);
const after = hit.snippet.slice(hit.matchStart + hit.matchLength);
diff --git a/src/components/Sidebar.tsx b/src/components/Sidebar.tsx
index b41af22bf2..e921bf4290 100644
--- a/src/components/Sidebar.tsx
+++ b/src/components/Sidebar.tsx
@@ -1,5 +1,5 @@
import { OrganizationIdentity } from "./OrganizationIdentity";
-import { memo, useCallback, useEffect, useMemo, useRef, useState, type CSSProperties, type Dispatch } from "react";
+import { lazy, memo, Suspense, useCallback, useEffect, useMemo, useRef, useState, type CSSProperties, type Dispatch } from "react";
import { createPortal } from "react-dom";
import { Archive, Bot as BotIcon, Check, ChevronRight, ClipboardCopy, Crown, FolderInput, FolderPlus, LayoutTemplate, Loader2, MessageSquarePlus, MoreHorizontal, Pencil, Phone, Pin, Plus, Search, SquarePen, TextQuote, Trash2, Users, X } from "lucide-react";
import { botPendingQueued, botRoutineRuns, sameBotRowProps, sidebarState } from "./sidebar-state"; import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select"; import { useStoreRef } from "@/state/store-ref"; import { sameDrawnBots } from "@/lib/drawn-bots";
@@ -28,7 +28,7 @@ import { RoomMark, StackedMauses } from "./StackedMauses";
import { LocalComputerAutoWarning } from "./LocalComputerAutoWarning";
import { nextRename } from "@/lib/rename";
import { useDesktopCapabilities, windowFramed } from "./DesktopCapabilities";
-import { MIN_QUERY, SearchResults } from "./SearchResults";
+const MIN_QUERY = 2; const SearchResults = lazy(() => import("./SearchResults").then((m) => ({ default: m.SearchResults })));
import { ImportDialog, ShareTemplateDialog, TeamDialog, TeamLibraryPanel, TeamSettingsDialog } from "./lazy-screens";
import { SidebarNewChatPanel } from "./SidebarNewChatPanel";
import { openCommandPalette } from "./CommandPalette";
@@ -104,7 +104,7 @@ import { myDefaultBot, useViewerEmail, useWelcomingBot } from "@/lib/default-bot
import { PinnedBotRoster, PinnedCircleThreadSection } from "./PinnedCircleThreads";
import { archiveBotWithNotice, onArchiveNotice, type ArchiveNotice } from "./bot-archive";
import { ArchivedBotsPanel, botConfirmProps, type BotConfirmKind } from "./ArchivedBotsPanel"; import { MovedBotRows } from "./MoveToTeam"; import { MovedToMyCloudRow } from "./MoveToMyCloud";
-import { NewRoomPanel } from "./SidebarNewRoomPanel";
+const NewRoomPanel = lazy(() => import("./SidebarNewRoomPanel").then((m) => ({ default: m.NewRoomPanel })));
import { SectionPicker } from "./SidebarSectionPicker";
export { PinnedBotCircle, PinnedCircleThreadPanel, PinnedCircleThreadSection } from "./PinnedCircleThreads";
@@ -1454,7 +1454,7 @@ export const Sidebar = memo(function Sidebar({ open, onClose, collapseToIcons =
</div>
);
})}
- <OtherPlaceLine query={query} icons={density === "icons"} /><PlacedBotMenuHost /><MovedBotRows bots={state.bots} /><MovedToMyCloudRow bots={state.bots} /><SearchResults query={query} onLanded={() => { setQuery(""); setSearchOpen(false); }} />
+ <OtherPlaceLine query={query} icons={density === "icons"} /><PlacedBotMenuHost /><MovedBotRows bots={state.bots} /><MovedToMyCloudRow bots={state.bots} />{query.trim().length >= MIN_QUERY && <Suspense fallback={null}><SearchResults query={query} onLanded={() => { setQuery(""); setSearchOpen(false); }} /></Suspense>}
{showPinnedCircleThreads && (
<PinnedCircleThreadSection
bots={pinnedBots}
@@ -1581,7 +1581,7 @@ export const Sidebar = memo(function Sidebar({ open, onClose, collapseToIcons =
dispatch({ type: "patchGroup", groupId: roomSectionPicker.groupId, patch: { section } });
}}
/>
- {newRoom && <NewRoomPanel onClose={() => setNewRoom(false)} />}
+ {newRoom && <Suspense fallback={null}><NewRoomPanel onClose={() => setNewRoom(false)} /></Suspense>}
{/* Portaled: below md the sidebar's translate makes it the containing block for fixed children. */}
{newChatOpen && createPortal(
<SidebarNewChatPanel
diff --git a/src/components/SidebarConnectApps.tsx b/src/components/SidebarConnectApps.tsx
index f3e777bd60..ff7592a752 100644
--- a/src/components/SidebarConnectApps.tsx
+++ b/src/components/SidebarConnectApps.tsx
@@ -3,7 +3,7 @@ import { useEffect, useState } from "react";
import { cn } from "@/lib/cn";
import { t } from "@/lib/i18n";
-import { useStore } from "@/state/store";
+import { useStoreDispatch, useStoreSelector } from "@/state/store-select";
import { loadAppCards } from "./bot-settings/useBotApps";
import { preloadConnectedApps } from "@/lib/connected-apps";
@@ -32,10 +32,10 @@ interface SidebarApps {
}
function useSidebarApps(): SidebarApps {
- const { state } = useStore();
+ const pluginsOpen = useStoreSelector((state) => state.pluginsOpen);
const [apps, setApps] = useState<SidebarApps>(() => ({ faces: appFaces([], new Map()), connected: false }));
useEffect(() => {
- if (state.pluginsOpen) return;
+ if (pluginsOpen) return;
let alive = true;
void preloadConnectedApps()
.then(async (inventory) => {
@@ -45,7 +45,7 @@ function useSidebarApps(): SidebarApps {
})
.catch(() => {});
return () => { alive = false; };
- }, [state.pluginsOpen]);
+ }, [pluginsOpen]);
return apps;
}
@@ -67,7 +67,8 @@ const FAN = ["motion-safe:group-hover/apps:-translate-x-[3px] motion-safe:group-
/** `circle` is the collapsed rail's round button. */
export function SidebarConnectApps({ circle = false }: { circle?: boolean }) {
- const { state, dispatch } = useStore();
+ const pluginsOpen = useStoreSelector((state) => state.pluginsOpen);
+ const dispatch = useStoreDispatch();
const { faces, connected } = useSidebarApps();
const label = connected ? t("sidebar.nav.apps") : t("sidebar.connectApps");
return (
@@ -75,7 +76,7 @@ export function SidebarConnectApps({ circle = false }: { circle?: boolean }) {
type="button"
data-tour="nav-apps"
data-sidebar-nav="apps"
- aria-pressed={state.pluginsOpen}
+ aria-pressed={pluginsOpen}
aria-label={circle ? label : undefined}
title={circle ? label : undefined}
onClick={() => dispatch({ type: "togglePlugins", open: true })}
diff --git a/src/components/SidebarFooter.tsx b/src/components/SidebarFooter.tsx
index db3b4ce6a0..2774c3e99e 100644
--- a/src/components/SidebarFooter.tsx
+++ b/src/components/SidebarFooter.tsx
@@ -4,7 +4,7 @@ import { useRef } from "react";
import { cn } from "@/lib/cn";
import { t } from "@/lib/i18n";
import type { SidebarDensity } from "@/lib/sidebar-preferences";
-import { useStore } from "@/state/store";
+import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select";
import { AccountMoveStatus, useAccountMoveLine } from "./AccountMove";
import { CloudRoomCard } from "./CloudRoomCard";
@@ -18,8 +18,9 @@ import { SidebarProfileMenu, useSimpleAccount, type ArchivedBots } from "./Sideb
import { UpdateIndicator } from "./UpdateIndicator";
export function useSimplePlace(): WorkspacePlace {
- const { state, dispatch } = useStore();
- return useWorkspacePlace({ cloudHome: state.config?.cloudHome === true, howTo: state.cloudHowTo, onMenuClosed: () => endCloudHowTo(dispatch) });
+ const { cloudHome, howTo } = useStoreSelector((state) => ({ cloudHome: state.config?.cloudHome === true, howTo: state.cloudHowTo }), sameFields);
+ const dispatch = useStoreDispatch();
+ return useWorkspacePlace({ cloudHome, howTo, onMenuClosed: () => endCloudHowTo(dispatch) });
}
export function SidebarPlaceStatus({ place, className }: { place: WorkspacePlace; className?: string }) {
@@ -29,10 +30,10 @@ export function SidebarPlaceStatus({ place, className }: { place: WorkspacePlace
}
function SimpleSidebarFooter({ owner, archived }: { owner: string | null; archived?: ArchivedBots }) {
- const { state } = useStore();
+ const cloudHome = useStoreSelector((state) => state.config?.cloudHome === true);
const place = useSimplePlace();
const account = useSimpleAccount(place, owner, archived);
- const move = useAccountMoveLine(state.config?.cloudHome === true);
+ const move = useAccountMoveLine(cloudHome);
const footer = useRef<HTMLDivElement>(null);
// The move's words open the account menu just below them, where the move's row is.
const openAccount = () => footer.current?.querySelector("[data-sidebar-account]")?.closest("button")?.click();
@@ -81,7 +82,7 @@ export function SidebarFooter({ density, simple = false, owner = null, archived,
toolsCollapsed: boolean;
onToggleTools?: () => void;
}) {
- const { dispatch } = useStore();
+ const dispatch = useStoreDispatch();
const automationsNeedYou = useAutomationsNeedYou();
if (simple) return <SimpleSidebarFooter owner={owner} archived={archived} />;
const icons = density === "icons";
diff --git a/src/components/SidebarFooterNav.tsx b/src/components/SidebarFooterNav.tsx
index dfb5bc6597..c7d1911e1f 100644
--- a/src/components/SidebarFooterNav.tsx
+++ b/src/components/SidebarFooterNav.tsx
@@ -9,7 +9,7 @@ import { t } from "@/lib/i18n";
import { useAdvancedMode } from "@/lib/interface-mode";
import { useWebPanels } from "@/lib/web-panel-preferences";
import { useSidebarToolsLayout, type SidebarDensity } from "@/lib/sidebar-preferences";
-import { useStore } from "@/state/store";
+import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select";
import { SidebarSectionHeader } from "./SidebarSectionHeader";
import { UpdateIndicator } from "./UpdateIndicator";
@@ -65,7 +65,8 @@ function NavRow({
}
export function SidebarAppsButton() {
- const { state, dispatch } = useStore();
+ const pluginsOpen = useStoreSelector((state) => state.pluginsOpen);
+ const dispatch = useStoreDispatch();
const label = t("sidebar.nav.apps");
return (
<button
@@ -75,10 +76,10 @@ export function SidebarAppsButton() {
onClick={() => dispatch({ type: "togglePlugins", open: true })}
aria-label={label}
title={label}
- aria-pressed={state.pluginsOpen}
+ aria-pressed={pluginsOpen}
className={cn(
"flex size-9 shrink-0 items-center justify-center rounded-xl transition-colors",
- state.pluginsOpen ? "bg-raised text-accent" : "text-ink-secondary hover:bg-raised/50 hover:text-ink",
+ pluginsOpen ? "bg-raised text-accent" : "text-ink-secondary hover:bg-raised/50 hover:text-ink",
)}
>
<Puzzle size={16} />
@@ -88,12 +89,12 @@ export function SidebarAppsButton() {
/** An unseen failed run of an automation the Automations page lists (the same list, so opening it clears the dot), or an app trigger in trouble. */
export function useAutomationsNeedYou(): boolean {
- const { state } = useStore();
+ const { routines, webhooks, routineRuns, bots } = useStoreSelector((state) => ({ routines: state.routines, webhooks: state.webhooks, routineRuns: state.routineRuns, bots: state.bots }), sameFields);
const appTriggers = useAppTriggers();
const routinesOnly = typeof window !== "undefined" && window.ogb?.remoteClient?.active === true;
const unseenProblem = useMemo(() => hasUnseenProblemRun(automationsFrom({
- routines: state.routines, webhooks: routinesOnly ? [] : state.webhooks, appTriggers: appTriggers.triggers, runs: state.routineRuns, bots: state.bots,
- })), [state.routines, state.webhooks, appTriggers.triggers, state.routineRuns, state.bots, routinesOnly]);
+ routines, webhooks: routinesOnly ? [] : webhooks, appTriggers: appTriggers.triggers, runs: routineRuns, bots,
+ })), [routines, webhooks, appTriggers.triggers, routineRuns, bots, routinesOnly]);
return unseenProblem || appTriggers.triggers.some((trigger) => trigger.enabled && trigger.problem);
}
@@ -117,7 +118,8 @@ export function SidebarFooterNav({
collapsed?: boolean;
onToggleCollapsed?: () => void;
}) {
- const { state, dispatch } = useStore();
+ const { activeView, pluginsOpen, hasTeam, webPanelId } = useStoreSelector((state) => ({ activeView: state.activeView, pluginsOpen: state.pluginsOpen, hasTeam: Boolean(state.config?.team), webPanelId: state.webPanelId }), sameFields);
+ const dispatch = useStoreDispatch();
const advanced = useAdvancedMode();
const webPanels = useWebPanels();
const iconsOnly = density === "icons";
@@ -132,7 +134,7 @@ export function SidebarFooterNav({
label={t("sidebar.nav.automations")}
tourId="nav-automations"
iconsOnly={iconsOnly || toolbar}
- active={state.activeView === "routines"}
+ active={activeView === "routines"}
attention={automationsNeedYou}
icon={(active) => <Zap size={iconSize} className={tone(active)} />}
onClick={() => dispatch({ type: "showRoutines", view: "list" })}
@@ -142,7 +144,7 @@ export function SidebarFooterNav({
label={t("sidebar.nav.files")}
iconsOnly={iconsOnly}
rail={rail}
- active={state.activeView === "files"}
+ active={activeView === "files"}
icon={(active) => <FolderOpen size={iconSize} className={tone(active)} />}
onClick={() => dispatch({ type: "showFiles" })}
/>;
@@ -153,7 +155,7 @@ export function SidebarFooterNav({
tourId="nav-apps"
iconsOnly={iconsOnly}
rail={rail}
- active={state.pluginsOpen}
+ active={pluginsOpen}
icon={(active) => <Puzzle size={iconSize} className={tone(active)} />}
onClick={() => dispatch({ type: "togglePlugins", open: true })}
/>;
@@ -169,7 +171,7 @@ export function SidebarFooterNav({
label={t("sidebar.nav.teamMap")}
tourId="team-tools"
iconsOnly={iconsOnly || toolbar}
- active={state.activeView === "team-map"}
+ active={activeView === "team-map"}
icon={(active) => <UsersRound size={iconSize} className={tone(active)} />}
onClick={() => dispatch({ type: "showTeamMap" })}
/>
@@ -179,16 +181,16 @@ export function SidebarFooterNav({
id="published-apps"
label={t("sidebar.nav.publishedApps")}
iconsOnly={iconsOnly || toolbar}
- active={state.activeView === "published-apps"}
+ active={activeView === "published-apps"}
icon={(active) => <Rocket size={iconSize} className={tone(active)} />}
onClick={() => dispatch({ type: "showPublishedApps" })}
/>
- {state.config?.team && (
+ {hasTeam && (
<NavRow
id="team-files"
label={t("sidebar.nav.teamFiles")}
iconsOnly={iconsOnly || toolbar}
- active={state.activeView === "team-files"}
+ active={activeView === "team-files"}
icon={(active) => <FolderTree size={iconSize} className={tone(active)} />}
onClick={() => dispatch({ type: "showTeamFiles" })}
/>
@@ -199,7 +201,7 @@ export function SidebarFooterNav({
id={`web-panel-${panel.id}`}
label={panel.name}
iconsOnly={iconsOnly || toolbar}
- active={state.activeView === "web-panel" && state.webPanelId === panel.id}
+ active={activeView === "web-panel" && webPanelId === panel.id}
icon={(active) => (panel.page ? <AppWindow size={iconSize} className={tone(active)} /> : <Globe size={iconSize} className={tone(active)} />)}
onClick={() => dispatch({ type: "showWebPanel", id: panel.id })}
/>
diff --git a/src/components/SidebarGroupThreadList.tsx b/src/components/SidebarGroupThreadList.tsx
index e44a2edf24..c0bcb89619 100644
--- a/src/components/SidebarGroupThreadList.tsx
+++ b/src/components/SidebarGroupThreadList.tsx
@@ -1,5 +1,6 @@
import { useMemo, useRef, useState, type Dispatch } from "react";
-import { useStore, type Action, type Group } from "@/state/store";
+import type { Action, Group } from "@/state/store";
+import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select";
import { activeLocale, t } from "@/lib/i18n";
import { roomThreadAttention, roomThreadWorking } from "@/lib/room-threads";
import { setRoomThreadClosed, threadRowCloser } from "@/lib/room-thread-close";
@@ -18,11 +19,12 @@ export function roomThreadRowActions(groupId: string, dispatch: Dispatch<Action>
}
export function GroupThreadList({ group, selected, query = "" }: { group: Group; selected: boolean; query?: string }) {
- const { state, dispatch } = useStore();
+ const { bots, revealThread } = useStoreSelector((state) => ({ bots: state.bots, revealThread: state.revealThread }), sameFields);
+ const dispatch = useStoreDispatch();
const now = useRelativeNow();
const [showAll, setShowAll] = useState(false);
const tasks = (group.tasks ?? [{ threadId: group.threadId, title: group.name, createdAt: group.createdAt }]).map((task) => {
- const { waiting, unread } = roomThreadAttention(group, task, state.bots);
+ const { waiting, unread } = roomThreadAttention(group, task, bots);
return { ...task, busy: roomThreadWorking(group, task.threadId), unread, activity: waiting ? "waiting-on-you" as const : undefined, closedBy: undefined, closer: threadRowCloser(task) };
});
const bulk = useBulkSelect();
@@ -30,7 +32,7 @@ export function GroupThreadList({ group, selected, query = "" }: { group: Group;
const visible = orderedThreadList(visibleSidebarThreads(tasks, group.threadId, query, [], showAll || bulk.active))
.map(({ closer, ...task }) => ({ ...task, closedBy: closer }));
const selection = bulk.forRows(visible);
- useRevealedThreadRow(state.revealThread, selected ? group.threadId : null);
+ useRevealedThreadRow(revealThread, selected ? group.threadId : null);
const latest = useRef(group);
latest.current = group;
const groupId = group.id;
diff --git a/src/components/SidebarPeople.tsx b/src/components/SidebarPeople.tsx
index e5f419e3b8..a15ff9c8da 100644
--- a/src/components/SidebarPeople.tsx
+++ b/src/components/SidebarPeople.tsx
@@ -10,7 +10,9 @@ import { cn } from "@/lib/cn";
import { leadComposerDraft } from "@/lib/drafts";
import { t } from "@/lib/i18n";
import { useShowThreads } from "@/lib/thread-preferences";
-import { openBot, openThread, useStore, type AppState, type Bot } from "@/state/store";
+import { openBot, openThread, type AppState, type Bot } from "@/state/store";
+import { useStoreRef } from "@/state/store-ref";
+import { sameFields, useStoreSelector } from "@/state/store-select";
import { openInbox } from "@/state/inbox";
import { retryTeamPeople, useTeamPeople, useTeamPeopleStatus, type TeamPerson } from "@/state/team-people";
import { PersonFace } from "./TeamOwner";
@@ -63,15 +65,15 @@ function PeopleStatusLine({ compact }: { compact: boolean }) {
/** `onOpened`: a row was chosen (the phone's full-screen list closes then). */
export function SidebarPeople({ compact, onOpened }: { compact: boolean; onOpened?: () => void }) {
const team = useTeamPeople();
- const { state, dispatch } = useStore();
+ const store = useStoreRef();
const showThreads = useShowThreads();
- if (!team) return state.config?.team ? <PeopleStatusLine compact={compact} /> : null;
- const invite = team.admin ? teamPeoplePage(state.config?.team) : null;
+ const meEmail = team?.me?.email;
+ const { teamConfig, inbox } = useStoreSelector((state) => ({ teamConfig: state.config?.team, inbox: inboxBotOf(state.bots, meEmail) }), sameFields);
+ if (!team) return teamConfig ? <PeopleStatusLine compact={compact} /> : null;
+ const invite = team.admin ? teamPeoplePage(teamConfig) : null;
if (team.people.length < 2 && !invite) return null;
- const me = team.me;
const presence = team.presence === true;
const people = peopleInOrder(team.people);
- const inbox = inboxBotOf(state.bots, me?.email);
const inboxThread = inbox?.tasks?.find((task) => task.inbox)?.threadId;
const waiting = inbox ? openAsksOf(inbox) : 0;
const open = (person: TeamPerson) => {
@@ -80,17 +82,18 @@ export function SidebarPeople({ compact, onOpened }: { compact: boolean; onOpene
};
const openPerson = (person: TeamPerson) => {
if (person.you) {
- if (inbox) openBot(dispatch, inbox, showThreads);
+ if (inbox) openBot(store.dispatch, inbox, showThreads);
if (inboxThread) openInbox();
return;
}
const tag = `@${person.name} `;
- const draft = openComposer(state);
+ const current = store.state();
+ const draft = openComposer(current);
if (draft) leadComposerDraft(draft, tag);
else if (inbox && inboxThread) {
leadComposerDraft(`bot:${inbox.id}:${inboxThread}`, tag);
- openThread(dispatch, { botId: inbox.id, threadId: inboxThread }, state, showThreads);
- } else if (inbox) openBot(dispatch, inbox, showThreads);
+ openThread(store.dispatch, { botId: inbox.id, threadId: inboxThread }, current, showThreads);
+ } else if (inbox) openBot(store.dispatch, inbox, showThreads);
focusComposer();
};
const face = compact ? 22 : 26;
diff --git a/src/components/SidebarPhoneBar.tsx b/src/components/SidebarPhoneBar.tsx
index 4eac6f0ac4..1c8d1ead02 100644
--- a/src/components/SidebarPhoneBar.tsx
+++ b/src/components/SidebarPhoneBar.tsx
@@ -3,7 +3,7 @@ import { FolderOpen, Hamburger, LayoutGrid, Puzzle, Rocket, Search, UsersRound,
import { useCloudFilesReady } from "@/lib/cloud-files";
import { t } from "@/lib/i18n";
import { useFeature } from "@/lib/use-feature";
-import { useStore } from "@/state/store";
+import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select";
import { CloudRoomCard } from "./CloudRoomCard";
import { CloudUsageCard } from "./CloudUsageMeter";
@@ -13,7 +13,8 @@ import { UpdateIndicator } from "./UpdateIndicator";
/** The phone's bottom bar: a round button for the tools that are rows in the desktop sidebar, and a search pill. */
export function SidebarPhoneBar({ query, onQuery }: { query: string; onQuery: (query: string) => void }) {
- const { state, dispatch } = useStore();
+ const { activeView, pluginsOpen } = useStoreSelector((state) => ({ activeView: state.activeView, pluginsOpen: state.pluginsOpen }), sameFields);
+ const dispatch = useStoreDispatch();
const automationsNeedYou = useAutomationsNeedYou();
const filesReady = useCloudFilesReady();
const skillBurger = useFeature("skillBurger");
@@ -22,7 +23,7 @@ export function SidebarPhoneBar({ query, onQuery }: { query: string; onQuery: (q
key: "automations",
label: t("sidebar.nav.automations"),
icon: <Zap size={18} />,
- active: state.activeView === "routines",
+ active: activeView === "routines",
attention: automationsNeedYou,
onSelect: () => dispatch({ type: "showRoutines", view: "list" }),
},
@@ -30,35 +31,35 @@ export function SidebarPhoneBar({ query, onQuery }: { query: string; onQuery: (q
key: "team-map",
label: t("sidebar.nav.teamMap"),
icon: <UsersRound size={18} />,
- active: state.activeView === "team-map",
+ active: activeView === "team-map",
onSelect: () => dispatch({ type: "showTeamMap" }),
},
...(filesReady ? [{
key: "files",
label: t("sidebar.nav.files"),
icon: <FolderOpen size={18} />,
- active: state.activeView === "files",
+ active: activeView === "files",
onSelect: () => dispatch({ type: "showFiles" }),
}] : []),
{
key: "published-apps",
label: t("sidebar.nav.publishedApps"),
icon: <Rocket size={18} />,
- active: state.activeView === "published-apps",
+ active: activeView === "published-apps",
onSelect: () => dispatch({ type: "showPublishedApps" }),
},
{
key: "apps",
label: t("sidebar.nav.apps"),
icon: <Puzzle size={18} />,
- active: state.pluginsOpen,
+ active: pluginsOpen,
onSelect: () => dispatch({ type: "togglePlugins", open: true }),
},
...(skillBurger ? [{
key: "skill-burgers",
label: t("skillBurger.list.title"),
icon: <Hamburger size={18} />,
- active: state.activeView === "skill-burgers",
+ active: activeView === "skill-burgers",
onSelect: () => dispatch({ type: "showSkillBurgers" }),
}] : []),
];
diff --git a/src/components/SidebarProfileMenu.tsx b/src/components/SidebarProfileMenu.tsx
index 5ed565fd8d..d26ae83211 100644
--- a/src/components/SidebarProfileMenu.tsx
+++ b/src/components/SidebarProfileMenu.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useRef, useState } from "react";
+import { lazy, Suspense, useEffect, useRef, useState } from "react";
import {
ArrowUpRight,
Archive,
@@ -35,8 +35,8 @@ import { usePhonePlaceState, type PhonePlaceState } from "./settings/phone-statu
import { useSettingsPlace } from "./settings/settings-place";
import { AccountMoveStatus, useAccountMove, type AccountMoveKind } from "./AccountMove";
import { InitialsAvatar } from "./Avatar";
-import { SignOutConfirm } from "./settings/SignOutConfirm";
-import { AboutDialog } from "./AboutDialog";
+const SignOutConfirm = lazy(() => import("./settings/SignOutConfirm").then((m) => ({ default: m.SignOutConfirm })));
+const AboutDialog = lazy(() => import("./AboutDialog").then((m) => ({ default: m.AboutDialog })));
import { CloudTile } from "./cloud-buy/parts";
import { usageBridge } from "./CloudUsageMeter";
import { useCloudPlanSnapshot } from "./CloudTrialNotice";
@@ -46,7 +46,8 @@ import { useAdvancedMode } from "@/lib/interface-mode";
import { useAutomationsNeedYou } from "./SidebarFooterNav";
import { useCloudFilesReady } from "@/lib/cloud-files";
import { SidebarPopoverMenu, type SidebarMenuItem } from "./SidebarPopoverMenu";
-import { api, useStore, type Action, type AppSettingsSection } from "@/state/store";
+import { api, type Action, type AppSettingsSection } from "@/state/store";
+import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select";
import { serverCheckPhase, serverUpdateRow, type ServerUpdateCheck, type ServerUpdatePhase } from "@/lib/server-update";
import type { CloudAccountBridge, CloudAccountState } from "../../electron/cloud-account.mjs";
import { updaterMessage, useUpdaterState, type UpdaterState } from "@/lib/updater";
@@ -539,12 +540,13 @@ export function useSimpleAccount(place: WorkspacePlace, owner: string | null, ar
export function SidebarProfileMenu({ iconOnly = false, rail = false, circle = false, simple: account }: {
iconOnly?: boolean; rail?: boolean; circle?: boolean; simple?: SimpleAccount;
} = {}) {
- const { state, dispatch } = useStore();
+ const { cloudHome, configProfile, hasTeam, activeView } = useStoreSelector((state) => ({ cloudHome: state.config?.cloudHome === true, configProfile: state.config?.profile, hasTeam: Boolean(state.config?.team), activeView: state.activeView }), sameFields);
+ const dispatch = useStoreDispatch();
const simple = account !== undefined;
const [menuOpen, setMenuOpen] = useState(false);
const advancedMode = useAdvancedMode(), skillBurger = useFeature("skillBurger");
const automationsNeedYou = useAutomationsNeedYou();
- const planSnapshot = useCloudPlanSnapshot(usageBridge(state.config?.cloudHome === true) ?? (window.ogb?.remoteClient?.active ? undefined : window.ogb?.cloudPlan));
+ const planSnapshot = useCloudPlanSnapshot(usageBridge(cloudHome) ?? (window.ogb?.remoteClient?.active ? undefined : window.ogb?.cloudPlan));
const cloudUsage = cloudUsageSummary(planSnapshot);
const phoneState = usePhonePlaceState(menuOpen);
const place = useSettingsPlace();
@@ -554,7 +556,7 @@ export function SidebarProfileMenu({ iconOnly = false, rail = false, circle = fa
const here = pageIsThisComputer();
const openComputer = window.ogb?.rail?.openComputer;
// A Cloud's page in the desktop window can't update the app: the row says where that happens, and goes there.
- const elsewhereUpdate: UpdateEntry | null = !desktopUpdate && !here && Boolean(window.ogb) && state.config?.cloudHome === true && openComputer ? {
+ const elsewhereUpdate: UpdateEntry | null = !desktopUpdate && !here && Boolean(window.ogb) && cloudHome && openComputer ? {
phase: "idle", pending: false, label: t("settings.updates.checkFrom", { place: t("rail.thisComputer") }),
item: { key: "update", label: t("settings.updates.checkFrom", { place: t("rail.thisComputer") }), wrap: true, icon: <RefreshCw size={16} />, trailing: <ArrowUpRight size={12} aria-hidden="true" className="text-ink-tertiary" />, onSelect: () => void openComputer("app").catch(() => {}) },
} : null;
@@ -572,16 +574,16 @@ export function SidebarProfileMenu({ iconOnly = false, rail = false, circle = fa
return () => { active = false; };
}, []);
- const profile = profileForSession(state.config?.profile, session);
+ const profile = profileForSession(configProfile, session);
const name = profileLabel(profile);
const remote = window.ogb?.remoteClient?.active === true;
const besideRail = railShown(usePlaces());
const filesReady = useCloudFilesReady();
const desktop = Boolean(window.ogb);
- const planHere = !remote && (desktop ? Boolean(window.ogb?.cloudAccount || (window.ogb?.cloudPlan && state.config?.cloudHome === true))
- : state.config?.cloudHome === true && !state.config?.team && isOwnerOrAdmin(session));
+ const planHere = !remote && (desktop ? Boolean(window.ogb?.cloudAccount || (window.ogb?.cloudPlan && cloudHome))
+ : cloudHome && !hasTeam && isOwnerOrAdmin(session));
const openSettings = (section: AppSettingsSection) => dispatch({ type: "toggleAppSettings", open: true, section });
- const move = useAccountMove(state.config?.cloudHome === true, { onOpen: () => openSettings("plan"), onPairPhone: () => dispatch(phonePairingSettingsAction()) });
+ const move = useAccountMove(cloudHome, { onOpen: () => openSettings("plan"), onPairPhone: () => dispatch(phonePairingSettingsAction()) });
const accounts = useAccounts();
const news = useAnnouncements();
const openSource = desktop && !window.ogb?.cloudAccount && !window.ogb?.cloudPlan;
@@ -606,14 +608,14 @@ export function SidebarProfileMenu({ iconOnly = false, rail = false, circle = fa
// Simple's own places to go, at every width: the phone's round avatar has them too.
...(account || (circle && !advancedMode) ? { simple: {
tools: toolMenuItems({
- activeView: state.activeView,
+ activeView: activeView,
automationsNeedYou: account?.automationsNeedYou ?? automationsNeedYou,
onAutomations: () => dispatch({ type: "showRoutines", view: "list" }),
onTeamMap: () => dispatch({ type: "showTeamMap" }),
onFiles: filesReady ? () => dispatch({ type: "showFiles" }) : undefined,
onPublishedApps: () => dispatch({ type: "showPublishedApps" }),
onSkillBurgers: skillBurger ? () => dispatch({ type: "showSkillBurgers" }) : undefined,
- onTeamFiles: state.config?.team ? () => dispatch({ type: "showTeamFiles" }) : undefined,
+ onTeamFiles: hasTeam ? () => dispatch({ type: "showTeamFiles" }) : undefined,
archived: account?.archived,
}),
} } : {}),
@@ -626,7 +628,7 @@ export function SidebarProfileMenu({ iconOnly = false, rail = false, circle = fa
onHelp: () => void openExternalLink(HELP_CENTER_URL),
onFeedback: () => void openExternalLink(FEEDBACK_URL),
onWhatsNew: () => void openExternalLink(RELEASES_URL),
- announcements: { unread: news.unread, active: state.activeView === "announcements", onSelect: () => dispatch({ type: "showAnnouncements" }) },
+ announcements: { unread: news.unread, active: activeView === "announcements", onSelect: () => dispatch({ type: "showAnnouncements" }) },
// Every Sign out asks first: "Sign out of MausBot?" and what keeps running.
signOut: accounts.view?.active ? null
: !desktop && session?.kind === "session" ? () => setSigningOut("browser")
@@ -708,12 +710,12 @@ export function SidebarProfileMenu({ iconOnly = false, rail = false, circle = fa
</span>
)}
/>
- <AboutDialog open={aboutOpen} onClose={() => setAboutOpen(false)} />
- {signingOut && <SignOutConfirm browser={signingOut === "browser"} here={signingOut === "browser" ? place.name : t("rail.thisComputer")}
+ {aboutOpen && <Suspense fallback={null}><AboutDialog open onClose={() => setAboutOpen(false)} /></Suspense>}
+ {signingOut && <Suspense fallback={null}><SignOutConfirm browser={signingOut === "browser"} here={signingOut === "browser" ? place.name : t("rail.thisComputer")}
cloud={signingOut === "desktop" && summary.plan ? t("cloudSetup.myCloud") : null} onClose={() => setSigningOut(null)}
onConfirm={() => signingOut === "browser"
? api("/api/auth/logout", { method: "POST" }).finally(() => location.reload())
- : window.ogb?.cloudAccount?.signOut()} />}
+ : window.ogb?.cloudAccount?.signOut()} /></Suspense>}
{accounts.sheet && <AccountsSheet adding={accounts.sheet.email} note={accounts.sheet.note} onClose={accounts.closeSheet} />}
</>
);
diff --git a/src/components/SidebarTeamMenu.tsx b/src/components/SidebarTeamMenu.tsx
index 696e2fc2d8..3e73a77e7c 100644
--- a/src/components/SidebarTeamMenu.tsx
+++ b/src/components/SidebarTeamMenu.tsx
@@ -5,7 +5,8 @@ import { useOwnerOrAdmin } from "@/lib/use-owner-or-admin";
import { cn } from "@/lib/cn";
import { departmentUnread, markDepartmentRead } from "@/lib/folder-read";
import { t } from "@/lib/i18n";
-import { api, useStore } from "@/state/store";
+import { api } from "@/state/store";
+import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select";
import { MENU_ITEM, MENU_ITEM_SEPARATOR } from "./menu-recipe";
function Label({ children }: { children: string }) {
@@ -14,9 +15,10 @@ function Label({ children }: { children: string }) {
/** Reads every conversation of the department's bots and its group chats; shown only while something there is unread. */
function MarkDepartmentRead({ name, className, onDone }: { name: string; className: string; onDone: () => void }) {
- const { state, dispatch } = useStore();
+ const { bots, groups } = useStoreSelector((state) => ({ bots: state.bots, groups: state.groups }), sameFields);
+ const dispatch = useStoreDispatch();
const [reading, setReading] = useState(false);
- const unread = departmentUnread(name, state.bots, state.groups);
+ const unread = departmentUnread(name, bots, groups);
if (!reading && unread.bots.length === 0 && unread.groups.length === 0) return null;
const read = async () => {
setReading(true);
@@ -36,10 +38,11 @@ function MarkDepartmentRead({ name, className, onDone }: { name: string; classNa
/** Pause or resume every bot in the department: only the owner or an admin. */
function PauseDepartment({ name, className, onDone }: { name: string; className: string; onDone: () => void }) {
- const { state, dispatch } = useStore();
+ const config = useStoreSelector((state) => state.config);
+ const dispatch = useStoreDispatch();
const [saving, setSaving] = useState(false);
if (useOwnerOrAdmin() !== true) return null;
- const paused = isPausedHere(state.config, "department", name);
+ const paused = isPausedHere(config, "department", name);
const toggle = async () => {
setSaving(true);
try {
diff --git a/src/components/SidebarTiles.tsx b/src/components/SidebarTiles.tsx
index fd98a450d8..b77b82dc7c 100644
--- a/src/components/SidebarTiles.tsx
+++ b/src/components/SidebarTiles.tsx
@@ -6,7 +6,8 @@ import { t } from "@/lib/i18n";
import { useLiveMedia } from "@/lib/live-call-media";
import { stateForBot } from "@/lib/mascot";
import { useShowThreads } from "@/lib/thread-preferences";
-import { api, openBotRow, useStore, type Bot } from "@/state/store";
+import { api, openBotRow, type Bot } from "@/state/store";
+import { useStoreSelector } from "@/state/store-select";
import { useChiefStepOpen } from "@/lib/default-bot";
import { BotAvatar } from "./Avatar"; import { useMotionBeat } from "./mascot-beat";
@@ -129,9 +130,9 @@ export const SidebarBotTile = memo(function SidebarBotTile({ primary = false, dr
/** The sidebar while the first run's Chief step is open over an app with no bots of the person's own yet. */
export function SidebarNoBots() {
- const { state } = useStore();
+ const hasOwnBots = useStoreSelector((state) => state.bots.some((bot) => !bot.hidden && !bot.defaultBot));
const chiefStep = useChiefStepOpen();
- if (!chiefStep || state.bots.some((bot) => !bot.hidden && !bot.defaultBot)) return null;
+ if (!chiefStep || hasOwnBots) return null;
return <p data-sidebar-empty="" className="px-5 pt-4 text-[13px] leading-[18px] text-ink-tertiary">{t("onboarding.shell.noBots")}</p>;
}
diff --git a/src/components/ThreadChip.tsx b/src/components/ThreadChip.tsx
index f350cc1d4c..95c1509101 100644
--- a/src/components/ThreadChip.tsx
+++ b/src/components/ThreadChip.tsx
@@ -1,6 +1,8 @@
import { use } from "react";
import { ChevronRight, MessagesSquare } from "lucide-react";
-import { openThread, useStore, type Message } from "@/state/store";
+import { openThread, type Message } from "@/state/store";
+import { useStoreRef } from "@/state/store-ref";
+import { sameFields, useStoreSelector } from "@/state/store-select";
import { useShowThreads } from "@/lib/thread-preferences";
import { t } from "@/lib/i18n";
import { activityText } from "@/lib/activity-text";
@@ -11,13 +13,17 @@ import { HandoffReply } from "./HandoffReply";
import { HandoffStatusChip } from "./HandoffStatusChip";
export function ThreadChip({ message, threadId }: { message: Message; threadId?: string }) {
- const { state, dispatch } = useStore();
+ const store = useStoreRef();
const showThreads = useShowThreads();
const openExchange = use(OpenExchangeContext);
const ref = message.threadRef;
const tool = message.tool;
+ const askedById = message.askedBy?.botId;
+ const { bot, pictured } = useStoreSelector((state) => {
+ const target = ref ? state.bots.find((candidate) => candidate.id === ref.botId) : undefined;
+ return { bot: target, pictured: askedById ? state.bots.find((candidate) => candidate.id === askedById) : target };
+ }, sameFields);
if (!ref || !tool) return null;
- const bot = state.bots.find((candidate) => candidate.id === ref.botId);
const direct = message.sentDirectly;
const label = !direct ? activityText(tool, tool.name)
: direct.room ? t("chat.sentDirectlyNotInRoom", { name: direct.name, room: direct.room }) : t("chat.sentDirectly", { name: direct.name });
@@ -30,8 +36,6 @@ export function ThreadChip({ message, threadId }: { message: Message; threadId?:
? { asker, helper: { botId: bot.id, name: bot.name, color: bot.color }, threadId: ref.threadId, ...(handoff ? { id: handoff.id, sentAt: message.at, ...(ended ? { endedAt: handoff.at } : {}) } : {}) }
: null;
const exchangeLabel = bot ? t("chat.handoffExchange.open", { name: bot.name }) : "";
- // The line that records a hand-off in the helper's own chat shows the bot that asked.
- const pictured = message.askedBy ? state.bots.find((candidate) => candidate.id === message.askedBy!.botId) : bot;
return (
<HandoffReply message={message} threadId={threadId}>
<span className="flex min-w-0 max-w-full flex-wrap items-center gap-x-2 gap-y-1">
@@ -52,7 +56,7 @@ export function ThreadChip({ message, threadId }: { message: Message; threadId?:
<button
type="button"
data-thread-chip={ref.threadId}
- onClick={() => openThread(dispatch, ref, state, showThreads)}
+ onClick={() => openThread(store.dispatch, ref, store.state(), showThreads)}
title={t("chat.openThread", { title: ref.title })}
className={cn("ui-pill", tool.ok === false && "text-danger")}
>
diff --git a/src/components/ThreadRefs.tsx b/src/components/ThreadRefs.tsx
index 5b10ad33dd..fb8d490e02 100644
--- a/src/components/ThreadRefs.tsx
+++ b/src/components/ThreadRefs.tsx
@@ -2,8 +2,9 @@ import { MentionText } from "./MentionText";
import { parseAppLink } from "../../electron/app-link.mjs";
import { openLocalApp } from "@/lib/local-apps";
import type { MentionPeer } from "@/lib/mentions";
-import { createContext, Fragment, useContext, useMemo, useRef, type ReactNode } from "react";
-import { botOpensTo, openBot, openThread, useStore, type Action, type AppState, type Bot, type Group, type ThreadTarget } from "@/state/store";
+import { createContext, Fragment, useContext, useMemo, type ReactNode } from "react";
+import { botOpensTo, openBot, openThread, type Action, type AppState, type Bot, type Group, type ThreadTarget } from "@/state/store";
+import { useStoreSelector } from "@/state/store-select";
import { useShowThreads } from "@/lib/thread-preferences";
import { useStoreRef } from "@/state/store-ref";
import { t } from "@/lib/i18n";
@@ -43,13 +44,13 @@ const signatureOf = (refs: ThreadRefCandidate[]) =>
refs.map((ref) => `${ref.botId}\u0000${ref.threadId}\u0000${ref.title}\u0000${ref.activeAt ?? ""}\u0000${ref.botName}`).join("\u0001");
export function ThreadRefsProvider({ children }: { children: ReactNode }) {
- const { state } = useStore();
- const next = collectThreadRefs(state.bots, state.groups);
- const signature = signatureOf(next);
- const cache = useRef({ signature, threads: next });
- if (cache.current.signature !== signature) cache.current = { signature, threads: next };
- const threads = cache.current.threads;
- const currentBotId = state.selectedId;
+ const { threads, currentBotId } = useStoreSelector(
+ (state) => {
+ const next = collectThreadRefs(state.bots, state.groups);
+ return { signature: signatureOf(next), threads: next, currentBotId: state.selectedId };
+ },
+ (a, b) => a.signature === b.signature && a.currentBotId === b.currentBotId,
+ );
const value = useMemo(() => ({ threads, currentBotId }), [threads, currentBotId]);
return <ThreadRefsContext.Provider value={value}>{children}</ThreadRefsContext.Provider>;
}
diff --git a/src/components/WindowPlaceTitle.tsx b/src/components/WindowPlaceTitle.tsx
index 5a7ee9ea07..f08729b2fa 100644
--- a/src/components/WindowPlaceTitle.tsx
+++ b/src/components/WindowPlaceTitle.tsx
@@ -1,7 +1,7 @@
import { useEffect, useState } from "react";
import { usePlaceLook } from "@/lib/place-look";
import { type WorkspaceState, windowPlaceName } from "@/lib/places";
-import { useStore } from "@/state/store";
+import { useStoreSelector } from "@/state/store-select";
import { PlaceMark } from "./PlacesRail";
export { windowPlaceName };
@@ -26,9 +26,9 @@ export function useWindowPlace(): WorkspaceState | null {
export function WindowPlaceTitle() {
const place = useWindowPlace();
const look = usePlaceLook();
- const { state } = useStore();
+ const teamName = useStoreSelector((state) => state.config?.team?.name);
if (!place) return <span aria-hidden="true" />;
- const name = windowPlaceName(place, state.config?.team?.name);
+ const name = windowPlaceName(place, teamName);
return <div data-window-place className="flex min-w-0 items-center justify-center gap-1.5 px-2 text-[12px] font-medium text-ink-secondary">
<PlaceMark place={{ kind: place.local ? "computer" : place.role ? "team" : "cloud", name, color: look?.color ?? place.color ?? null }} size={16} />
<span className="min-w-0 truncate">{name}</span>