feat(tui): refresh the side pane parent snapshot while open

This commit is contained in:
coso committed 2026-11-14 14:44:17 +08:00
1 parent 0a81d7f2e4
commit 75d7dfd2a8
18 files changed
+241 -11

No files matched your search

+11 -3
View File
@@ -32,6 +32,7 @@ describe("browserExtensionsHost", () => {
version: "1.0.0",
manifestVersion: 3,
path: "/tmp/ext",
enabled: true,
},
]);
});
@@ -44,6 +45,7 @@ describe("browserExtensionsHost", () => {
version: "1.0.0",
manifestVersion: 3,
path: "/tmp/ext",
enabled: true,
});
expect(fake.loadExtension).toHaveBeenCalledWith("/tmp/ext", {
allowFileAccess: true,
@@ -72,11 +74,16 @@ describe("BrowserExtensionStore", () => {
await store.add({ id: "a", path: "/tmp/a" });
await store.add({ id: "b", path: "/tmp/b" });
expect(await store.read()).toEqual([
{ id: "a", path: "/tmp/a" },
{ id: "b", path: "/tmp/b" },
{ id: "a", path: "/tmp/a", enabled: true },
{ id: "b", path: "/tmp/b", enabled: true },
]);
await expect(store.setEnabled("a", false)).resolves.toBe(true);
expect((await store.read())[0]).toMatchObject({ id: "a", enabled: false });
await expect(store.setEnabled("missing", false)).resolves.toBe(false);
await store.remove("a");
expect(await store.read()).toEqual([{ id: "b", path: "/tmp/b" }]);
expect(await store.read()).toEqual([
{ id: "b", path: "/tmp/b", enabled: true },
]);
});
it("启动时恢复记录并跳过损坏扩展", async () => {
@@ -112,6 +119,7 @@ describe("BrowserExtensionStore", () => {
version: "1.0.0",
path: "/tmp/a",
manifestVersion: 3,
enabled: true,
},
]);
});
+20 -1
View File
@@ -7,6 +7,7 @@ export interface BrowserExtensionRecord {
version: string;
manifestVersion: number | null;
path: string;
enabled: boolean;
}
interface RawBrowserExtension {
@@ -33,6 +34,7 @@ function toRecord(extension: RawBrowserExtension): BrowserExtensionRecord {
version: extension.version,
manifestVersion: extension.manifest?.manifest_version ?? null,
path: extension.path,
enabled: true,
};
}
@@ -67,6 +69,9 @@ export function removeBrowserExtension(
export interface PersistedBrowserExtension {
id: string;
path: string;
name?: string;
version?: string;
enabled?: boolean;
}
export class BrowserExtensionStore {
@@ -98,10 +103,23 @@ export class BrowserExtensionStore {
const next = records.filter(
(entry) => entry.id !== record.id && entry.path !== record.path,
);
next.push(record);
next.push({ ...record, enabled: record.enabled !== false });
await this.#write(next);
}
async setEnabled(id: string, enabled: boolean): Promise<boolean> {
const records = await this.read();
const record = records.find((entry) => entry.id === id);
if (!record) return false;
record.enabled = enabled;
await this.#write(records);
return true;
}
async find(id: string): Promise<PersistedBrowserExtension | null> {
return (await this.read()).find((entry) => entry.id === id) ?? null;
}
async remove(id: string): Promise<void> {
const records = await this.read();
await this.#write(records.filter((entry) => entry.id !== id));
@@ -119,6 +137,7 @@ export async function restoreBrowserExtensions(
): Promise<BrowserExtensionRecord[]> {
const restored: BrowserExtensionRecord[] = [];
for (const record of await store.read()) {
if (record.enabled === false) continue;
try {
restored.push(
toRecord(
+41
View File
@@ -177,9 +177,50 @@ export class ElectronHostCommands {
await this.#browserExtensionsStore.add({
id: extension.id,
path: extension.path,
name: extension.name,
version: extension.version,
enabled: true,
});
return extension;
}
case "browser_extensions_set_enabled": {
const record = toRecord(args) ?? {};
const id = readRequiredString(record, "id");
const enabled = record.enabled;
if (typeof enabled !== "boolean") {
throw new Error("Invalid extension enabled flag");
}
const session = openEmbeddedBrowserSession();
if (enabled) {
const stored = await this.#browserExtensionsStore.find(id);
if (!stored) throw new Error("扩展不存在");
const extension = await loadBrowserExtension(session, stored.path);
await this.#browserExtensionsStore.add({
id: extension.id,
path: extension.path,
name: extension.name,
version: extension.version,
enabled: true,
});
return extension;
}
try {
removeBrowserExtension(session, id);
} catch {
// 已禁用的扩展可能未被加载。
}
await this.#browserExtensionsStore.setEnabled(id, false);
const stored = await this.#browserExtensionsStore.find(id);
if (!stored) throw new Error("扩展不存在");
return {
id: stored.id,
name: stored.name ?? stored.path,
version: stored.version ?? "",
manifestVersion: null,
path: stored.path,
enabled: false,
};
}
case "browser_extensions_remove": {
const id = readRequiredString(toRecord(args) ?? {}, "id");
const removed = removeBrowserExtension(
+1
View File
@@ -60,6 +60,7 @@ export const ELECTRON_HOST_COMMANDS = [
"browser_extensions_list",
"browser_extensions_load",
"browser_extensions_remove",
"browser_extensions_set_enabled",
"browser_passwords_list",
"browser_passwords_save",
"browser_passwords_remove",
@@ -90,6 +90,11 @@ func accessibilityWindowMatching(ownerPID: pid_t, frame: CGRect) throws -> AXUIE
"AXManualAccessibility" as CFString,
kCFBooleanTrue
)
AXUIElementSetAttributeValue(
application,
"AXEnhancedUserInterface" as CFString,
kCFBooleanTrue
)
var value: CFTypeRef?
guard AXUIElementCopyAttributeValue(application, kAXWindowsAttribute as CFString, &value) == .success,
let value,
@@ -90211,7 +90211,7 @@
"wrapping/tests.rs",
"wrapping/url.rs"
],
"symbolCount": 6861,
"symbolCount": 6864,
"symbols": [
{
"path": "app.rs",
@@ -90393,6 +90393,11 @@
"name": "TranscriptSelectionTarget",
"kind": "type"
},
{
"path": "app.rs",
"name": "update_side_parent_snapshot",
"kind": "function"
},
{
"path": "app/agent_center/hints.rs",
"name": "accept_hint",
@@ -95158,6 +95163,11 @@
"name": "side_and_btw_start_and_exit_a_side_conversation",
"kind": "function"
},
{
"path": "app/tests.rs",
"name": "side_parent_snapshot_can_be_refreshed_while_the_side_is_open",
"kind": "function"
},
{
"path": "app/tests.rs",
"name": "side_thread_title_uses_the_parent_name_when_known",
@@ -96933,6 +96943,11 @@
"name": "thread_read_metadata",
"kind": "function"
},
{
"path": "app_server_session/thread.rs",
"name": "thread_read_with_turns",
"kind": "function"
},
{
"path": "app_server_session/thread.rs",
"name": "thread_unsubscribe",
@@ -124519,7 +124534,7 @@
"kind": "function"
}
],
"treeSha256": "759f610c8f0ebf308ff61839e0c6a73a84b9a4e659a18247738d138ecf3500b5"
"treeSha256": "3e1ff0762afcfb6e1cb33f2b91d9835f55d8b3d176f5a32c78d7683eb0aff198"
},
"codex-rs/tui/tests": {
"root": "/Users/coso/Documents/dev/rust/codex/codex-rs/tui/tests",
@@ -143419,6 +143434,7 @@
"side_parent_needs_input",
"side_parent_pane_title",
"side_parent_snapshot",
"side_parent_snapshot_can_be_refreshed_while_the_side_is_open",
"side_parent_working",
"side_returned",
"side_split_renders_parent_snapshot_and_side_transcript",
@@ -143721,6 +143737,7 @@
"thread_notifications_route_to_their_thread",
"thread_pages_append_unique_threads_and_keep_the_next_cursor",
"thread_read_metadata",
"thread_read_with_turns",
"thread_state",
"thread_to_transcript_entries",
"thread_turns_for_items",
@@ -143959,6 +143976,7 @@
"update_rows",
"update_settings",
"update_settings_with_policy",
"update_side_parent_snapshot",
"update_snapshot_layout",
"update_thread_cwd",
"updated_label",
+9
View File
@@ -466,6 +466,15 @@ impl App {
.unwrap_or_else(|| thread_id.to_string())
}
pub(crate) fn update_side_parent_snapshot(
&mut self,
title: String,
entries: Vec<crate::projection::TranscriptEntry>,
) {
self.side_state
.set_parent_snapshot(side::SideParentSnapshot { title, entries });
}
pub(crate) fn side_parent_snapshot(&self) -> Option<&side::SideParentSnapshot> {
let thread_id = self.thread_id.as_deref()?;
self.side_state
+20
View File
@@ -847,6 +847,26 @@ fn voice_slash_command_starts_dictation_when_idle() {
assert!(!app.voice.is_recording());
}
#[test]
fn side_parent_snapshot_can_be_refreshed_while_the_side_is_open() {
let mut app = App::default();
app.set_locale(Locale::EnUs);
app.projection.add_info_message("parent update");
let entries = app.projection.entries().to_vec();
app.side_state
.open("side-thread".to_string(), "parent-thread".to_string());
app.set_thread_id("side-thread".into());
app.update_side_parent_snapshot("Roadmap".to_string(), entries);
let snapshot = app
.side_parent_snapshot()
.expect("snapshot without side thread");
assert_eq!(snapshot.title, "Roadmap");
assert!(snapshot
.entries
.iter()
.any(|entry| entry.text.contains("parent update")));
}
#[test]
fn side_thread_title_uses_the_parent_name_when_known() {
let mut app = App::default();
@@ -110,6 +110,24 @@ impl AppServerSession {
Ok(response.data)
}
pub(crate) async fn thread_read_with_turns(
&self,
thread_id: String,
) -> Result<app_server_protocol::protocol::v2::Thread> {
let response: app_server_protocol::protocol::v2::ThreadReadResponse = self
.request_handle
.request(
app_server_protocol::protocol::v2::METHOD_THREAD_READ,
app_server_protocol::protocol::v2::ThreadReadParams {
thread_id,
include_turns: true,
},
)
.await
.context("failed to read the parent thread for the side pane")?;
Ok(response.thread)
}
pub(crate) async fn thread_read_metadata(
&self,
thread_id: String,
+27
View File
@@ -83,6 +83,8 @@ pub async fn run_tui(options: TuiOptions) -> Result<()> {
status_tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
let mut recap_tick = tokio::time::interval(Duration::from_secs(60));
recap_tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
let mut side_refresh_tick = tokio::time::interval(Duration::from_secs(5));
side_refresh_tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
let run_result: Result<()> = async {
let mut resume_picker_load_tx: Option<tokio::sync::mpsc::UnboundedSender<PickerLoadEvent>> =
None;
@@ -356,6 +358,31 @@ pub async fn run_tui(options: TuiOptions) -> Result<()> {
_ = status_tick.tick(), if app.projection.active_turn_id().is_some() => {
frame_requester.schedule_frame();
}
_ = side_refresh_tick.tick(), if app.side_parent_snapshot().is_some() => {
let parent_thread_id = app
.thread_id
.as_deref()
.and_then(|thread_id| app.side_state.parent_of(thread_id))
.map(str::to_string);
let Some(parent_thread_id) = parent_thread_id else { continue };
let Some(session_ref) = session.as_ref() else { continue };
if let Ok(thread) = session_ref
.thread_read_with_turns(parent_thread_id)
.await
{
let title = thread
.name
.clone()
.unwrap_or_else(|| thread.id.clone());
let mut projection =
crate::projection::ConversationProjection::default();
projection.hydrate_thread(thread);
app.update_side_parent_snapshot(
title,
projection.entries().to_vec(),
);
}
}
_ = recap_tick.tick(), if app.chat_widget.tui_config.auto_recap => {
let due = app.projection.active_turn_id().is_none()
&& !app.recap.is_pending()
@@ -7,6 +7,7 @@ import {
listBrowserExtensions,
loadBrowserExtension,
removeBrowserExtension,
setBrowserExtensionEnabled,
type BrowserExtensionSummary,
} from "@/lib/api/browserExtensions";
import { BROWSER_SETTINGS_BUTTON } from "./BrowserSettingsFields";
@@ -85,6 +86,19 @@ export function BrowserExtensionsDialog({
}
};
const toggleEnabled = async (extension: BrowserExtensionSummary) => {
setPending(true);
setError(null);
try {
await setBrowserExtensionEnabled(extension.id, !extension.enabled);
await refresh();
} catch {
if (alive.current) setError("import");
} finally {
if (alive.current) setPending(false);
}
};
const remove = async (id: string) => {
setPending(true);
setError(null);
@@ -152,6 +166,16 @@ export function BrowserExtensionsDialog({
{extension.path}
</div>
</div>
<button
type="button"
className={BROWSER_SETTINGS_BUTTON}
disabled={pending}
onClick={() => void toggleEnabled(extension)}
>
{extension.enabled
? t("settings.browser.extensionsDisable")
: t("settings.browser.extensionsEnable")}
</button>
<button
type="button"
className={BROWSER_SETTINGS_BUTTON}
+3 -1
View File
@@ -2627,5 +2627,7 @@
"settings.browser.passwordManagerEdit": "Edit",
"settings.connections.editTitle": "Edit SSH connection",
"settings.connections.edit": "Edit",
"settings.connections.updateFailed": "Could not update the SSH connection"
"settings.connections.updateFailed": "Could not update the SSH connection",
"settings.browser.extensionsEnable": "Enable",
"settings.browser.extensionsDisable": "Disable"
}
+3 -1
View File
@@ -2627,5 +2627,7 @@
"settings.browser.passwordManagerEdit": "編集",
"settings.connections.editTitle": "SSH 接続を編集",
"settings.connections.edit": "編集",
"settings.connections.updateFailed": "SSH 接続を更新できませんでした"
"settings.connections.updateFailed": "SSH 接続を更新できませんでした",
"settings.browser.extensionsEnable": "有効化",
"settings.browser.extensionsDisable": "無効化"
}
+3 -1
View File
@@ -2627,5 +2627,7 @@
"settings.browser.passwordManagerEdit": "편집",
"settings.connections.editTitle": "SSH 연결 편집",
"settings.connections.edit": "편집",
"settings.connections.updateFailed": "SSH 연결을 업데이트하지 못했습니다"
"settings.connections.updateFailed": "SSH 연결을 업데이트하지 못했습니다",
"settings.browser.extensionsEnable": "사용",
"settings.browser.extensionsDisable": "사용 안 함"
}
+3 -1
View File
@@ -2627,5 +2627,7 @@
"settings.browser.passwordManagerEdit": "编辑",
"settings.connections.editTitle": "编辑 SSH 连接",
"settings.connections.edit": "编辑",
"settings.connections.updateFailed": "无法更新 SSH 连接"
"settings.connections.updateFailed": "无法更新 SSH 连接",
"settings.browser.extensionsEnable": "启用",
"settings.browser.extensionsDisable": "禁用"
}
+3 -1
View File
@@ -2627,5 +2627,7 @@
"settings.browser.passwordManagerEdit": "編輯",
"settings.connections.editTitle": "編輯 SSH 連線",
"settings.connections.edit": "編輯",
"settings.connections.updateFailed": "無法更新 SSH 連線"
"settings.connections.updateFailed": "無法更新 SSH 連線",
"settings.browser.extensionsEnable": "啟用",
"settings.browser.extensionsDisable": "停用"
}
+14
View File
@@ -3,6 +3,7 @@ import {
listBrowserExtensions,
loadBrowserExtension,
removeBrowserExtension,
setBrowserExtensionEnabled,
} from "./browserExtensions";
const invoke = vi.hoisted(() => vi.fn());
@@ -14,6 +15,7 @@ const extension = {
version: "1.0.0",
manifestVersion: 3,
path: "/tmp/ext",
enabled: true,
};
describe("browserExtensions", () => {
@@ -53,4 +55,16 @@ describe("browserExtensions", () => {
"remove failed",
);
});
it("启用/禁用扩展并校验返回结构", async () => {
const disabled = { ...extension, enabled: false };
invoke.mockResolvedValue(disabled);
await expect(setBrowserExtensionEnabled("abc123", false)).resolves.toEqual(
disabled,
);
expect(invoke).toHaveBeenCalledWith("browser_extensions_set_enabled", {
id: "abc123",
enabled: false,
});
});
});
+16
View File
@@ -6,6 +6,7 @@ export interface BrowserExtensionSummary {
version: string;
manifestVersion: number | null;
path: string;
enabled: boolean;
}
function isExtensionSummary(value: unknown): value is BrowserExtensionSummary {
@@ -17,6 +18,7 @@ function isExtensionSummary(value: unknown): value is BrowserExtensionSummary {
typeof record.name === "string" &&
typeof record.version === "string" &&
typeof record.path === "string" &&
typeof record.enabled === "boolean" &&
(record.manifestVersion === null ||
typeof record.manifestVersion === "number")
);
@@ -52,3 +54,17 @@ export async function removeBrowserExtension(id: string): Promise<void> {
throw new Error("browser extension remove failed");
}
}
export async function setBrowserExtensionEnabled(
id: string,
enabled: boolean,
): Promise<BrowserExtensionSummary> {
const result = await safeInvoke<unknown>("browser_extensions_set_enabled", {
id,
enabled,
});
if (!isExtensionSummary(result)) {
throw new Error("browser extension update returned an invalid result");
}
return result;
}