From 962a098940493c90939d6169fa99f0ae267711f0 Mon Sep 17 00:00:00 2001 From: James Chapman Date: Thu, 26 Nov 2026 16:16:42 +0000 Subject: [PATCH 01/12] feat: grant the workspace folder read-write without a folder dialog A read-write container grant from the settings window now uses the workspace's recorded folder, since core accepts no other, and its confirmation says the access goes to the workspace's sandbox. Grant, revoke, and discovery confirmations, the form, and the run refusal name who gets the access (ADR-0104). Version 0.69.0. Work in progress: guides, changelog, and checks still to do. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 10 +- Cargo.toml | 2 +- .../src/desktop/settings_changes.rs | 5 +- .../src/desktop/settings_discovery.rs | 2 +- .../src/desktop/settings_execution.rs | 149 ++++++++++++------ .../tests/desktop_settings_execution.rs | 86 +++++++++- crates/omgcode-core/src/run.rs | 2 +- crates/omgcode-desktop/ui/src/mock/backend.ts | 6 +- .../ui/src/settings/discovery_panel.ts | 2 +- .../ui/src/settings/execution_forms.ts | 33 +++- .../ui/tests/settings_execution.test.ts | 48 +++++- ...ecution-settings-in-the-settings-window.md | 2 +- ...lder-read-write-without-a-folder-dialog.md | 97 ++++++++++++ docs/adr/index.md | 3 +- 14 files changed, 372 insertions(+), 75 deletions(-) create mode 100644 docs/adr/0104-grant-the-workspace-folder-read-write-without-a-folder-dialog.md diff --git a/Cargo.lock b/Cargo.lock index 98fdf332..6994c025 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3622,7 +3622,7 @@ dependencies = [ [[package]] name = "omgcode-app" -version = "0.68.0" +version = "0.69.0" dependencies = [ "directories", "omgcode-core", @@ -3638,7 +3638,7 @@ dependencies = [ [[package]] name = "omgcode-cli" -version = "0.68.0" +version = "0.69.0" dependencies = [ "clap", "omgcode-app", @@ -3651,7 +3651,7 @@ dependencies = [ [[package]] name = "omgcode-core" -version = "0.68.0" +version = "0.69.0" dependencies = [ "base64 0.23.1", "bytes", @@ -3675,7 +3675,7 @@ dependencies = [ [[package]] name = "omgcode-desktop" -version = "0.68.0" +version = "0.69.0" dependencies = [ "omgcode-app", "rfd", @@ -3688,7 +3688,7 @@ dependencies = [ [[package]] name = "omgcode-platform" -version = "0.68.0" +version = "0.69.0" dependencies = [ "libc", "rustix", diff --git a/Cargo.toml b/Cargo.toml index bdc8506d..da888702 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ resolver = "3" members = ["crates/omgcode-core", "crates/omgcode-cli", "crates/omgcode-platform", "crates/omgcode-app", "crates/omgcode-desktop"] [workspace.package] -version = "0.68.0" +version = "0.69.0" edition = "2024" rust-version = "1.99.1" license = "Apache-2.0" diff --git a/crates/omgcode-app/src/desktop/settings_changes.rs b/crates/omgcode-app/src/desktop/settings_changes.rs index 97634ffc..90c04864 100644 --- a/crates/omgcode-app/src/desktop/settings_changes.rs +++ b/crates/omgcode-app/src/desktop/settings_changes.rs @@ -82,7 +82,8 @@ pub enum FolderPurpose { ToolchainRoot, /// A `PATH` entry of a toolchain profile, inside one of its roots. ToolchainPathEntry, - /// A folder to grant to a workspace's container. + /// A folder to grant read and execute to a workspace's container. A + /// read-write grant opens no dialog (ADR-0104). ContainerGrant, } @@ -97,7 +98,7 @@ impl FolderPurpose { Self::Skill => "Choose a skill folder", Self::ToolchainRoot => "Choose a read-only root for the toolchain profile", Self::ToolchainPathEntry => "Choose a PATH entry inside a root of the profile", - Self::ContainerGrant => "Choose a folder to grant to the workspace's container", + Self::ContainerGrant => "Choose a folder the workspace's commands may read and execute", } } } diff --git a/crates/omgcode-app/src/desktop/settings_discovery.rs b/crates/omgcode-app/src/desktop/settings_discovery.rs index dca8ba6e..7fa4c571 100644 --- a/crates/omgcode-app/src/desktop/settings_discovery.rs +++ b/crates/omgcode-app/src/desktop/settings_discovery.rs @@ -458,7 +458,7 @@ fn grants_confirmation( Confirmation { title: "Grant toolchain folders to a workspace", message: format!( - "Give the workspace\n{workspace}\nread and execute access to these folders?\n{}\n\nThis changes each folder's access-control list on disk for that workspace's AppContainer, and each grant stays until you revoke it. Runs in the workspace can then read and execute everything beneath them.{skipped}", + "Let the commands OMGCode runs for the workspace\n{workspace}\nread and execute these folders and everything beneath them?\n{}\n\nThis adds the workspace's AppContainer, the Windows sandbox its commands run in, to each folder's access-control list on disk, and each grant stays until you revoke it.{skipped}", list(folders) ), } diff --git a/crates/omgcode-app/src/desktop/settings_execution.rs b/crates/omgcode-app/src/desktop/settings_execution.rs index da73b259..db486908 100644 --- a/crates/omgcode-app/src/desktop/settings_execution.rs +++ b/crates/omgcode-app/src/desktop/settings_execution.rs @@ -7,9 +7,11 @@ //! same expected-revision check and validation, and records the same events. //! The window adds no second rule and names no path: //! -//! - Every folder (a toolchain root, a `PATH` entry, a granted folder) comes -//! only from [`SettingsPrompt::pick_folder`], one dialog per folder. The -//! request carries how many of each, never a path. +//! - Every folder (a toolchain root, a `PATH` entry, a folder granted read +//! and execute) comes only from [`SettingsPrompt::pick_folder`], one dialog +//! per folder. The request carries how many of each, never a path. A +//! read-write grant opens no dialog: core accepts it only on the +//! workspace's own directory, so its folder is the recorded one (ADR-0104). //! - Adding a toolchain profile widens what a run can see, adding a package //! profile records origins, and a grant changes a folder's access-control //! list on disk. Each is applied only after a native confirmation that this @@ -260,22 +262,34 @@ fn toolchain_add_confirmation( } } -/// The native confirmation for a container grant. -fn grant_confirmation( - workspace_folder: &str, - access: ContainerGrantAccess, - folder: &str, -) -> Confirmation { +/// The native confirmation for the read-write grant on the workspace's own +/// folder. It says who gets the access (the workspace's sandbox) because the +/// workspace and the folder are the same path (ADR-0104). +fn workspace_folder_grant_confirmation(workspace_folder: &str) -> Confirmation { Confirmation { - title: "Grant a folder to a workspace", + title: "Let a workspace's commands use its folder", message: format!( - "Give the workspace + "Let the commands OMGCode runs for the workspace {workspace_folder} -{} access to the folder -{folder}? +read and write that folder and everything beneath it? -This changes the folder's access-control list on disk for that workspace's AppContainer, and it stays until you revoke it. Runs in the workspace can then use the folder, including everything beneath it.", - access_text(access), +OMGCode runs each of the workspace's commands in the workspace's own AppContainer, a Windows sandbox that starts with no access to your files; registering the folder gave it none. This adds the sandbox to the folder's access-control list on disk, and it stays until you revoke it. Every run in the workspace needs it." + ), + } +} + +/// The native confirmation for a read-and-execute grant on a chosen folder. +fn read_execute_grant_confirmation(workspace_folder: &str, folder: &str) -> Confirmation { + Confirmation { + title: "Let a workspace's commands read a folder", + message: format!( + "Let the commands OMGCode runs for the workspace +{workspace_folder} +read and execute the folder +{folder} +and everything beneath it? + +This adds the workspace's AppContainer, the Windows sandbox its commands run in, to the folder's access-control list on disk, and it stays until you revoke it." ), } } @@ -289,12 +303,12 @@ fn revoke_confirmation( Confirmation { title: "Revoke a container grant", message: format!( - "Revoke the {} grant on -{directory} -for the workspace -{workspace}? + "Revoke the {} access of the commands OMGCode runs for the workspace +{workspace} +to the folder +{directory}? -This removes the entry from the folder's access-control list on disk. Runs of that workspace that started before are stopped.", +This removes the workspace's AppContainer, the Windows sandbox those commands run in, from the folder's access-control list on disk. Runs of that workspace that started before are stopped.", access_text(access), ), } @@ -577,19 +591,26 @@ impl DesktopService { }) } - /// `settings` only. Windows only. Ask the operator for a folder and, - /// after a native confirmation that names the workspace, the folder and - /// the access and says the folder's access-control list changes on disk, - /// grant it to the workspace's container as `omgcode workspace - /// container-grant` does. + /// `settings` only. Windows only. Grant a folder to the workspace's + /// container as `omgcode workspace container-grant` does, after a native + /// confirmation that names the workspace, the folder and the access and + /// says the folder's access-control list changes on disk. + /// + /// For read and execute, the operator chooses the folder in a native + /// dialog. For read and write, no dialog opens: core accepts that access + /// only on the workspace's own directory, so the folder is the recorded + /// one, and core still checks that the directory at that path is the + /// recorded directory before it records anything (ADR-0104). /// /// # Errors /// /// `unsupported_platform` outside Windows; `unknown_workspace`; - /// `cancelled`; `stale_revision`; `settings_change_running`; `busy`; - /// `control` with core's reason (a scope or overlap refusal, an existing - /// grant); `container_access_failed` when the grant was recorded but the - /// list could not be changed (it stays `pending`; revoke it). + /// `invalid_request` when the recorded workspace path cannot be used on + /// this system; `cancelled`; `stale_revision`; `settings_change_running`; + /// `busy`; `control` with core's reason (a scope or overlap refusal, an + /// existing grant, a workspace folder that was moved or replaced); + /// `container_access_failed` when the grant was recorded but the list + /// could not be changed (it stays `pending`; revoke it). pub fn settings_grant_container_folder( &self, request: ContainerGrantRequest, @@ -599,25 +620,38 @@ impl DesktopService { return Err(DesktopError::unsupported_platform()); } let _guard = ChangeGuard::take(&self.inner.settings_change)?; - let (workspace_id, workspace_folder) = { + let (workspace_id, workspace_path) = { let store = self.inner.open_or_create_control()?; check_revision(&store, request.revision)?; let workspace = store .registered_workspace(request.workspace_id) .ok_or_else(DesktopError::unknown_workspace)?; - ( - workspace.id(), - folder_of_directory(workspace.directory_path()), - ) + (workspace.id(), workspace.directory_path()) + }; + let workspace_folder = folder_of_directory(workspace_path.clone()); + let (folder, confirmation) = match request.access { + ContainerAccessChoice::ReadWrite => { + let folder = workspace_path.ok_or_else(|| { + DesktopError::execution_request( + "The workspace path is not usable on this system.", + ) + })?; + ( + folder, + workspace_folder_grant_confirmation(&workspace_folder), + ) + } + ContainerAccessChoice::ReadExecute => { + let folder = prompt + .pick_folder(FolderPurpose::ContainerGrant, None) + .ok_or_else(DesktopError::cancelled)?; + let confirmation = + read_execute_grant_confirmation(&workspace_folder, &shown(&folder)); + (folder, confirmation) + } }; - let folder = prompt - .pick_folder(FolderPurpose::ContainerGrant, None) - .ok_or_else(DesktopError::cancelled)?; let access = ContainerGrantAccess::from(request.access); - confirm( - prompt, - &grant_confirmation(&workspace_folder, access, &shown(&folder)), - )?; + confirm(prompt, &confirmation)?; let mut store = self.inner.open_or_create_control()?; let outcome = store.grant_container_access(workspace_id, &folder, access, request.revision); match outcome { @@ -701,13 +735,14 @@ mod tests { #[test] fn the_grant_and_revoke_confirmations_name_everything_they_change() { - let grant = grant_confirmation("/dev/a", ContainerGrantAccess::ReadWrite, "/dev/b"); + let grant = read_execute_grant_confirmation("/dev/a", "/tools"); for expected in [ "/dev/a", - "/dev/b", - "read and write", + "/tools", + "read and execute", "access-control list", "AppContainer", + "sandbox", ] { assert!( grant.message.contains(expected), @@ -721,6 +756,7 @@ mod tests { "/dev/a", "read and execute", "access-control list", + "AppContainer", "stopped", ] { assert!( @@ -731,6 +767,31 @@ mod tests { } } + #[test] + fn the_workspace_folder_confirmation_says_the_sandbox_gets_the_access() { + let grant = workspace_folder_grant_confirmation("O:\\ShippingQuotes"); + let message = &grant.message; + // The folder is named once, as the workspace's: the operator is not + // asked to give a folder access to itself. + assert_eq!( + message.matches("O:\\ShippingQuotes").count(), + 1, + "{message}" + ); + for expected in [ + "commands OMGCode runs for the workspace", + "read and write that folder", + "AppContainer", + "Windows sandbox", + "registering the folder gave it none", + "access-control list", + "until you revoke it", + "Every run in the workspace needs it", + ] { + assert!(message.contains(expected), "{expected}: {message}"); + } + } + #[test] fn a_choice_names_the_core_access() { assert_eq!( diff --git a/crates/omgcode-app/tests/desktop_settings_execution.rs b/crates/omgcode-app/tests/desktop_settings_execution.rs index 9e61c2a9..4687bfdf 100644 --- a/crates/omgcode-app/tests/desktop_settings_execution.rs +++ b/crates/omgcode-app/tests/desktop_settings_execution.rs @@ -974,17 +974,87 @@ mod windows { } #[test] - fn the_write_access_is_named_in_the_confirmation() { + fn a_read_write_grant_opens_no_folder_dialog_and_names_the_workspace_folder_once() { let fixture = Fixture::new(); let workspace = with_workspace(&fixture); let now = current_revision(&fixture.data); - let prompt = ScriptedPrompt::new() - .folder(Some(&fixture.development.join("project"))) - .answer(false); - let _ = service(&fixture.data) - .settings_grant_container_folder(grant_request(now, workspace, "read_write"), &prompt); - let message = prompt.confirmations().remove(0).message; - assert!(message.contains("read and write"), "{message}"); + // No folder is scripted: a folder dialog would fail the test. + let prompt = ScriptedPrompt::new().answer(false); + + let error = + error_of(service(&fixture.data).settings_grant_container_folder( + grant_request(now, workspace, "read_write"), + &prompt, + )); + + assert_eq!(error.code(), "cancelled"); + let asked = prompt.asked(); + assert_eq!(asked.len(), 1, "{asked:?}"); + let Asked::Confirm(confirmation) = &asked[0] else { + panic!("only the confirmation is shown"); + }; + let message = &confirmation.message; + // The folder is shown once, as the workspace's; the temporary root's + // name cannot end a line with the workspace's own name. + let folder_lines = message + .lines() + .filter(|line| line.ends_with("project")) + .count(); + assert_eq!(folder_lines, 1, "{message}"); + for expected in [ + "read and write that folder", + "AppContainer", + "sandbox", + "access-control list", + ] { + assert!(message.contains(expected), "{expected} in {message}"); + } + assert_eq!(current_revision(&fixture.data), now); + let store = ControlStore::open_existing(&fixture.data) + .expect("open") + .expect("exists"); + assert!(store.container_grants().is_empty()); + } + + #[test] + fn a_confirmed_read_write_grant_reaches_core_with_the_confirmed_revision() { + let fixture = Fixture::new(); + let workspace = with_workspace(&fixture); + let now = current_revision(&fixture.data); + let other = tool_root(&fixture, "other"); + let data = fixture.data.clone(); + let prompt = ScriptedPrompt::new().answer(true).meanwhile(move || { + let mut store = ControlStore::open_existing(&data) + .expect("open") + .expect("exists"); + let revision = store.revision(); + store + .add_profile( + &omgcode_core::control::ProfileDeclaration { + name: "intervening".into(), + read_only_roots: vec![other], + path_entries: Vec::new(), + environment: Vec::new(), + }, + revision, + ) + .expect("an intervening change"); + }); + + let error = + error_of(service(&fixture.data).settings_grant_container_folder( + grant_request(now, workspace, "read_write"), + &prompt, + )); + + // The grant went to core without a dialog, and core refused the + // revision before it recorded or changed anything: no ACL changes here. + assert_eq!(error.code(), "stale_revision"); + assert_eq!(prompt.confirmations().len(), 1); + let store = ControlStore::open_existing(&fixture.data) + .expect("open") + .expect("exists"); + assert!(store.container_grants().is_empty()); } #[test] diff --git a/crates/omgcode-core/src/run.rs b/crates/omgcode-core/src/run.rs index b5863079..4917ce6e 100644 --- a/crates/omgcode-core/src/run.rs +++ b/crates/omgcode-core/src/run.rs @@ -677,7 +677,7 @@ fn workspace_access( return Err(if running { "the workspace read-write container grant was revoked" } else { - "grant the workspace directory read-write to its container first" + "the workspace's sandbox has no read-write grant on the workspace folder; grant it first under Settings, Advanced, Container grants, or with `omgcode workspace container-grant`" }); } Ok(()) diff --git a/crates/omgcode-desktop/ui/src/mock/backend.ts b/crates/omgcode-desktop/ui/src/mock/backend.ts index 7e27d763..b7ec58a3 100644 --- a/crates/omgcode-desktop/ui/src/mock/backend.ts +++ b/crates/omgcode-desktop/ui/src/mock/backend.ts @@ -1521,7 +1521,7 @@ export function createMockBackend(now: () => number = Date.now): { invoke: Invok case "settings_grant_container_folder": return changeSettings(args, () => { const workspaceId = str(args, "workspace_id"); - mockWorkspace({ workspace_id: workspaceId }); + const workspace = mockWorkspace({ workspace_id: workspaceId }); const access = str(args, "access"); if (access !== "read_execute" && access !== "read_write") { fail("invalid_argument", "Bad access."); @@ -1529,7 +1529,9 @@ export function createMockBackend(now: () => number = Date.now): { invoke: Invok settings.container_grants.push({ grant_id: `00000000-0000-4000-8000-${String(settings.container_grants.length + 1).padStart(12, "0")}`, workspace_id: workspaceId, - directory: nextMockFolder("grant"), + // As in Rust (ADR-0104): read and write goes on the workspace's own folder, with no + // folder dialog; read and execute goes on a folder the dialog would choose. + directory: access === "read_write" ? workspace.folder_display : nextMockFolder("grant"), access, state: "active", }); diff --git a/crates/omgcode-desktop/ui/src/settings/discovery_panel.ts b/crates/omgcode-desktop/ui/src/settings/discovery_panel.ts index e3e26483..f8907266 100644 --- a/crates/omgcode-desktop/ui/src/settings/discovery_panel.ts +++ b/crates/omgcode-desktop/ui/src/settings/discovery_panel.ts @@ -23,7 +23,7 @@ export const NOTHING_FOUND = "No toolchain was found in the standard install folders, on PATH, or in the folders named by JAVA_HOME, GOROOT, and RUSTUP_HOME."; export const SELECTION_LIMIT = "Select at most 8 proposals at a time."; export const WORKSPACE_GRANT_MISSING = - "This workspace has no active read-write grant on its own folder, which every run in it needs. Grant it under Container grants."; + "This workspace's sandbox has no active read-write grant on the workspace folder, which every run in it needs. Grant it under Container grants with Read and write the workspace's own folder."; export const NO_WORKSPACE = "No workspace"; /** Says how many installations the list leaves out. */ diff --git a/crates/omgcode-desktop/ui/src/settings/execution_forms.ts b/crates/omgcode-desktop/ui/src/settings/execution_forms.ts index 46380f7e..aa508967 100644 --- a/crates/omgcode-desktop/ui/src/settings/execution_forms.ts +++ b/crates/omgcode-desktop/ui/src/settings/execution_forms.ts @@ -7,6 +7,8 @@ import { emptyLine, facts, row } from "./parts"; export const ADD_TOOLCHAIN_LABEL = "Add profile…"; export const ADD_PACKAGE_LABEL = "Add package profile…"; export const GRANT_FOLDER_LABEL = "Grant folder…"; +/** Read and write is granted on the workspace's own folder only, so no folder dialog opens (ADR-0104). */ +export const GRANT_WORKSPACE_FOLDER_LABEL = "Grant the workspace folder…"; export const TOOLCHAIN_HELP = "A toolchain profile lists the directories a run may read and execute, the directories searched for programs, and extra environment variables. Rust opens a system folder dialog for each root and each PATH entry, then asks you to confirm the whole profile. A profile grants nothing by itself, and it cannot be edited: remove it and add it again."; @@ -15,7 +17,11 @@ export const ENVIRONMENT_WARNING = export const PACKAGE_HELP = "A package-network profile records registry origins as configuration only. No run uses it and it grants no network access. Registry credentials are bound with the trusted CLI, not here. Removing a profile also unbinds and deletes the credentials bound to its origins. A profile cannot be edited: remove it and add it again."; export const GRANT_HELP = - "A container grant changes a folder's access-control list on disk for one workspace's AppContainer, and stays until you revoke it. Rust opens the folder dialog and asks you to confirm. A grant that shows pending or revoking did not finish: Revoke tries again."; + "OMGCode runs each workspace's commands in that workspace's own AppContainer, a Windows sandbox that starts with no access to your files. Registering a folder as a workspace does not change that. A container grant adds the sandbox to one folder's access-control list on disk and stays until you revoke it. Every run needs read and write on the workspace's own folder; a toolchain outside it needs read and execute. A grant that shows pending or revoking did not finish: Revoke tries again."; +export const GRANT_READ_WRITE_HINT = + "Lets the commands OMGCode runs for this workspace read and write its own folder, which every run needs. No folder dialog opens, because read and write can only be granted on the workspace's own folder. You confirm in a system dialog."; +export const GRANT_READ_EXECUTE_HINT = + "Lets the commands OMGCode runs for this workspace read and execute a folder you choose, such as a toolchain outside the workspace. A system folder dialog opens, then you confirm."; export const GRANTS_UNSUPPORTED = "Container grants are Windows-only. This computer cannot record or apply them, so there is nothing to change here."; @@ -268,27 +274,40 @@ function grantForm(ctx: SectionContext): HTMLElement { workspace.value = known ? draft.workspaceId : (overview.workspaces[0]?.workspace_id ?? ""); const access = el("select", { attrs: { id: "new-grant-access" } }); access.append( - el("option", { text: "Read and execute", attrs: { value: "read_execute" } }), el("option", { - text: "Read and write (the workspace folder only)", + text: "Read and execute a folder you choose", + attrs: { value: "read_execute" }, + }), + el("option", { + text: "Read and write the workspace's own folder", attrs: { value: "read_write" }, }), ); access.value = draft.access; + const hint = el("p", { class: "muted", attrs: { id: "new-grant-hint" } }); + const grant = button(GRANT_FOLDER_LABEL, () => + submit(actions.grantContainerFolder(workspace.value, access.value as ContainerAccess)), + ); + // The button and the hint follow the access: read and write opens no folder dialog. + const describe = (): void => { + const readWrite = access.value === "read_write"; + grant.textContent = readWrite ? GRANT_WORKSPACE_FOLDER_LABEL : GRANT_FOLDER_LABEL; + hint.textContent = readWrite ? GRANT_READ_WRITE_HINT : GRANT_READ_EXECUTE_HINT; + }; + describe(); workspace.addEventListener("change", () => { draft.workspaceId = workspace.value; }); access.addEventListener("change", () => { draft.access = access.value as ContainerAccess; + describe(); }); - const grant = button(GRANT_FOLDER_LABEL, () => - submit(actions.grantContainerFolder(workspace.value, access.value as ContainerAccess)), - ); return el( "div", { class: "form" }, - labelled("Workspace", "new-grant-workspace", workspace), + labelled("Workspace whose commands get access", "new-grant-workspace", workspace), labelled("Access", "new-grant-access", access), + hint, el("div", { class: "row-actions" }, grant), ); } diff --git a/crates/omgcode-desktop/ui/tests/settings_execution.test.ts b/crates/omgcode-desktop/ui/tests/settings_execution.test.ts index 335236b9..4d489eca 100644 --- a/crates/omgcode-desktop/ui/tests/settings_execution.test.ts +++ b/crates/omgcode-desktop/ui/tests/settings_execution.test.ts @@ -9,6 +9,10 @@ import { ADD_TOOLCHAIN_LABEL, ENVIRONMENT_WARNING, GRANT_FOLDER_LABEL, + GRANT_HELP, + GRANT_READ_EXECUTE_HINT, + GRANT_READ_WRITE_HINT, + GRANT_WORKSPACE_FOLDER_LABEL, GRANTS_UNSUPPORTED, PACKAGE_HELP, parseEnvironment, @@ -322,7 +326,7 @@ describe("container grants", () => { } access.value = "read_write"; access.dispatchEvent(new Event("change")); - buttonByText(root, GRANT_FOLDER_LABEL).click(); + buttonByText(root, GRANT_WORKSPACE_FOLDER_LABEL).click(); await settle(); expect(ipc.callsTo("settings_grant_container_folder")[0]?.args).toEqual({ revision: 5, @@ -332,6 +336,32 @@ describe("container grants", () => { expect(block("Container grants").textContent).toContain("C:\\dev\\a\\vendor"); }); + it("says the sandbox gets the access and that read and write opens no folder dialog", async () => { + await start(() => overview()); + const group = block("Container grants"); + expect(group.textContent).toContain(GRANT_HELP); + expect(group.textContent).toContain("Workspace whose commands get access"); + const hint = group.querySelector("#new-grant-hint"); + const access = group.querySelector("#new-grant-access"); + if (hint === null || access === null) { + throw new Error("no hint or access select"); + } + // Read and execute is the default: a folder dialog follows the button. + expect(hint.textContent).toBe(GRANT_READ_EXECUTE_HINT); + expect(buttonByText(group, GRANT_FOLDER_LABEL)).toBeTruthy(); + + access.value = "read_write"; + access.dispatchEvent(new Event("change")); + expect(hint.textContent).toBe(GRANT_READ_WRITE_HINT); + expect(buttonByText(group, GRANT_WORKSPACE_FOLDER_LABEL)).toBeTruthy(); + expect(group.textContent).not.toContain(GRANT_FOLDER_LABEL); + + access.value = "read_execute"; + access.dispatchEvent(new Event("change")); + expect(hint.textContent).toBe(GRANT_READ_EXECUTE_HINT); + expect(buttonByText(group, GRANT_FOLDER_LABEL)).toBeTruthy(); + }); + it("shows a pending grant with its state and a Revoke button", async () => { await start(() => overview({ container_grants: [{ ...GRANT_VIEW }] }), { settings_revoke_container_grant: () => overview({ revision: 6 }), @@ -448,4 +478,20 @@ describe("mock execution commands", () => { })) as SettingsOverview; expect(revoked.container_grants).toEqual([]); }); + + it("grants read and write on the workspace's own folder, as Rust does", async () => { + const { invoke } = createMockBackend(); + const before = await overviewOf(invoke); + const workspace = before.workspaces[0]; + if (workspace === undefined) { + throw new Error("the mock has a workspace"); + } + const granted = (await invoke("settings_grant_container_folder", { + revision: before.revision, + workspace_id: workspace.workspace_id, + access: "read_write", + })) as SettingsOverview; + expect(granted.container_grants[0]?.directory).toBe(workspace.folder_display); + expect(granted.container_grants[0]?.access).toBe("read_write"); + }); }); diff --git a/docs/adr/0088-change-execution-settings-in-the-settings-window.md b/docs/adr/0088-change-execution-settings-in-the-settings-window.md index 27882b7d..6f3010e0 100644 --- a/docs/adr/0088-change-execution-settings-in-the-settings-window.md +++ b/docs/adr/0088-change-execution-settings-in-the-settings-window.md @@ -1,6 +1,6 @@ # 0088: Change execution settings in the settings window -- Status: Accepted +- Status: Accepted, amended by [ADR-0104](0104-grant-the-workspace-folder-read-write-without-a-folder-dialog.md) - Date: 2026-11-24 ## Context diff --git a/docs/adr/0104-grant-the-workspace-folder-read-write-without-a-folder-dialog.md b/docs/adr/0104-grant-the-workspace-folder-read-write-without-a-folder-dialog.md new file mode 100644 index 00000000..8072f5a5 --- /dev/null +++ b/docs/adr/0104-grant-the-workspace-folder-read-write-without-a-folder-dialog.md @@ -0,0 +1,97 @@ +# 0104: Grant the workspace folder read-write without a folder dialog + +- Status: Accepted +- Date: 2026-11-26 + +## Context + +On Windows every run in a workspace, including the model's command tool, +runs in that workspace's AppContainer. The container starts with no access +to the operator's files, and registering a folder as a workspace does not +give it any. A run is refused until the workspace folder holds an active +read-write container grant (`workspace_access` in +`crates/omgcode-core/src/run.rs`). + +[ADR-0088](0088-change-execution-settings-in-the-settings-window.md) +(decision 2) made **Grant folder…** in the `settings` window open a native +folder dialog for every grant. Core accepts read-write only on the +workspace's own directory (`check_grant_scope`), so for read-write the dialog +could only repeat the workspace folder or pick a folder core then refused. +The confirmation then read "Give the workspace `` read and write +access to the folder ``?". An operator whose model run was refused +with "grant the workspace directory read-write to its container first" +asked which folder to choose, and then read the grant as giving a folder +access to itself. The text did not say who receives the access: the +workspace's sandbox. + +## Decision + +1. **A read-write grant opens no folder dialog.** + `settings_grant_container_folder` with `read_write` uses the workspace's + recorded directory. The request is unchanged: a revision, a registered + workspace, and an access, never a path. A read-execute grant still opens + the dialog. A recorded path that this system cannot form is refused as + `invalid_request` before any confirmation. +2. **Core still decides.** The window adds no rule. Core opens the path, + checks that the directory there is the recorded one by volume and file + identity, and refuses a folder that was moved or replaced, exactly as + before. The revision is checked before the confirmation and again by core + with the confirmed revision, so a change made meanwhile is refused as + `stale_revision` (ADR-0088 decision 4). +3. **The text names who gets the access.** Every grant and revocation + confirmation, the discovery grant confirmation (ADR-0103), the folder + dialog title, and the group's help say that the access goes to the + workspace's AppContainer, the Windows sandbox its commands run in. The + read-write confirmation names the folder once, as the workspace's, and + says that registering the folder gave the sandbox no access and that + every run needs this grant. The form's access options read **Read and + execute a folder you choose** and **Read and write the workspace's own + folder**, the button reads **Grant the workspace folder…** for read-write, + and a hint under the selects says what each choice does. +4. **The run refusal says where to grant.** The fixed text becomes "the + workspace's sandbox has no read-write grant on the workspace folder; grant + it first under Settings, Advanced, Container grants, or with `omgcode + workspace container-grant`". It names no path. The refusal during a run + is unchanged. +5. **ADR-0088 decision 2 is narrowed** for read-write grants only. The CLI is + unchanged: `workspace container-grant` still takes a path, and core + refuses any other folder for read-write. + +## Alternatives considered + +- **Keep the dialog and only reword the text.** The dialog would still ask + for a choice that has one valid answer, and a wrong pick would still fail + only after the dialog, with core's refusal. +- **Start the dialog at the workspace folder.** Less wrong, but it still + offers a choice with one valid answer. +- **Grant read-write automatically when a workspace is registered.** It would + change a folder's access-control list on disk without a separate, + revocable decision. Registration is configuration only, and + ADR-0060 requires a confirmation before each change that widens access. +- **Name the container by its SID or `OMGCode.Workspace.`.** Accurate, + but the identifier explains nothing to the operator. The confirmations name + the AppContainer and call it the workspace's sandbox. The execution guide + keeps the name. + +## Consequences + +- The read-write grant takes one confirmation and no folder dialog. A + read-execute grant is unchanged apart from its text. +- The window and the CLI still record the same events through the same core + call, and core's checks are unchanged. +- A model that relays the run refusal now tells the operator where to grant. +- No test applies a container grant, because that changes the host's + access-control lists. Windows integration tests check that a read-write + grant opens no folder dialog, that its confirmation names the folder once, + and that a confirmed grant reaches core with the confirmed revision (core + refuses a stale one before it records anything). The native dialogs and the + real shell were not driven by automation. + +## References + +- [ADR-0088](0088-change-execution-settings-in-the-settings-window.md), + [ADR-0060](0060-change-workspace-settings-from-the-desktop-with-native-dialogs.md), + [ADR-0103](0103-generate-toolchain-profiles-from-installed-toolchains.md), + [ADR-0029](0029-confine-windows-runs-in-a-workspace-appcontainer-with-recorded-grants.md) +- [docs/execution.md](../execution.md#container-grants) +- [docs/desktop-interface.md](../desktop-interface.md) diff --git a/docs/adr/index.md b/docs/adr/index.md index a795d345..0fbadeff 100644 --- a/docs/adr/index.md +++ b/docs/adr/index.md @@ -102,7 +102,7 @@ meaningful alternative does not need an ADR. | [0085: Read Git status with gix without running programs](0085-read-git-status-with-gix-without-running-programs.md) | Accepted | 2026-11-24 | | [0086: Show the session's subprocesses in the main window](0086-show-the-sessions-subprocesses-in-the-main-window.md) | Accepted | 2026-11-24 | | [0087: Show a per-part context estimate for the open session](0087-show-a-per-part-context-estimate-for-the-open-session.md) | Accepted; amended by ADR-0102 | 2026-11-24 | -| [0088: Change execution settings in the settings window](0088-change-execution-settings-in-the-settings-window.md) | Accepted | 2026-11-24 | +| [0088: Change execution settings in the settings window](0088-change-execution-settings-in-the-settings-window.md) | Accepted, amended by ADR-0104 | 2026-11-24 | | [0089: Choose the provider and model in the side panel footer](0089-choose-the-provider-and-model-in-the-side-panel-footer.md) | Accepted; amended by ADR-0102 | 2026-11-24 | | [0090: Set every file-write tool limit at once](0090-set-every-file-write-tool-limit-at-once.md) | Accepted | 2026-11-24 | | [0091: Compact automatically at 400K by default in the desktop](0091-compact-automatically-at-400k-by-default-in-the-desktop.md) | Accepted | 2026-11-24 | @@ -118,3 +118,4 @@ meaningful alternative does not need an ADR. | [0101: Make every section divider movable](0101-make-every-section-divider-movable.md) | Accepted | 2026-11-26 | | [0102: Choose a reasoning effort per session](0102-choose-a-reasoning-effort-per-session.md) | Accepted | 2026-11-26 | | [0103: Generate toolchain profiles from installed toolchains](0103-generate-toolchain-profiles-from-installed-toolchains.md) | Accepted | 2026-11-26 | +| [0104: Grant the workspace folder read-write without a folder dialog](0104-grant-the-workspace-folder-read-write-without-a-folder-dialog.md) | Accepted | 2026-11-26 | From 23e83436cc95836c2d7974b51e36e73a54c3c4fa Mon Sep 17 00:00:00 2001 From: James Chapman Date: Thu, 26 Nov 2026 16:20:17 +0000 Subject: [PATCH 02/12] docs: describe the read-write grant without a folder dialog Update the desktop interface, execution, and workspace-permissions guides for ADR-0104, and record version 0.69.0 in the changelog. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 20 ++++++++++++++++++++ docs/desktop-interface.md | 24 ++++++++++++++++++------ docs/execution.md | 13 ++++++++++--- docs/workspace-permissions.md | 5 ++++- 4 files changed, 52 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4361467b..96588489 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -546,6 +546,26 @@ Changes are recorded here before a release version is assigned. ### Changed +- Version 0.69.0 makes the read-write container grant say what it does + (ADR-0104). In the desktop `settings` window, **Grant a folder** with read + and write no longer opens a folder dialog: core accepts that access only on + the workspace's own directory, so Rust uses the recorded one, and core + still checks that the directory there is the recorded directory. The + button reads **Grant the workspace folder…**, the access options read + **Read and execute a folder you choose** and **Read and write the + workspace's own folder**, and a hint under the selects says what each + does. A read-execute grant still opens the dialog. The grant, revoke, and + toolchain-discovery confirmations, the folder dialog's title, and the + group's help now say that the access goes to the workspace's AppContainer, + the Windows sandbox its commands run in, and that registering a folder + gives it none; the read-write confirmation names the folder once instead + of as both the workspace and the folder. A run refused for a missing grant + now says the workspace's sandbox has no read-write grant on the workspace + folder, and where to grant it. The command's request is unchanged and + carries no path. An operator had read the old confirmation as giving a + folder access to itself. No test applies a real grant, and the native + dialogs were not driven by automation. + - Version 0.61.0 restyles the desktop windows in the OMG Software outlined-toggle palette (ADR-0095). The theme uses neutral greys around charcoal `#151515`, switch orange `#ff761f` as the accent, and charcoal diff --git a/docs/desktop-interface.md b/docs/desktop-interface.md index bb85c0b6..b911ae9c 100644 --- a/docs/desktop-interface.md +++ b/docs/desktop-interface.md @@ -1434,12 +1434,24 @@ waits. The window shows: no control, the overview's `container_grants_supported` is false, and the two commands return `unsupported_platform`. On Windows each grant lists its folder, workspace, access, and state (`pending`, `active`, `revoking`) with a - **Revoke** button, and **Grant a folder** has a workspace select and an - access select (read and execute, or read and write for the workspace - folder only). **Grant folder…** calls `settings_grant_container_folder`; - Rust opens the folder dialog and shows a confirmation naming the workspace, - the folder, and the access, and saying that the folder's access-control - list changes on disk for that workspace's AppContainer. A failed list + **Revoke** button. The group's help says that each workspace's commands run + in its own AppContainer, a Windows sandbox with no access to the operator's + files until a grant adds it, and that registering a folder gives none. + **Grant a folder** has a **Workspace whose commands get access** select, an + access select (**Read and execute a folder you choose**, or **Read and write + the workspace's own folder**), and a hint that follows the access. Both + buttons call `settings_grant_container_folder` with the workspace and the + access. For read and execute, **Grant folder…** has Rust open the folder + dialog. For read and write, **Grant the workspace folder…** opens no + dialog: core accepts that access only on the workspace's own directory, so + Rust uses the recorded one, and core still checks that the directory at + that path is the recorded directory + ([ADR-0104](adr/0104-grant-the-workspace-folder-read-write-without-a-folder-dialog.md)). + A recorded path this system cannot form is refused as `invalid_request`. + Either way Rust shows a confirmation that names the workspace, the folder + (once, for read and write), and the access, says that the access goes to + the workspace's sandbox, and says that the folder's access-control list + changes on disk until the grant is revoked. A failed list change leaves the grant `pending` (the command fails with `container_access_failed`); **Revoke** tries again, and a revocation that fails stays `revoking`. Revoking checks the revision under the lock, stops diff --git a/docs/execution.md b/docs/execution.md index fff0334c..171e3808 100644 --- a/docs/execution.md +++ b/docs/execution.md @@ -411,9 +411,16 @@ Rules: the root's ancestors; a dedicated top-level directory is recommended. - Grants work only on Windows. Elsewhere `container-grant` fails and records nothing. The desktop `settings` window grants and revokes through the same - core calls after a native folder dialog and confirmation, and returns - `unsupported_platform` elsewhere (ADR-0088). A revocation there stops the - workspace's earlier runs, as `container-revoke` does. + core calls after a native confirmation, and returns `unsupported_platform` + elsewhere (ADR-0088). A read-execute grant there starts with a native + folder dialog. A read-write grant opens none and uses the workspace's + recorded directory, the only one core accepts for that access + ([ADR-0104](adr/0104-grant-the-workspace-folder-read-write-without-a-folder-dialog.md)). + A revocation there stops the workspace's earlier runs, as + `container-revoke` does. +- A run refused for a missing read-write grant says the workspace's sandbox + has no read-write grant on the workspace folder, and names the `settings` + window's **Container grants** group and `workspace container-grant`. ## Trusted runs diff --git a/docs/workspace-permissions.md b/docs/workspace-permissions.md index 49544523..3785aac6 100644 --- a/docs/workspace-permissions.md +++ b/docs/workspace-permissions.md @@ -183,7 +183,10 @@ Version 0.14.0 refuses a settings log that records a grant. The [ADR-0088](adr/0088-change-execution-settings-in-the-settings-window.md) the desktop `settings` window grants a folder and revokes a grant through the same core calls, with native dialogs and confirmations; on other platforms it -returns `unsupported_platform`. It adds no new event. +returns `unsupported_platform`. It adds no new event. Since +[ADR-0104](adr/0104-grant-the-workspace-folder-read-write-without-a-folder-dialog.md) +a read-write grant there opens no folder dialog and uses the workspace's +recorded directory. ## Unregistering a workspace From 7a0474cdec9fa8da938301be906c210b61204882 Mon Sep 17 00:00:00 2001 From: James Chapman Date: Thu, 26 Nov 2026 16:52:22 +0000 Subject: [PATCH 03/12] feat: show the approvals window when a turn starts waiting A desktop chat turn that waits for an approval now shows the approvals window at once. When OMGCode owns the foreground window it comes to the front; otherwise it is shown and its taskbar button flashes, and the foreground is not taken from another application. Core's ApprovalWaitSlot can carry a WaitObserver that the turn calls each time it publishes the call it waits on. The desktop service holds one and drops it on shutdown. The approvals window also lists again when it gains focus, so a new request no longer waits for the 3-second poll. Records ADR-0105. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 4 + CHANGELOG.md | 31 +++++ Cargo.lock | 1 + crates/omgcode-app/src/desktop.rs | 14 +- crates/omgcode-app/src/desktop/chat.rs | 50 ++++++- crates/omgcode-app/tests/desktop_approvals.rs | 56 ++++++++ crates/omgcode-core/src/turn.rs | 2 +- crates/omgcode-core/src/turn/approval_wait.rs | 112 +++++++++++++++- crates/omgcode-desktop/Cargo.toml | 3 + crates/omgcode-desktop/src/commands.rs | 11 +- crates/omgcode-desktop/src/lib.rs | 14 +- crates/omgcode-desktop/src/windows.rs | 68 +++++++++- .../omgcode-desktop/ui/src/approvals/app.ts | 11 ++ .../ui/tests/approvals.test.ts | 31 ++++- crates/omgcode-platform/src/foreground.rs | 59 +++++++++ crates/omgcode-platform/src/lib.rs | 1 + ...ovals-window-when-a-turn-starts-waiting.md | 123 ++++++++++++++++++ docs/adr/index.md | 1 + docs/desktop-interface.md | 21 ++- 19 files changed, 585 insertions(+), 28 deletions(-) create mode 100644 crates/omgcode-platform/src/foreground.rs create mode 100644 docs/adr/0105-show-the-approvals-window-when-a-turn-starts-waiting.md diff --git a/AGENTS.md b/AGENTS.md index 9284240f..dc58dbf6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -144,6 +144,10 @@ in the same turn; on the CLI only a later identical call may consume an approved record. The trusted CLI or the desktop approvals window can decide a record; the window shows a request only when core reproduces its digest, and approval needs a single-use review token. +When a desktop turn starts waiting, Rust shows the approvals window: it comes +to the front only when OMGCode owns the foreground window, and otherwise its +taskbar button flashes without taking focus from another application +([ADR-0105](docs/adr/0105-show-the-approvals-window-when-a-turn-starts-waiting.md)). `workspace_run_command` then invokes the trusted runner, and `workspace_edit_file` then calls the checkpointed apply with the size and digest of a live trusted read diff --git a/CHANGELOG.md b/CHANGELOG.md index 96588489..13dc6b3e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -566,6 +566,37 @@ Changes are recorded here before a release version is assigned. folder access to itself. No test applies a real grant, and the native dialogs were not driven by automation. +- Version 0.69.0 also shows the desktop approvals window as soon as a chat + turn starts waiting for an approval (ADR-0105), instead of only counting + it in the `main` window. Core's `ApprovalWaitSlot` can carry a `WaitObserver` + that the turn calls on its own thread, with no lock held, each time it + publishes the call it waits on; the observer receives nothing and decides + nothing. `DesktopService::set_approval_wait_observer` holds one, each turn + copies it when it starts, and `DesktopService::shutdown` drops it. The + shell registers an observer at startup. When OMGCode owns the foreground + window, read on Windows with `GetForegroundWindow` and + `GetWindowThreadProcessId` in a new `omgcode-platform` function + (`foreground::this_process_owns_foreground`), the approvals window is + unminimized, shown, and focused. Otherwise it is shown and its taskbar + button flashes, and the foreground is not taken, because on Windows that + sends the other application a simulated key press. No command, event, or + capability is added, and the approvals window still never focuses + **Approve**, decides on no key, and arms **Approve** one second after a + review renders. The approvals window also lists again when it gains focus, + so a request that brought it forward appears without waiting up to 3 + seconds for the next poll; a new request still never replaces the one + under review. An approval recorded by a CLI turn still shows only in the + count. The `settings` and `approvals` show commands now share one helper + and behave as before; the operator saw the settings window open in front + every time in their latest testing, and no cause of an earlier, occasional + open behind `main` was found. `omgcode-desktop` now depends on the + workspace crate `omgcode-platform`. Tests cover the observer, a real + desktop turn telling it once while still waiting for a decision, shutdown + dropping it, and the focus refresh keeping the review; which window ends + up in front, the taskbar flash, and whether WebView2 delivers the focus + event were not driven by automation. The approvals tests now dispose a + window before starting another in the same test. + - Version 0.61.0 restyles the desktop windows in the OMG Software outlined-toggle palette (ADR-0095). The theme uses neutral greys around charcoal `#151515`, switch orange `#ff761f` as the accent, and charcoal diff --git a/Cargo.lock b/Cargo.lock index 6994c025..ed027f00 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3678,6 +3678,7 @@ name = "omgcode-desktop" version = "0.69.0" dependencies = [ "omgcode-app", + "omgcode-platform", "rfd", "serde", "serde_json", diff --git a/crates/omgcode-app/src/desktop.rs b/crates/omgcode-app/src/desktop.rs index 036e220d..c58c792c 100644 --- a/crates/omgcode-app/src/desktop.rs +++ b/crates/omgcode-app/src/desktop.rs @@ -35,6 +35,7 @@ //! | `reviews` | outstanding single-use approval review tokens | //! | `events` | the one chat event subscriber and the running turns' previews | //! | `pending_cache` | an atomic copy of the last pending-approval count read | +//! | `approval_wait_observer` | the shell's one approval-wait observer (ADR-0105) | //! | `session_choices` | the read-modify-write of `session-connections.json` (ADR-0071) | //! //! **Lock order** when two are ever needed: `turns`, then `index`, then @@ -42,7 +43,9 @@ //! together with the `turns` lock (where both are needed, `turns` is taken and //! released first) and never while `index` or `reviews` is taken. It is held //! while a subscriber sink runs, so a sink must not block or call the service -//! (see [`ChatEventSink`]). No service lock and no open +//! (see [`ChatEventSink`]). The `approval_wait_observer` lock is held only to +//! clone or replace the observer, with no other lock, and never while the +//! observer runs. No service lock and no open //! control store is held across provider I/O, a chat turn, a journal //! inspection, a thread join, or a sleep. The one deliberate exception is the //! `index` lock during a refresh: a refresh needs `&mut SessionIndex`, so it @@ -320,6 +323,14 @@ struct Inner { /// The last pending-approval count read, served when the settings store is /// busy. Advisory only; it authorizes nothing. pending_cache: AtomicU64, + /// Called on a turn's thread each time the turn starts waiting for an + /// approval decision, so the shell can show its approvals window + /// (ADR-0105). It decides nothing. Each turn copies the observer when it + /// starts. Owners: this field and the slots of turns started while it was + /// set. A shell observer may own a handle that reaches this service, which + /// is a cycle; [`DesktopService::shutdown`] clears the field to end it, + /// and a turn that outlives shutdown keeps its copy until it ends. + approval_wait_observer: Mutex>, /// Set while one settings change waits for the operator or applies, so /// a second change is refused rather than opening a second dialog. settings_change: AtomicBool, @@ -391,6 +402,7 @@ impl DesktopService { reviews: Mutex::new(ReviewTokens::default()), events: Mutex::new(EventHub::default()), pending_cache: AtomicU64::new(0), + approval_wait_observer: Mutex::new(None), settings_change: AtomicBool::new(false), settings_scope: Mutex::new(None), session_choices: Mutex::new(()), diff --git a/crates/omgcode-app/src/desktop/chat.rs b/crates/omgcode-app/src/desktop/chat.rs index 40a06f14..f7f002a6 100644 --- a/crates/omgcode-app/src/desktop/chat.rs +++ b/crates/omgcode-app/src/desktop/chat.rs @@ -1,12 +1,13 @@ //! Chat commands: defaults, model list, send, status, cancel, and shutdown. +use std::sync::PoisonError; use std::time::Duration; use omgcode_core::session_index::IndexedState; use uuid::Uuid; use omgcode_core::skills::{MAX_SELECTED_SKILLS, SkillName}; -use omgcode_core::turn::ApprovalWaitSlot; +use omgcode_core::turn::{ApprovalWaitSlot, WaitObserver}; use super::ChatEventSink; use super::error::DesktopError; @@ -281,7 +282,10 @@ impl DesktopService { let clients = ChatClients::for_connection(&settings, &connection) .map_err(|error| DesktopError::from_app(&error))?; let token = connection.token; - let approval_wait = ApprovalWaitSlot::new(); + let approval_wait = match inner.current_approval_wait_observer()? { + Some(observer) => ApprovalWaitSlot::new().with_observer(observer), + None => ApprovalWaitSlot::new(), + }; let job = TurnJob { session_id, path, @@ -376,6 +380,25 @@ impl DesktopService { Ok(()) } + /// Register the one approval-wait observer, replacing any earlier one + /// (ADR-0105). Turns started afterwards call it on their own thread each + /// time they start waiting for an approval decision; a turn already + /// running keeps the observer it started with. The observer must return + /// promptly, must not panic, and must not call this service. It is told + /// only that a wait began and can approve nothing. + /// + /// # Errors + /// + /// `internal` when the service state is unavailable. + pub fn set_approval_wait_observer(&self, observer: WaitObserver) -> Result<(), DesktopError> { + *self + .inner + .approval_wait_observer + .lock() + .map_err(|_| DesktopError::poisoned())? = Some(observer); + Ok(()) + } + /// Request cancellation of every running turn and wait up to `grace` for /// the turn threads to finish, polling for completion. /// @@ -388,7 +411,16 @@ impl DesktopService { /// close later with the interrupt command. After shutdown, `chat_send` is /// refused. pub fn shutdown(&self, grace: Duration) -> ShutdownReport { - self.inner.shutdown_turns(grace) + let report = self.inner.shutdown_turns(grace); + // No turn starts after shutdown, so the observer is no longer needed. + // Dropping it ends the cycle a shell observer may form with this + // service. A poisoned lock is recovered: the value is a whole `Option`. + self.inner + .approval_wait_observer + .lock() + .unwrap_or_else(PoisonError::into_inner) + .take(); + report } fn read_status(&self, session_id: Uuid) -> Result { @@ -478,3 +510,15 @@ fn status_of(session_id: Uuid, state: Option<&SlotState>) -> ChatStatus { error, } } + +impl Inner { + /// A copy of the registered approval-wait observer, if any (ADR-0105). + /// The lock is held only to clone it. + fn current_approval_wait_observer(&self) -> Result, DesktopError> { + Ok(self + .approval_wait_observer + .lock() + .map_err(|_| DesktopError::poisoned())? + .clone()) + } +} diff --git a/crates/omgcode-app/tests/desktop_approvals.rs b/crates/omgcode-app/tests/desktop_approvals.rs index f099977a..4c2599cc 100644 --- a/crates/omgcode-app/tests/desktop_approvals.rs +++ b/crates/omgcode-app/tests/desktop_approvals.rs @@ -421,6 +421,62 @@ fn a_command_approval_is_decided_while_the_turn_waits() { assert_eq!(setup.server.finish(), 2); } +#[test] +fn a_turn_that_starts_waiting_tells_the_observer_once_and_the_wait_still_needs_a_decision() { + use std::sync::Arc; + use std::sync::atomic::{AtomicUsize, Ordering}; + + let setup = setup(vec![ + Step::reply(tool_call("cmd-1", COMMAND_TOOL, &command_args())), + Step::reply(text("denied")), + ]); + let told = Arc::new(AtomicUsize::new(0)); + let counter = Arc::clone(&told); + setup + .service + .set_approval_wait_observer(Arc::new(move || { + counter.fetch_add(1, Ordering::SeqCst); + })) + .expect("observer"); + let session = setup.session("Observed"); + setup.start(session, "say hello"); + let id = setup.await_pending(session); + + // The record exists before the turn publishes its call and starts + // waiting, so the observer may run just after the record appears. + let deadline = Instant::now() + PENDING_DEADLINE; + while told.load(Ordering::SeqCst) == 0 { + assert!(Instant::now() < deadline, "the observer was not called"); + std::thread::sleep(Duration::from_millis(10)); + } + // Telling the observer decided nothing: the turn still waits. + assert!(setup.detail(id).waiting); + assert_eq!(setup.state_of(id), ApprovalStateDto::Pending); + + setup.deny_and_finish(id, session); + assert_eq!(told.load(Ordering::SeqCst), 1); + assert_eq!(setup.server.finish(), 2); +} + +#[test] +fn shutdown_drops_the_approval_wait_observer() { + use std::sync::Arc; + + let setup = setup(Vec::new()); + let observer: Arc = Arc::new(|| {}); + let watch = Arc::downgrade(&observer); + setup + .service + .set_approval_wait_observer(observer) + .expect("observer"); + assert!(watch.upgrade().is_some(), "the service keeps the observer"); + let report = setup.service.shutdown(Duration::from_millis(100)); + assert_eq!(report.still_running, 0); + // No turn ran, so the service held the only owner. + assert!(watch.upgrade().is_none(), "shutdown drops the observer"); + assert_eq!(setup.server.finish(), 0); +} + /// Two sessions, each with a turn waiting on one pending edit approval for /// its own file. Each turn needs one more model reply once it is decided. fn two_pending() -> (Setup, [(Uuid, Uuid); 2]) { diff --git a/crates/omgcode-core/src/turn.rs b/crates/omgcode-core/src/turn.rs index 43334c7c..c312a173 100644 --- a/crates/omgcode-core/src/turn.rs +++ b/crates/omgcode-core/src/turn.rs @@ -54,7 +54,7 @@ use crate::web_fetch::{ mod approval_wait; mod review; -pub use approval_wait::{ApprovalWaitSlot, AwaitedCall}; +pub use approval_wait::{ApprovalWaitSlot, AwaitedCall, WaitObserver}; pub use review::{ ApprovalReview, DisplaySafeStream, ReviewCandidate, ReviewError, ReviewField, ReviewedRequest, diff --git a/crates/omgcode-core/src/turn/approval_wait.rs b/crates/omgcode-core/src/turn/approval_wait.rs index fcc71e86..63973c82 100644 --- a/crates/omgcode-core/src/turn/approval_wait.rs +++ b/crates/omgcode-core/src/turn/approval_wait.rs @@ -6,7 +6,14 @@ //! call here instead. The call is only a review candidate: the review still //! recomputes the approval digest from it and the live workspace, so a call //! that does not match the record is never shown as exact. +//! +//! A front end may also attach a [`WaitObserver`], which the turn calls each +//! time it starts waiting, so the front end can show its review surface at +//! once instead of when it next polls (ADR-0105). The observer only learns +//! that a wait began; it decides nothing and receives nothing it could +//! approve with. +use std::fmt; use std::sync::{Arc, Mutex, PoisonError}; use uuid::Uuid; @@ -33,8 +40,35 @@ pub struct AwaitedCall { /// data, so no reference cycle can form. The lock is held only to copy or /// replace the value. A poisoned lock is recovered, because the value is a /// whole `Option` with no invariant a panic could leave half-updated. -#[derive(Clone, Debug, Default)] -pub struct ApprovalWaitSlot(Arc>>); +/// +/// An attached [`WaitObserver`] is shared by every clone made after it was +/// attached. It must not own a clone of the slot it is attached to, or the +/// slot would keep itself alive. +#[derive(Clone, Default)] +pub struct ApprovalWaitSlot { + call: Arc>>, + observer: Option, +} + +/// Called on the turn's thread each time the turn starts waiting for a +/// decision, after the call is published and before the wait begins. +/// +/// It runs with no lock of the slot held and must return promptly: the wait, +/// and with it the operator's decision, starts only when it returns. It must +/// not panic, because a panic would end the turn. It receives nothing: the +/// front end reads [`ApprovalWaitSlot::current`] or its own approval list if +/// it needs the call. +pub type WaitObserver = Arc; + +impl fmt::Debug for ApprovalWaitSlot { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("ApprovalWaitSlot") + .field("call", &self.current()) + .field("observer", &self.observer.is_some()) + .finish() + } +} impl ApprovalWaitSlot { /// An empty slot. @@ -43,18 +77,30 @@ impl ApprovalWaitSlot { Self::default() } + /// This slot with `observer` called whenever the turn starts waiting. + #[must_use] + pub fn with_observer(mut self, observer: WaitObserver) -> Self { + self.observer = Some(observer); + self + } + /// The call the turn waits on now, or `None` when it is not waiting. #[must_use] pub fn current(&self) -> Option { - self.0 + self.call .lock() .unwrap_or_else(PoisonError::into_inner) .clone() } - /// Publish `call` until the returned guard is dropped. + /// Publish `call` until the returned guard is dropped, then tell the + /// observer, if any, that a wait began. pub(super) fn publish(&self, call: AwaitedCall) -> PublishedCall<'_> { - *self.0.lock().unwrap_or_else(PoisonError::into_inner) = Some(call); + *self.call.lock().unwrap_or_else(PoisonError::into_inner) = Some(call); + // The lock is released above, so the observer may read the slot. + if let Some(observer) = &self.observer { + observer(); + } PublishedCall { slot: self } } } @@ -66,7 +112,11 @@ pub(super) struct PublishedCall<'a> { impl Drop for PublishedCall<'_> { fn drop(&mut self) { - *self.slot.0.lock().unwrap_or_else(PoisonError::into_inner) = None; + *self + .slot + .call + .lock() + .unwrap_or_else(PoisonError::into_inner) = None; } } @@ -89,4 +139,54 @@ mod tests { drop(guard); assert_eq!(reader.current(), None); } + + fn call() -> AwaitedCall { + AwaitedCall { + approval_id: Uuid::new_v4(), + tool: "workspace_run_command".to_owned(), + arguments: "{}".to_owned(), + } + } + + #[test] + fn the_observer_runs_once_per_wait_after_the_call_is_published() { + use std::sync::atomic::{AtomicUsize, Ordering}; + + // The observer reads through a clone made before it was attached, so + // it owns no clone of the slot that holds it. + let reader = ApprovalWaitSlot::new(); + let seen = Arc::new(Mutex::new(Vec::new())); + let calls = Arc::new(AtomicUsize::new(0)); + let slot = reader.clone().with_observer({ + let reader = reader.clone(); + let seen = Arc::clone(&seen); + let calls = Arc::clone(&calls); + Arc::new(move || { + calls.fetch_add(1, Ordering::SeqCst); + // The slot's lock is free and the call is already visible. + seen.lock().expect("seen").push(reader.current()); + }) + }); + let shared = slot.clone(); + + let first = call(); + let guard = shared.publish(first.clone()); + drop(guard); + let second = call(); + drop(slot.publish(second.clone())); + + assert_eq!(calls.load(Ordering::SeqCst), 2); + assert_eq!(*seen.lock().expect("seen"), vec![Some(first), Some(second)]); + assert_eq!(reader.current(), None); + } + + #[test] + fn a_slot_without_an_observer_still_publishes_and_debug_shows_no_closure() { + let slot = ApprovalWaitSlot::new(); + let guard = slot.publish(call()); + assert!(slot.current().is_some()); + drop(guard); + let text = format!("{slot:?}"); + assert!(text.contains("observer: false"), "{text}"); + } } diff --git a/crates/omgcode-desktop/Cargo.toml b/crates/omgcode-desktop/Cargo.toml index e099e81b..d3fd4b7a 100644 --- a/crates/omgcode-desktop/Cargo.toml +++ b/crates/omgcode-desktop/Cargo.toml @@ -29,6 +29,9 @@ custom-protocol = ["tauri/custom-protocol"] [dependencies] omgcode-app = { path = "../omgcode-app" } +# Whether this process owns the foreground window before the approvals window is +# brought to the front (ADR-0105). A workspace crate: no third-party code is added. +omgcode-platform = { path = "../omgcode-platform" } serde.workspace = true serde_json.workspace = true uuid.workspace = true diff --git a/crates/omgcode-desktop/src/commands.rs b/crates/omgcode-desktop/src/commands.rs index 19d82720..be3ddcf9 100644 --- a/crates/omgcode-desktop/src/commands.rs +++ b/crates/omgcode-desktop/src/commands.rs @@ -172,16 +172,7 @@ fn show_window(webview: &Webview, label: WindowLabel) -> Result<(), CommandError .app_handle() .get_webview_window(label.as_str()) .ok_or_else(CommandError::window_unavailable)?; - window - .unminimize() - .map_err(|_| CommandError::window_unavailable())?; - window - .show() - .map_err(|_| CommandError::window_unavailable())?; - window - .set_focus() - .map_err(|_| CommandError::window_unavailable())?; - Ok(()) + crate::windows::bring_to_front(&window).map_err(|_| CommandError::window_unavailable()) } #[cfg(test)] diff --git a/crates/omgcode-desktop/src/lib.rs b/crates/omgcode-desktop/src/lib.rs index 6c67d74d..3d0547ce 100644 --- a/crates/omgcode-desktop/src/lib.rs +++ b/crates/omgcode-desktop/src/lib.rs @@ -139,11 +139,23 @@ fn check_connection(connection: &LocalConnection) -> Result<(), String> { } fn run_app(service: Arc) -> ExitCode { + let observed = Arc::clone(&service); let built = tauri::Builder::default() .manage(service) .manage(ShutdownGate::default()) - .setup(|app| { + .setup(move |app| { windows::create_windows(app)?; + // A turn that starts waiting for an approval shows the approvals + // window (ADR-0105). The service keeps this observer and the handle + // reaches the service through managed state; that cycle ends when + // `DesktopService::shutdown` drops the observer. + let handle = app.handle().clone(); + if observed + .set_approval_wait_observer(Arc::new(move || windows::present_approvals(&handle))) + .is_err() + { + eprintln!("omgcode-desktop: the approvals window will not open on its own"); + } Ok(()) }) .invoke_handler(tauri::generate_handler![ diff --git a/crates/omgcode-desktop/src/windows.rs b/crates/omgcode-desktop/src/windows.rs index 5051c650..990bf1a2 100644 --- a/crates/omgcode-desktop/src/windows.rs +++ b/crates/omgcode-desktop/src/windows.rs @@ -1,4 +1,5 @@ -//! Window creation, the navigation guard, and close behaviour. +//! Window creation, the navigation guard, close behaviour, and bringing a +//! window to the front. //! //! Every window is created in Rust so that the navigation and new-window //! hooks are attached before the first page loads. No window may leave @@ -7,7 +8,10 @@ use tauri::webview::NewWindowResponse; use tauri::window::Color; -use tauri::{App, Url, WebviewUrl, WebviewWindow, WebviewWindowBuilder, WindowEvent}; +use tauri::{ + App, AppHandle, Manager, Url, UserAttentionType, WebviewUrl, WebviewWindow, + WebviewWindowBuilder, WindowEvent, +}; use crate::policy::WindowLabel; use crate::shutdown; @@ -132,6 +136,66 @@ pub fn create_windows(app: &App) -> tauri::Result<()> { Ok(()) } +/// Unminimize, show, and focus `window`. +/// +/// Used when the operator asks for a window from `main`, and when a turn +/// starts waiting for an approval while the operator works in this +/// application. Both cases leave this process in the foreground, so focusing +/// needs no workaround. +/// +/// # Errors +/// +/// The runtime's error when a step cannot be sent to the event loop. +pub fn bring_to_front(window: &WebviewWindow) -> tauri::Result<()> { + window.unminimize()?; + window.show()?; + window.set_focus() +} + +/// Show the `approvals` window because a chat turn started waiting for a +/// decision (ADR-0105). +/// +/// When the operator is working in this application, the window is brought to +/// the front. Otherwise it is shown and its taskbar button flashes until the +/// operator comes to it, and focus stays with the other application: on +/// Windows, taking the foreground from another application sends that +/// application a simulated key press. Neither path approves anything: the +/// window never focuses **Approve**, no key decides, and **Approve** is armed +/// only one second after a review renders. +/// +/// Runs on the turn's thread before the wait starts. The window steps are +/// messages to the event loop. A failure is reported on standard error and +/// the turn waits either way. +pub fn present_approvals(app: &AppHandle) { + let Some(window) = app.get_webview_window(WindowLabel::Approvals.as_str()) else { + eprintln!("omgcode-desktop: the approvals window is missing"); + return; + }; + let shown = if operator_is_here(app) { + bring_to_front(&window) + } else { + window + .show() + .and_then(|()| window.request_user_attention(Some(UserAttentionType::Critical))) + }; + if shown.is_err() { + eprintln!("omgcode-desktop: could not show the approvals window"); + } +} + +/// Whether the operator is working in this application now. On Windows the +/// foreground window's owner decides, because a window's own focus flag is +/// clear while its webview holds the keyboard focus. Elsewhere a window of +/// this application must report focus; that query waits for the event loop. +fn operator_is_here(app: &AppHandle) -> bool { + omgcode_platform::foreground::this_process_owns_foreground().unwrap_or_else(|| { + WindowLabel::ALL.iter().any(|label| { + app.get_webview_window(label.as_str()) + .is_some_and(|window| window.is_focused().unwrap_or(false)) + }) + }) +} + /// Closing a secondary window hides it, so its state and the process survive. fn hide_on_close(window: &WebviewWindow) { let hidden = window.clone(); diff --git a/crates/omgcode-desktop/ui/src/approvals/app.ts b/crates/omgcode-desktop/ui/src/approvals/app.ts index 37e5d914..6c1a2411 100644 --- a/crates/omgcode-desktop/ui/src/approvals/app.ts +++ b/crates/omgcode-desktop/ui/src/approvals/app.ts @@ -452,8 +452,19 @@ export function startApprovals(root: HTMLElement): ApprovalsApp { void poller.tick(); poller.start(); + /** + * Rust shows and may focus this window when a turn starts waiting (ADR-0105); the + * list should not wait for the next poll. A tick changes only the list: the selection + * rule above still keeps a pending request under review. + */ + function onWindowFocus(): void { + void poller.tick(); + } + window.addEventListener("focus", onWindowFocus); + return { dispose() { + window.removeEventListener("focus", onWindowFocus); poller.stop(); clearInterval(countdownTimer); queueSplitter.dispose(); diff --git a/crates/omgcode-desktop/ui/tests/approvals.test.ts b/crates/omgcode-desktop/ui/tests/approvals.test.ts index 6970ac89..54795211 100644 --- a/crates/omgcode-desktop/ui/tests/approvals.test.ts +++ b/crates/omgcode-desktop/ui/tests/approvals.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { type ApprovalsApp, startApprovals } from "../src/approvals/app"; +import { type ApprovalsApp, LIST_POLL_MS, startApprovals } from "../src/approvals/app"; import { approvalEffect, approveGate, @@ -123,6 +123,8 @@ describe("approvals window", () => { let current: ApprovalDetail; async function start(): Promise { + // A second start in one test would otherwise leave the first window's listeners live. + app?.dispose(); ipc = installFakeIpc({ approvals_list: () => ({ now_unix: 1000, approvals }), approval_detail: () => current, @@ -667,5 +669,32 @@ describe("approvals window", () => { expect(root.querySelector(".who")?.classList.contains("clamp-1")).toBe(true); expect(root.querySelector(".summary")?.classList.contains("clamp-1")).toBe(true); }); + + it("lists a new request when the window gains focus and keeps the review", async () => { + approvals = [view({ id: "a1", expires_unix: 2000 })]; + await start(); + rowFor("a1").click(); + await settle(); + const review = root.querySelector(".review") as HTMLElement; + const listCalls = ipc.callsTo("approvals_list").length; + approvals = [view({ id: "a1", expires_unix: 2000 }), view({ id: "a2", expires_unix: 1500 })]; + window.dispatchEvent(new Event("focus")); + await settle(); + expect(ipc.callsTo("approvals_list")).toHaveLength(listCalls + 1); + expect(rowIds()).toEqual(["a2", "a1"]); + expect(rowFor("a1").getAttribute("aria-pressed")).toBe("true"); + expect(rowFor("a2").getAttribute("aria-pressed")).toBe("false"); + expect(root.querySelector(".review")).toBe(review); + }); + + it("stops refreshing on window focus once disposed", async () => { + await start(); + app?.dispose(); + app = null; + const listCalls = ipc.callsTo("approvals_list").length; + window.dispatchEvent(new Event("focus")); + await settle(LIST_POLL_MS); + expect(ipc.callsTo("approvals_list")).toHaveLength(listCalls); + }); }); }); diff --git a/crates/omgcode-platform/src/foreground.rs b/crates/omgcode-platform/src/foreground.rs new file mode 100644 index 00000000..991fc79d --- /dev/null +++ b/crates/omgcode-platform/src/foreground.rs @@ -0,0 +1,59 @@ +//! Whether the operator is working in this process's windows (ADR-0105). +//! +//! The desktop shell asks this before it brings a window to the front. On +//! Windows, taking the foreground from another application needs a workaround +//! that sends that application a simulated key press, so the shell does that +//! only when this process already owns the foreground window. The answer is +//! advisory and can change at any moment; it authorizes nothing. + +/// Whether the foreground window belongs to this process. +/// +/// On Windows, `Some(true)` when the window the operator is working in is +/// owned by this process, `Some(false)` when another process owns it or no +/// window is in the foreground. Elsewhere `None`: the caller decides with its +/// own toolkit's focus state. +/// +/// Two Win32 calls with no safe wrapper in `windows-sys`; each `unsafe` block +/// states its obligations. +#[cfg(windows)] +#[allow(unsafe_code)] +#[must_use] +pub fn this_process_owns_foreground() -> Option { + use windows_sys::Win32::UI::WindowsAndMessaging::{ + GetForegroundWindow, GetWindowThreadProcessId, + }; + + // SAFETY: `GetForegroundWindow` takes no arguments and only returns a + // window handle value, or null when no window is in the foreground. + let window = unsafe { GetForegroundWindow() }; + if window.is_null() { + return Some(false); + } + let mut process = 0_u32; + // SAFETY: `window` is a handle value the system just returned. If that + // window has since been destroyed, the call fails and returns 0, which is + // handled below; the handle is never dereferenced here. `process` is a + // live, writable `u32` for the whole call. + let thread = unsafe { GetWindowThreadProcessId(window, &raw mut process) }; + Some(thread != 0 && process == std::process::id()) +} + +/// Whether the foreground window belongs to this process. Not known outside +/// Windows. +#[cfg(not(windows))] +#[must_use] +pub const fn this_process_owns_foreground() -> Option { + None +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_answer_is_known_only_on_windows() { + // Which window is in the foreground depends on the test host, so only + // whether there is an answer is checked. + assert_eq!(this_process_owns_foreground().is_some(), cfg!(windows)); + } +} diff --git a/crates/omgcode-platform/src/lib.rs b/crates/omgcode-platform/src/lib.rs index 0095adb2..9efc277d 100644 --- a/crates/omgcode-platform/src/lib.rs +++ b/crates/omgcode-platform/src/lib.rs @@ -5,6 +5,7 @@ pub mod broker; pub mod browser; pub mod container; pub mod credentials; +pub mod foreground; pub mod interrupt; pub mod journal; pub mod private_store; diff --git a/docs/adr/0105-show-the-approvals-window-when-a-turn-starts-waiting.md b/docs/adr/0105-show-the-approvals-window-when-a-turn-starts-waiting.md new file mode 100644 index 00000000..6db646e6 --- /dev/null +++ b/docs/adr/0105-show-the-approvals-window-when-a-turn-starts-waiting.md @@ -0,0 +1,123 @@ +# 0105: Show the approvals window when a turn starts waiting + +- Status: Accepted +- Date: 2026-11-26 + +## Context + +A desktop chat turn whose tool call needs an approval waits in the turn for +the operator's decision (ADR-0063). Until now the operator learned about it +from the `main` window's advisory count, which polls `approvals_summary` +every 3 seconds, and had to open the hidden `approvals` window with +**Review** or the sidebar row (`approvals_show_window`). An operator asked +for the approvals window to open and come to the front by itself when an +approval is requested, and for the `settings` window to come to the front +when its button opens it. + +Bringing a window to the front is not free on Windows. When another +application owns the foreground, `SetForegroundWindow` is refused. tao, the +windowing library Tauri uses, then sends a simulated Alt key press to steal +the foreground permission (`force_window_active` in tao 0.37.2). That key +press reaches the application the operator is working in. The operator +chose that OMGCode must not take focus from another application: it shows +the approvals window and flashes its taskbar button instead. + +A window's own focus flag cannot answer "is the operator in OMGCode?" on +Windows: tao reports a window focused only while its top-level window holds +the keyboard focus, which the WebView2 child normally holds instead. + +The approvals window already guards against a window that appears under the +operator's hands: **Approve** is never the default focus, no key approves or +denies, and **Approve** is armed only one second after a review renders. + +## Decision + +1. **Core tells an observer when a wait begins.** `ApprovalWaitSlot` can + carry a `WaitObserver`, a `Fn()` that the turn calls on its own thread + each time it publishes the call it waits on, with no lock of the slot + held, before the wait starts. The observer receives nothing and decides + nothing. A slot without one behaves as before. +2. **The desktop service holds one observer.** + `DesktopService::set_approval_wait_observer` replaces it. Each turn + copies it when it starts; a running turn keeps its copy. + `DesktopService::shutdown` drops the service's copy, which ends the + reference cycle a shell observer forms through the application handle. +3. **The shell shows the approvals window from Rust.** At startup the shell + registers an observer that calls `present_approvals`. When this process + owns the foreground window, the approvals window is unminimized, shown, + and focused, as **Review** does. Otherwise it is shown and its taskbar + button flashes until the operator comes to it (`UserAttentionType::Critical`), + and nothing takes the foreground. On Windows, ownership of the foreground + window is read with `GetForegroundWindow` and `GetWindowThreadProcessId` + in `omgcode-platform` (`foreground::this_process_owns_foreground`). On + Linux, where the prototype has not run, any OMGCode window that reports + focus counts. +4. **Nothing reaches a webview.** No command, event, or capability is added. + The `main` window cannot open or focus the approvals window in any new + way, and the approvals window decides exactly as before. +5. **The approvals window lists again when it gains focus.** Its list poll + runs every 3 seconds and pauses while the window is hidden, so a hidden + window lists at once when shown, but a window that was already open + could show the new request up to 3 seconds after coming forward. A + `focus` listener on the page now runs one poll tick, which is skipped if + a list call is in flight. The tick changes only the list: a pending + request under review stays selected, as for any poll. +6. **Settings is unchanged.** `settings_show_window` and + `settings_show_workspace` already unminimize, show, and focus the window, + and now share the same helper as `approvals_show_window`. The operator + saw the window open in front every time in their latest testing and had + seen it open behind `main` only occasionally before. No cause was found + in the code, so no speculative change was made. + +## Alternatives considered + +- **Open the window from the `main` window's 3-second poll.** It needs no + core change, but it adds up to 3 seconds and depends on the `main` + webview's timers, which the browser engine slows while the window is + minimized. +- **Push a chat event and let `main` call `approvals_show_window`.** The + chat event sink exists only while `main` is subscribed, and a webview + round trip adds nothing that Rust cannot do itself. +- **Always take the foreground.** Rejected by the operator: on Windows it + sends a simulated key press to another application. +- **Use the window focus flags on Windows.** They read as unfocused while a + webview holds the keyboard focus, so the window would only flash while the + operator types in OMGCode. +- **Emit an event to the approvals window to list now.** It would reach the + window even when Windows delivers no focus event, but it adds an event and + a capability to the isolated window; a focus tick needs neither. +- **Poll the approvals list faster.** It would cut the delay for every + request, at the cost of more store reads while nothing changes. +- **Poll the turn table from a shell thread.** It needs a supervised thread + and still reacts late; the observer runs exactly when the wait begins. + +## Consequences + +- A desktop turn that starts waiting shows the approvals window at once. An + approval recorded by a CLI turn still shows only in the count. +- Showing the window selects and reviews the soonest-expiring pending + record, as opening it always has. For a file-write approval, that review + makes its audited broker read, now without a click. +- The observer runs before the wait starts, so a slow observer would delay + the wait; the shell's observer only posts messages to the event loop and, + on Windows, makes two non-blocking Win32 calls. +- `omgcode-desktop` now depends on the workspace crate `omgcode-platform`. + `omgcode-platform` gains one Windows-only function with two `unsafe` + calls; no third-party code is added. +- Every time the operator switches to the approvals window it makes one + extra `approvals_list` call, which reads the approval store as each poll + does. +- Tests cover the slot's observer, that a real desktop turn tells the + observer once and still waits for a decision, that shutdown drops the + observer, and that a focus event lists a new request without moving the + review. Which window ends up in front, the taskbar flash, and whether + WebView2 delivers the page's `focus` event when the window is activated + depend on the Windows desktop and were not driven by automation. + +## References + +- [docs/desktop-interface.md](../desktop-interface.md#approvals) +- [ADR-0063](0063-deny-prompt-or-allow-each-preference-wait-for-approvals-in-the-turn-and-journal-model-actions.md), + [ADR-0059](0059-configure-trusted-settings-in-an-isolated-desktop-settings-window.md) +- Microsoft, [`SetForegroundWindow`](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setforegroundwindow) + and [`GetWindowThreadProcessId`](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getwindowthreadprocessid) diff --git a/docs/adr/index.md b/docs/adr/index.md index 0fbadeff..d8dca277 100644 --- a/docs/adr/index.md +++ b/docs/adr/index.md @@ -119,3 +119,4 @@ meaningful alternative does not need an ADR. | [0102: Choose a reasoning effort per session](0102-choose-a-reasoning-effort-per-session.md) | Accepted | 2026-11-26 | | [0103: Generate toolchain profiles from installed toolchains](0103-generate-toolchain-profiles-from-installed-toolchains.md) | Accepted | 2026-11-26 | | [0104: Grant the workspace folder read-write without a folder dialog](0104-grant-the-workspace-folder-read-write-without-a-folder-dialog.md) | Accepted | 2026-11-26 | +| [0105: Show the approvals window when a turn starts waiting](0105-show-the-approvals-window-when-a-turn-starts-waiting.md) | Accepted | 2026-11-26 | diff --git a/docs/desktop-interface.md b/docs/desktop-interface.md index b911ae9c..483af028 100644 --- a/docs/desktop-interface.md +++ b/docs/desktop-interface.md @@ -454,7 +454,8 @@ The `main` window is laid out as follows. It has no model or provider control and shows no connection message (ADR-0084). The segment reads "N approvals waiting" with a **Review** button while the advisory count is above zero, and is hidden at - zero. **Review** and the sidebar row only call `approvals_show_window`. The + zero. **Review** and the sidebar row only call `approvals_show_window`; + Rust also shows the window when a turn starts waiting (ADR-0105). The notice line above the status bar now only reports a failure to open a window, with **Dismiss**; the earlier "An approval is waiting." banner is gone. @@ -1829,8 +1830,22 @@ The flow: exact call it waits on so that the approvals window can review it. 2. The `main` window polls `approvals_summary` every 3 seconds and shows the pending count. It can show the approvals window and nothing more. -3. The operator opens the `approvals` window. It polls `approvals_list` every 3 - seconds. Polling stops while a window is hidden. Since 0.45.0 (ADR-0065) + Since 0.69.0 (ADR-0105) Rust also shows the approvals window as soon as a + desktop turn starts waiting, before the wait begins, through an observer + the shell registers with the service at startup. When OMGCode owns the + foreground window (on Windows, read with `GetForegroundWindow`), the window + is unminimized, shown, and focused, as **Review** does. When another + application owns it, the window is shown and its taskbar button flashes + until the operator comes to it, and the foreground is not taken: on + Windows that would send the other application a simulated key press. No + webview can trigger this, and the window decides as below. An approval + recorded by a CLI turn shows only in the count. +3. The operator opens the `approvals` window, or it opens itself (step 2). + It polls `approvals_list` every 3 + seconds. Polling stops while a window is hidden. Since 0.69.0 (ADR-0105) + it also lists again when the window gains focus, so a request that + brought it forward is listed without waiting for the next poll; a new + request never replaces the one under review. Since 0.45.0 (ADR-0065) the window shows a queue beside a review pane; each column scrolls on its own, and below 720 pixels wide they stack. Since 0.66.0 (ADR-0101) the line between them moves, to widen the queue or, stacked, make it taller From 60cc4305623ec69a10c624ea2706dd6e60daa5ac Mon Sep 17 00:00:00 2001 From: James Chapman Date: Thu, 26 Nov 2026 17:00:47 +0000 Subject: [PATCH 04/12] test: match the new run refusal in the CLI workflow test The Windows workflow test still looked for the old refusal text, which ADR-0104 replaced with one that names the workspace's sandbox. Co-Authored-By: Claude Opus 5.5 --- crates/omgcode-cli/tests/run_workflow.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/omgcode-cli/tests/run_workflow.rs b/crates/omgcode-cli/tests/run_workflow.rs index cf050451..6ab1428a 100644 --- a/crates/omgcode-cli/tests/run_workflow.rs +++ b/crates/omgcode-cli/tests/run_workflow.rs @@ -416,7 +416,11 @@ fn windows_runs_need_the_workspace_grant() { let scene = Scene::build(true, false); assert_success(&scene.add_profile("system", &[])); let output = scene.run("system", &[], &shell("echo ungranted")); - assert!(error_message(&output).contains("grant the workspace directory")); + let message = error_message(&output); + assert!( + message.contains("the workspace's sandbox has no read-write grant on the workspace folder"), + "{message}" + ); assert_no_runs(&scene); scene.close(); } From 994e02cd9c2684b500e6e4cb2a6b0095cd61901b Mon Sep 17 00:00:00 2001 From: James Chapman Date: Thu, 26 Nov 2026 17:22:43 +0000 Subject: [PATCH 05/12] fix: release the wait observer and activate without simulated input Review found two gaps in ADR-0105: - The turn table keeps finished slots, and each held a clone of the approval-wait slot with the observer, so shutdown did not release it. The table now keeps ApprovalWaitSlot::reader, which shares the awaited call without the observer; only the turn thread's copy holds it. - The shell checked the foreground on the turn's thread and then queued tao's set_focus. If the operator switched applications in between, set_focus's fallback would send the other application a simulated Alt key press. The check and the activation now run in one event-loop callback, and the window is activated with SetForegroundWindow alone; if Windows refuses, the taskbar button flashes instead. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 42 +++++----- crates/omgcode-app/src/desktop.rs | 10 ++- crates/omgcode-app/src/desktop/chat.rs | 8 +- crates/omgcode-app/tests/desktop_approvals.rs | 23 ++++++ crates/omgcode-core/src/turn/approval_wait.rs | 48 +++++++++++- crates/omgcode-desktop/src/windows.rs | 77 +++++++++++++++---- crates/omgcode-platform/src/foreground.rs | 63 +++++++++++++-- ...ovals-window-when-a-turn-starts-waiting.md | 60 ++++++++++----- docs/desktop-interface.md | 15 ++-- 9 files changed, 273 insertions(+), 73 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 13dc6b3e..c0cc3db2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -572,27 +572,33 @@ Changes are recorded here before a release version is assigned. that the turn calls on its own thread, with no lock held, each time it publishes the call it waits on; the observer receives nothing and decides nothing. `DesktopService::set_approval_wait_observer` holds one, each turn - copies it when it starts, and `DesktopService::shutdown` drops it. The - shell registers an observer at startup. When OMGCode owns the foreground - window, read on Windows with `GetForegroundWindow` and - `GetWindowThreadProcessId` in a new `omgcode-platform` function - (`foreground::this_process_owns_foreground`), the approvals window is - unminimized, shown, and focused. Otherwise it is shown and its taskbar - button flashes, and the foreground is not taken, because on Windows that - sends the other application a simulated key press. No command, event, or - capability is added, and the approvals window still never focuses - **Approve**, decides on no key, and arms **Approve** one second after a - review renders. The approvals window also lists again when it gains focus, - so a request that brought it forward appears without waiting up to 3 - seconds for the next poll; a new request still never replaces the one - under review. An approval recorded by a CLI turn still shows only in the - count. The `settings` and `approvals` show commands now share one helper + copies it when it starts, the turn table keeps only an + `ApprovalWaitSlot::reader` without it, and `DesktopService::shutdown` + drops it. The shell registers an observer at startup that posts one + closure to the event loop, which checks the foreground and acts in the + same callback. When OMGCode owns the foreground window, read on Windows + with `GetForegroundWindow` and `GetWindowThreadProcessId` in a new + `omgcode-platform` function (`foreground::this_process_owns_foreground`), + the approvals window is unminimized, shown, and activated with + `SetForegroundWindow` alone (`foreground::activate_if_foreground_owner`), + never tao's `set_focus`. Otherwise, or if Windows refuses, it is shown + and its taskbar button flashes, and the foreground is not taken, because + on Windows that sends the other application a simulated key press. No + command, event, or capability is added, and the approvals window still + never focuses **Approve**, decides on no key, and arms **Approve** one + second after a review renders. The approvals window also lists again + when it gains focus, so a request that brought it forward appears without + waiting up to 3 seconds for the next poll; a new request still never + replaces the one under review. An approval recorded by a CLI turn still + shows only in the count. The `settings` and `approvals` show commands now share one helper and behave as before; the operator saw the settings window open in front every time in their latest testing, and no cause of an earlier, occasional open behind `main` was found. `omgcode-desktop` now depends on the - workspace crate `omgcode-platform`. Tests cover the observer, a real - desktop turn telling it once while still waiting for a decision, shutdown - dropping it, and the focus refresh keeping the review; which window ends + workspace crate `omgcode-platform`. Tests cover the observer and its + reader, a real desktop turn telling it once while still waiting for a + decision, shutdown dropping it with and without a finished turn, the + activation refusing a handle that is not this process's window, and the + focus refresh keeping the review; which window ends up in front, the taskbar flash, and whether WebView2 delivers the focus event were not driven by automation. The approvals tests now dispose a window before starting another in the same test. diff --git a/crates/omgcode-app/src/desktop.rs b/crates/omgcode-app/src/desktop.rs index c58c792c..2510960f 100644 --- a/crates/omgcode-app/src/desktop.rs +++ b/crates/omgcode-app/src/desktop.rs @@ -326,10 +326,12 @@ struct Inner { /// Called on a turn's thread each time the turn starts waiting for an /// approval decision, so the shell can show its approvals window /// (ADR-0105). It decides nothing. Each turn copies the observer when it - /// starts. Owners: this field and the slots of turns started while it was - /// set. A shell observer may own a handle that reaches this service, which - /// is a cycle; [`DesktopService::shutdown`] clears the field to end it, - /// and a turn that outlives shutdown keeps its copy until it ends. + /// starts. Owners: this field and the threads of turns started while it + /// was set; the turn table keeps only a reader of each slot, without the + /// observer, because it keeps finished slots. A shell observer may own a + /// handle that reaches this service, which is a cycle; + /// [`DesktopService::shutdown`] clears the field to end it, and a turn + /// that outlives shutdown keeps its copy until its thread ends. approval_wait_observer: Mutex>, /// Set while one settings change waits for the operator or applies, so /// a second change is refused rather than opening a second dialog. diff --git a/crates/omgcode-app/src/desktop/chat.rs b/crates/omgcode-app/src/desktop/chat.rs index f7f002a6..77961088 100644 --- a/crates/omgcode-app/src/desktop/chat.rs +++ b/crates/omgcode-app/src/desktop/chat.rs @@ -286,6 +286,10 @@ impl DesktopService { Some(observer) => ApprovalWaitSlot::new().with_observer(observer), None => ApprovalWaitSlot::new(), }; + // The table keeps finished slots, so it holds a reader: only the turn + // thread's copy keeps the observer, which shutdown must be able to + // release (ADR-0105). + let awaited = approval_wait.reader(); let job = TurnJob { session_id, path, @@ -294,7 +298,7 @@ impl DesktopService { token, clients, skills, - approval_wait: approval_wait.clone(), + approval_wait, }; // Reserve the slot and start the thread under one lock hold, so two @@ -311,7 +315,7 @@ impl DesktopService { return Err(DesktopError::too_many_turns()); } let handle = spawn_turn(inner, job)?; - turns.insert_running(session_id, handle, approval_wait); + turns.insert_running(session_id, handle, awaited); drop(turns); Ok(status_of( session_id, diff --git a/crates/omgcode-app/tests/desktop_approvals.rs b/crates/omgcode-app/tests/desktop_approvals.rs index 4c2599cc..0d33b965 100644 --- a/crates/omgcode-app/tests/desktop_approvals.rs +++ b/crates/omgcode-app/tests/desktop_approvals.rs @@ -477,6 +477,29 @@ fn shutdown_drops_the_approval_wait_observer() { assert_eq!(setup.server.finish(), 0); } +#[test] +fn a_finished_turn_does_not_keep_the_observer_after_shutdown() { + use std::sync::Arc; + + let setup = setup(vec![Step::reply(text("hello"))]); + let observer: Arc = Arc::new(|| {}); + let watch = Arc::downgrade(&observer); + setup + .service + .set_approval_wait_observer(observer) + .expect("observer"); + let session = setup.session("Finished"); + setup.turn(session, "say hello"); + // The turn table keeps the finished slot, which must hold no observer. + let report = setup.service.shutdown(Duration::from_secs(5)); + assert_eq!(report.still_running, 0); + assert!( + watch.upgrade().is_none(), + "a finished turn's slot keeps the observer" + ); + assert_eq!(setup.server.finish(), 1); +} + /// Two sessions, each with a turn waiting on one pending edit approval for /// its own file. Each turn needs one more model reply once it is decided. fn two_pending() -> (Setup, [(Uuid, Uuid); 2]) { diff --git a/crates/omgcode-core/src/turn/approval_wait.rs b/crates/omgcode-core/src/turn/approval_wait.rs index 63973c82..33688c5a 100644 --- a/crates/omgcode-core/src/turn/approval_wait.rs +++ b/crates/omgcode-core/src/turn/approval_wait.rs @@ -43,7 +43,9 @@ pub struct AwaitedCall { /// /// An attached [`WaitObserver`] is shared by every clone made after it was /// attached. It must not own a clone of the slot it is attached to, or the -/// slot would keep itself alive. +/// slot would keep itself alive. A holder that only reads the call, and may +/// outlive the turn, keeps [`ApprovalWaitSlot::reader`] instead, so it does +/// not keep the observer alive. #[derive(Clone, Default)] pub struct ApprovalWaitSlot { call: Arc>>, @@ -84,6 +86,16 @@ impl ApprovalWaitSlot { self } + /// A handle that shares this slot's call but holds no observer. A wait + /// published through it tells no observer. + #[must_use] + pub fn reader(&self) -> Self { + Self { + call: Arc::clone(&self.call), + observer: None, + } + } + /// The call the turn waits on now, or `None` when it is not waiting. #[must_use] pub fn current(&self) -> Option { @@ -180,6 +192,40 @@ mod tests { assert_eq!(reader.current(), None); } + #[test] + fn a_reader_shares_the_call_but_not_the_observer() { + use std::sync::atomic::{AtomicUsize, Ordering}; + + let calls = Arc::new(AtomicUsize::new(0)); + let observer: WaitObserver = { + let calls = Arc::clone(&calls); + Arc::new(move || { + calls.fetch_add(1, Ordering::SeqCst); + }) + }; + let weak = Arc::downgrade(&observer); + let slot = ApprovalWaitSlot::new().with_observer(observer); + let reader = slot.reader(); + assert!(format!("{reader:?}").contains("observer: false")); + + let published = call(); + let guard = slot.publish(published.clone()); + assert_eq!(reader.current(), Some(published)); + drop(guard); + assert_eq!(reader.current(), None); + drop(reader.publish(call())); + assert_eq!(calls.load(Ordering::SeqCst), 1); + + // Only the reader is left, and it does not keep the observer alive. + drop(slot); + assert!(weak.upgrade().is_none()); + let late = call(); + let shared = reader.clone(); + let guard = reader.publish(late.clone()); + assert_eq!(shared.current(), Some(late)); + drop(guard); + } + #[test] fn a_slot_without_an_observer_still_publishes_and_debug_shows_no_closure() { let slot = ApprovalWaitSlot::new(); diff --git a/crates/omgcode-desktop/src/windows.rs b/crates/omgcode-desktop/src/windows.rs index 990bf1a2..f840247b 100644 --- a/crates/omgcode-desktop/src/windows.rs +++ b/crates/omgcode-desktop/src/windows.rs @@ -138,10 +138,10 @@ pub fn create_windows(app: &App) -> tauri::Result<()> { /// Unminimize, show, and focus `window`. /// -/// Used when the operator asks for a window from `main`, and when a turn -/// starts waiting for an approval while the operator works in this -/// application. Both cases leave this process in the foreground, so focusing -/// needs no workaround. +/// Used when the operator asks for a window from `main`, a request that +/// follows their own click, so this process is in the foreground and +/// focusing needs no workaround. A window shown on its own uses +/// [`present_approvals`] instead. /// /// # Errors /// @@ -157,36 +157,79 @@ pub fn bring_to_front(window: &WebviewWindow) -> tauri::Result<()> { /// /// When the operator is working in this application, the window is brought to /// the front. Otherwise it is shown and its taskbar button flashes until the -/// operator comes to it, and focus stays with the other application: on -/// Windows, taking the foreground from another application sends that -/// application a simulated key press. Neither path approves anything: the -/// window never focuses **Approve**, no key decides, and **Approve** is armed -/// only one second after a review renders. +/// operator comes to it, and focus stays with the other application. Neither +/// path approves anything: the window never focuses **Approve**, no key +/// decides, and **Approve** is armed only one second after a review renders. /// -/// Runs on the turn's thread before the wait starts. The window steps are -/// messages to the event loop. A failure is reported on standard error and -/// the turn waits either way. +/// Runs on the turn's thread before the wait starts and only posts one +/// closure to the event loop. A failure is reported on standard error and the +/// turn waits either way. pub fn present_approvals(app: &AppHandle) { + let handle = app.clone(); + // The foreground check and the activation run in one event-loop callback, + // where window calls take effect at once: checking on the turn's thread + // left a gap in which the operator could switch applications before the + // focus request ran. + if app + .run_on_main_thread(move || present_on_event_loop(&handle)) + .is_err() + { + eprintln!("omgcode-desktop: could not show the approvals window"); + } +} + +fn present_on_event_loop(app: &AppHandle) { let Some(window) = app.get_webview_window(WindowLabel::Approvals.as_str()) else { eprintln!("omgcode-desktop: the approvals window is missing"); return; }; let shown = if operator_is_here(app) { - bring_to_front(&window) + raise_without_input(&window) } else { - window - .show() - .and_then(|()| window.request_user_attention(Some(UserAttentionType::Critical))) + show_and_flash(&window) }; if shown.is_err() { eprintln!("omgcode-desktop: could not show the approvals window"); } } +/// Show `window` and flash its taskbar button until the operator comes to it, +/// leaving the foreground where it is. +fn show_and_flash(window: &WebviewWindow) -> tauri::Result<()> { + window.show()?; + window.request_user_attention(Some(UserAttentionType::Critical)) +} + +/// Unminimize, show, and activate `window` without tao's `set_focus`, which +/// sends a simulated Alt key press to the foreground application when +/// Windows refuses the activation. If another application took the +/// foreground since the check, or Windows refuses, the window flashes +/// instead. +#[cfg(windows)] +fn raise_without_input(window: &WebviewWindow) -> tauri::Result<()> { + window.unminimize()?; + window.show()?; + let activated = window.hwnd().is_ok_and(|hwnd| { + omgcode_platform::foreground::activate_if_foreground_owner(hwnd.0.addr()) + }); + if activated { + Ok(()) + } else { + window.request_user_attention(Some(UserAttentionType::Critical)) + } +} + +/// Unminimize, show, and focus `window`; outside Windows the toolkit's focus +/// request sends no input. +#[cfg(not(windows))] +fn raise_without_input(window: &WebviewWindow) -> tauri::Result<()> { + bring_to_front(window) +} + /// Whether the operator is working in this application now. On Windows the /// foreground window's owner decides, because a window's own focus flag is /// clear while its webview holds the keyboard focus. Elsewhere a window of -/// this application must report focus; that query waits for the event loop. +/// this application must report focus. fn operator_is_here(app: &AppHandle) -> bool { omgcode_platform::foreground::this_process_owns_foreground().unwrap_or_else(|| { WindowLabel::ALL.iter().any(|label| { diff --git a/crates/omgcode-platform/src/foreground.rs b/crates/omgcode-platform/src/foreground.rs index 991fc79d..34766e3b 100644 --- a/crates/omgcode-platform/src/foreground.rs +++ b/crates/omgcode-platform/src/foreground.rs @@ -1,10 +1,13 @@ -//! Whether the operator is working in this process's windows (ADR-0105). +//! Whether the operator is working in this process's windows, and bringing +//! one of them forward without simulated input (ADR-0105). //! -//! The desktop shell asks this before it brings a window to the front. On -//! Windows, taking the foreground from another application needs a workaround -//! that sends that application a simulated key press, so the shell does that -//! only when this process already owns the foreground window. The answer is -//! advisory and can change at any moment; it authorizes nothing. +//! The desktop shell asks this before it brings a window to the front on its +//! own. On Windows, taking the foreground from another application needs a +//! workaround that sends that application a simulated key press, so the shell +//! brings a window forward only when this process already owns the foreground +//! window, and then with [`activate_if_foreground_owner`], which sends no +//! input. The answer is advisory and can change at any moment; it authorizes +//! nothing. /// Whether the foreground window belongs to this process. /// @@ -38,6 +41,44 @@ pub fn this_process_owns_foreground() -> Option { Some(thread != 0 && process == std::process::id()) } +/// Activate `window` if this process owns the foreground window now, with +/// `SetForegroundWindow` alone and never simulated input. +/// +/// `window` is the value of a top-level window's handle, such as the address +/// inside a toolkit's `HWND`. A handle is an opaque value, not memory, so it +/// is taken as an integer. It must belong to this process; a handle of +/// another process, a destroyed window, or 0 is left alone. Returns `true` only +/// when Windows activated the window. `false` means another process owns the +/// foreground, the handle is not this process's, or Windows refused, and the +/// caller should ask for attention instead. +/// +/// Windows only: elsewhere the toolkit's own focus request sends no input. +#[cfg(windows)] +#[allow(unsafe_code)] +#[must_use] +pub fn activate_if_foreground_owner(window: usize) -> bool { + use windows_sys::Win32::UI::WindowsAndMessaging::{ + GetWindowThreadProcessId, SetForegroundWindow, + }; + + if window == 0 || this_process_owns_foreground() != Some(true) { + return false; + } + let window = std::ptr::without_provenance_mut(window); + let mut process = 0_u32; + // SAFETY: `GetWindowThreadProcessId` only reads the handle value; an + // invalid or destroyed handle makes it fail and return 0, handled below. + // `process` is a live, writable `u32` for the whole call. + let thread = unsafe { GetWindowThreadProcessId(window, &raw mut process) }; + if thread == 0 || process != std::process::id() { + return false; + } + // SAFETY: `SetForegroundWindow` takes a handle value and reports failure + // for one that is not a window; it sends no input. The handle was just + // checked to name a window of this process. + unsafe { SetForegroundWindow(window) != 0 } +} + /// Whether the foreground window belongs to this process. Not known outside /// Windows. #[cfg(not(windows))] @@ -56,4 +97,14 @@ mod tests { // whether there is an answer is checked. assert_eq!(this_process_owns_foreground().is_some(), cfg!(windows)); } + + #[cfg(windows)] + #[test] + fn a_handle_that_is_not_this_processs_window_is_never_activated() { + // Zero and a value no window of this process has are refused before + // any activation. + // No test activates a real window, which would take the host's focus. + assert!(!activate_if_foreground_owner(0)); + assert!(!activate_if_foreground_owner(0x7FFF_FFF0)); + } } diff --git a/docs/adr/0105-show-the-approvals-window-when-a-turn-starts-waiting.md b/docs/adr/0105-show-the-approvals-window-when-a-turn-starts-waiting.md index 6db646e6..7d7a291e 100644 --- a/docs/adr/0105-show-the-approvals-window-when-a-turn-starts-waiting.md +++ b/docs/adr/0105-show-the-approvals-window-when-a-turn-starts-waiting.md @@ -39,19 +39,30 @@ denies, and **Approve** is armed only one second after a review renders. nothing. A slot without one behaves as before. 2. **The desktop service holds one observer.** `DesktopService::set_approval_wait_observer` replaces it. Each turn - copies it when it starts; a running turn keeps its copy. - `DesktopService::shutdown` drops the service's copy, which ends the + copies it when it starts; a running turn keeps its copy until its thread + ends. The turn table, which keeps finished slots, holds + `ApprovalWaitSlot::reader`, which shares the awaited call but not the + observer. `DesktopService::shutdown` drops the service's copy, so once + the turn threads have ended nothing holds the observer, which ends the reference cycle a shell observer forms through the application handle. 3. **The shell shows the approvals window from Rust.** At startup the shell - registers an observer that calls `present_approvals`. When this process + registers an observer that calls `present_approvals`, which posts one + closure to the event loop. There, where window calls take effect at once, + the shell checks the foreground and acts, so the operator cannot switch + applications between the check and the activation. When this process owns the foreground window, the approvals window is unminimized, shown, - and focused, as **Review** does. Otherwise it is shown and its taskbar - button flashes until the operator comes to it (`UserAttentionType::Critical`), - and nothing takes the foreground. On Windows, ownership of the foreground + and activated. Otherwise it is shown and its taskbar button flashes + until the operator comes to it (`UserAttentionType::Critical`), and + nothing takes the foreground. On Windows, ownership of the foreground window is read with `GetForegroundWindow` and `GetWindowThreadProcessId` - in `omgcode-platform` (`foreground::this_process_owns_foreground`). On - Linux, where the prototype has not run, any OMGCode window that reports - focus counts. + in `omgcode-platform` (`foreground::this_process_owns_foreground`), and + the window is activated with `SetForegroundWindow` alone + (`foreground::activate_if_foreground_owner`), never with tao's + `set_focus`, whose fallback sends the simulated key press. If Windows + refuses, or another application took the foreground since the check, the + window flashes instead. On Linux, where the prototype has not run, any + OMGCode window that reports focus counts, and the toolkit's focus + request is used. 4. **Nothing reaches a webview.** No command, event, or capability is added. The `main` window cannot open or focus the approvals window in any new way, and the approvals window decides exactly as before. @@ -64,7 +75,9 @@ denies, and **Approve** is armed only one second after a review renders. request under review stays selected, as for any poll. 6. **Settings is unchanged.** `settings_show_window` and `settings_show_workspace` already unminimize, show, and focus the window, - and now share the same helper as `approvals_show_window`. The operator + and now share the same helper as `approvals_show_window`. That helper + keeps tao's `set_focus`, because it runs on the operator's own click in + OMGCode, which leaves this process in the foreground. The operator saw the window open in front every time in their latest testing and had seen it open behind `main` only occasionally before. No cause was found in the code, so no speculative change was made. @@ -90,6 +103,13 @@ denies, and **Approve** is armed only one second after a review renders. request, at the cost of more store reads while nothing changes. - **Poll the turn table from a shell thread.** It needs a supervised thread and still reacts late; the observer runs exactly when the wait begins. +- **Check the foreground on the turn's thread and queue the focus.** Review + found that the operator could switch applications before the queued + `set_focus` ran, which would then send the simulated key press to the + other application. +- **Clear the observer from each slot when its turn finishes.** It works, + but every path that ends a turn would have to remember to do it; a reader + that never held the observer needs no cleanup. ## Consequences @@ -99,20 +119,22 @@ denies, and **Approve** is armed only one second after a review renders. record, as opening it always has. For a file-write approval, that review makes its audited broker read, now without a click. - The observer runs before the wait starts, so a slow observer would delay - the wait; the shell's observer only posts messages to the event loop and, - on Windows, makes two non-blocking Win32 calls. + the wait; the shell's observer only posts one closure to the event loop. - `omgcode-desktop` now depends on the workspace crate `omgcode-platform`. - `omgcode-platform` gains one Windows-only function with two `unsafe` + `omgcode-platform` gains two Windows-only functions with four `unsafe` calls; no third-party code is added. - Every time the operator switches to the approvals window it makes one extra `approvals_list` call, which reads the approval store as each poll does. -- Tests cover the slot's observer, that a real desktop turn tells the - observer once and still waits for a decision, that shutdown drops the - observer, and that a focus event lists a new request without moving the - review. Which window ends up in front, the taskbar flash, and whether - WebView2 delivers the page's `focus` event when the window is activated - depend on the Windows desktop and were not driven by automation. +- Tests cover the slot's observer and its reader, that a real desktop turn + tells the observer once and still waits for a decision, that shutdown + drops the observer with and without a finished turn in the table, that + activation refuses a handle that is not this process's window, and that + a focus event lists a new request without moving the review. No test + activates a real window. Which window ends up in front, the taskbar + flash, and whether WebView2 delivers the page's `focus` event when the + window is activated depend on the Windows desktop and were not driven by + automation. ## References diff --git a/docs/desktop-interface.md b/docs/desktop-interface.md index 483af028..62053718 100644 --- a/docs/desktop-interface.md +++ b/docs/desktop-interface.md @@ -1832,12 +1832,15 @@ The flow: pending count. It can show the approvals window and nothing more. Since 0.69.0 (ADR-0105) Rust also shows the approvals window as soon as a desktop turn starts waiting, before the wait begins, through an observer - the shell registers with the service at startup. When OMGCode owns the - foreground window (on Windows, read with `GetForegroundWindow`), the window - is unminimized, shown, and focused, as **Review** does. When another - application owns it, the window is shown and its taskbar button flashes - until the operator comes to it, and the foreground is not taken: on - Windows that would send the other application a simulated key press. No + the shell registers with the service at startup. The observer posts one + closure to the event loop, which checks the foreground and acts in the + same callback. When OMGCode owns the foreground window (on Windows, read + with `GetForegroundWindow`), the window is unminimized, shown, and + activated with `SetForegroundWindow` alone, not tao's `set_focus`. When + another application owns it, or Windows refuses, the window is shown and + its taskbar button flashes until the operator comes to it, and the + foreground is not taken: on Windows that would send the other + application a simulated key press. No webview can trigger this, and the window decides as below. An approval recorded by a CLI turn shows only in the count. 3. The operator opens the `approvals` window, or it opens itself (step 2). From 7603cfd452ef03bad27be324d47a9666d726ec64 Mon Sep 17 00:00:00 2001 From: James Chapman Date: Thu, 26 Nov 2026 17:24:46 +0000 Subject: [PATCH 06/12] fix: name the sandbox in the container grant folder dialog title ADR-0104 and the changelog say the folder dialog's title names who gets the access, but the read-execute dialog said only "the workspace's commands". It now names the workspace's sandbox, as the confirmations do, and the fixed-titles test covers it. Co-Authored-By: Claude Opus 5.5 --- crates/omgcode-app/src/desktop/settings_changes.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/crates/omgcode-app/src/desktop/settings_changes.rs b/crates/omgcode-app/src/desktop/settings_changes.rs index 90c04864..71e55171 100644 --- a/crates/omgcode-app/src/desktop/settings_changes.rs +++ b/crates/omgcode-app/src/desktop/settings_changes.rs @@ -98,7 +98,9 @@ impl FolderPurpose { Self::Skill => "Choose a skill folder", Self::ToolchainRoot => "Choose a read-only root for the toolchain profile", Self::ToolchainPathEntry => "Choose a PATH entry inside a root of the profile", - Self::ContainerGrant => "Choose a folder the workspace's commands may read and execute", + // The access goes to the workspace's AppContainer, not to the + // operator or the folder (ADR-0104). + Self::ContainerGrant => "Choose a folder the workspace's sandbox may read and execute", } } } @@ -1535,5 +1537,10 @@ mod tests { FolderPurpose::PackageCache.title(), "Choose a package cache folder" ); + // The grant dialog names who receives the access (ADR-0104). + assert_eq!( + FolderPurpose::ContainerGrant.title(), + "Choose a folder the workspace's sandbox may read and execute" + ); } } From ff6cd3ad77a1d6b51c6c14a09c7f35d4828be6f7 Mon Sep 17 00:00:00 2001 From: James Chapman Date: Thu, 26 Nov 2026 17:30:18 +0000 Subject: [PATCH 07/12] docs: record that showing the approvals window requests activation Review noted that tao's show and unminimize call ShowWindow with activating flags. Windows' foreground lock refuses that activation for a background process and no input is sent, but a non-activating show is not available through tao after creation, and a direct ShowWindow would leave tao's visibility flag stale so a later hide would do nothing. ADR-0105 now records this and that the stacking order was not checked on a desktop. Co-Authored-By: Claude Opus 5.5 --- ...he-approvals-window-when-a-turn-starts-waiting.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/docs/adr/0105-show-the-approvals-window-when-a-turn-starts-waiting.md b/docs/adr/0105-show-the-approvals-window-when-a-turn-starts-waiting.md index 7d7a291e..7ace4bb8 100644 --- a/docs/adr/0105-show-the-approvals-window-when-a-turn-starts-waiting.md +++ b/docs/adr/0105-show-the-approvals-window-when-a-turn-starts-waiting.md @@ -120,6 +120,18 @@ denies, and **Approve** is armed only one second after a review renders. makes its audited broker read, now without a click. - The observer runs before the wait starts, so a slow observer would delay the wait; the shell's observer only posts one closure to the event loop. +- Showing a hidden window still goes through tao's `show`, which calls + `ShowWindow` with `SW_SHOW`, and unminimizing calls it with + `SW_RESTORE`; both flags request activation. When another application + owns the foreground, Windows' foreground lock refuses that activation + and flashes the taskbar button instead, and no input is sent. A + non-activating show is not available through tao once a window exists: + its `MARKER_DONT_FOCUS` flag applies only at creation. A direct + `ShowWindow` with `SW_SHOWNOACTIVATE` would leave tao's visibility flag + clear, and tao skips a change that matches its flag, so a later `hide`, + such as closing the window, would do nothing. Where the shown window + lands in the stacking order while another application owns the + foreground was not checked on a Windows desktop. - `omgcode-desktop` now depends on the workspace crate `omgcode-platform`. `omgcode-platform` gains two Windows-only functions with four `unsafe` calls; no third-party code is added. From aa48160db05d3e7ec8356210025b63ddfe7ead45 Mon Sep 17 00:00:00 2001 From: James Chapman Date: Thu, 26 Nov 2026 17:45:33 +0000 Subject: [PATCH 08/12] docs: say the event-loop callback narrows the foreground gap ADR-0105 said the operator cannot switch applications between the foreground check and the activation. The callback only narrows that gap; activate_if_foreground_owner checks ownership again and the window flashes if another application took over. The ADR and the code comment now say so, so the second check is not mistaken for redundant. Co-Authored-By: Claude Opus 5.5 --- crates/omgcode-desktop/src/windows.rs | 7 ++++--- ...show-the-approvals-window-when-a-turn-starts-waiting.md | 7 +++++-- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/crates/omgcode-desktop/src/windows.rs b/crates/omgcode-desktop/src/windows.rs index f840247b..f9ea4f3a 100644 --- a/crates/omgcode-desktop/src/windows.rs +++ b/crates/omgcode-desktop/src/windows.rs @@ -167,9 +167,10 @@ pub fn bring_to_front(window: &WebviewWindow) -> tauri::Result<()> { pub fn present_approvals(app: &AppHandle) { let handle = app.clone(); // The foreground check and the activation run in one event-loop callback, - // where window calls take effect at once: checking on the turn's thread - // left a gap in which the operator could switch applications before the - // focus request ran. + // where window calls take effect at once, which narrows the gap that a + // check on the turn's thread left before the queued focus request ran. + // It does not close it: `activate_if_foreground_owner` checks ownership + // again, and the window flashes if another application took over. if app .run_on_main_thread(move || present_on_event_loop(&handle)) .is_err() diff --git a/docs/adr/0105-show-the-approvals-window-when-a-turn-starts-waiting.md b/docs/adr/0105-show-the-approvals-window-when-a-turn-starts-waiting.md index 7ace4bb8..15faef07 100644 --- a/docs/adr/0105-show-the-approvals-window-when-a-turn-starts-waiting.md +++ b/docs/adr/0105-show-the-approvals-window-when-a-turn-starts-waiting.md @@ -48,8 +48,11 @@ denies, and **Approve** is armed only one second after a review renders. 3. **The shell shows the approvals window from Rust.** At startup the shell registers an observer that calls `present_approvals`, which posts one closure to the event loop. There, where window calls take effect at once, - the shell checks the foreground and acts, so the operator cannot switch - applications between the check and the activation. When this process + the shell checks the foreground and acts, so only a few window calls on + one thread separate the check from the activation, not a queued message. + Another application can still take the foreground in that gap, so the + activation checks ownership again (below) rather than relying on the + callback to make the check and the activation atomic. When this process owns the foreground window, the approvals window is unminimized, shown, and activated. Otherwise it is shown and its taskbar button flashes until the operator comes to it (`UserAttentionType::Critical`), and From c114496ba021b3b4dce758715b5362826a7219c3 Mon Sep 17 00:00:00 2001 From: James Chapman Date: Thu, 26 Nov 2026 17:50:31 +0000 Subject: [PATCH 09/12] docs: credit the taskbar flash to the shell's own request ADR-0105 said Windows flashes the taskbar button when it refuses the activation. The flash comes from the shell's request_user_attention call; the ADR now says so, so that call is not read as redundant. Co-Authored-By: Claude Opus 5.5 --- ...-show-the-approvals-window-when-a-turn-starts-waiting.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/adr/0105-show-the-approvals-window-when-a-turn-starts-waiting.md b/docs/adr/0105-show-the-approvals-window-when-a-turn-starts-waiting.md index 15faef07..4f92fc83 100644 --- a/docs/adr/0105-show-the-approvals-window-when-a-turn-starts-waiting.md +++ b/docs/adr/0105-show-the-approvals-window-when-a-turn-starts-waiting.md @@ -126,8 +126,10 @@ denies, and **Approve** is armed only one second after a review renders. - Showing a hidden window still goes through tao's `show`, which calls `ShowWindow` with `SW_SHOW`, and unminimizing calls it with `SW_RESTORE`; both flags request activation. When another application - owns the foreground, Windows' foreground lock refuses that activation - and flashes the taskbar button instead, and no input is sent. A + owns the foreground, Windows' foreground restrictions should refuse that + activation, and no input is sent either way. The taskbar flash comes + from the shell's own `request_user_attention` call with + `UserAttentionType::Critical`, not from the refusal. A non-activating show is not available through tao once a window exists: its `MARKER_DONT_FOCUS` flag applies only at creation. A direct `ShowWindow` with `SW_SHOWNOACTIVATE` would leave tao's visibility flag From 96dc4e7741d0d9df506d3e41ee398c370c2ee057 Mon Sep 17 00:00:00 2001 From: James Chapman Date: Thu, 26 Nov 2026 17:55:23 +0000 Subject: [PATCH 10/12] docs: say the second ownership check is Windows-only ADR-0105 said the activation checks foreground ownership again on every platform. Only the Windows path does, through activate_if_foreground_owner; on Linux the toolkit's focus request runs without a second check and sends no simulated input. Co-Authored-By: Claude Opus 5.5 --- ...-the-approvals-window-when-a-turn-starts-waiting.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/docs/adr/0105-show-the-approvals-window-when-a-turn-starts-waiting.md b/docs/adr/0105-show-the-approvals-window-when-a-turn-starts-waiting.md index 4f92fc83..d9c15efb 100644 --- a/docs/adr/0105-show-the-approvals-window-when-a-turn-starts-waiting.md +++ b/docs/adr/0105-show-the-approvals-window-when-a-turn-starts-waiting.md @@ -50,9 +50,10 @@ denies, and **Approve** is armed only one second after a review renders. closure to the event loop. There, where window calls take effect at once, the shell checks the foreground and acts, so only a few window calls on one thread separate the check from the activation, not a queued message. - Another application can still take the foreground in that gap, so the - activation checks ownership again (below) rather than relying on the - callback to make the check and the activation atomic. When this process + Another application can still take the foreground in that gap, so on + Windows the activation checks ownership again (below) rather than + relying on the callback to make the check and the activation atomic. + When this process owns the foreground window, the approvals window is unminimized, shown, and activated. Otherwise it is shown and its taskbar button flashes until the operator comes to it (`UserAttentionType::Critical`), and @@ -65,7 +66,8 @@ denies, and **Approve** is armed only one second after a review renders. refuses, or another application took the foreground since the check, the window flashes instead. On Linux, where the prototype has not run, any OMGCode window that reports focus counts, and the toolkit's focus - request is used. + request is used without a second ownership check; it sends no simulated + input. 4. **Nothing reaches a webview.** No command, event, or capability is added. The `main` window cannot open or focus the approvals window in any new way, and the approvals window decides exactly as before. From daa0c359c49d7ff049feb7e829a350f02a984754 Mon Sep 17 00:00:00 2001 From: James Chapman Date: Thu, 26 Nov 2026 18:01:53 +0000 Subject: [PATCH 11/12] docs: ground the activation and flash claims in Microsoft's docs Review asked whether ShowWindow could make a background OMGCode the foreground owner and defeat the ownership recheck, and whether Windows flashes the taskbar button itself. ADR-0105 now cites SetActiveWindow (activation does not bring a background application forward) and SetForegroundWindow (a refused process is flashed instead), notes that the recheck reads GetForegroundWindow rather than the active window, and records the documented cases in which Windows lets any process set the foreground. The flash is described as coming from Windows, the shell's request_user_attention call, or both. Co-Authored-By: Claude Opus 5.5 --- ...ovals-window-when-a-turn-starts-waiting.md | 38 ++++++++++++------- 1 file changed, 25 insertions(+), 13 deletions(-) diff --git a/docs/adr/0105-show-the-approvals-window-when-a-turn-starts-waiting.md b/docs/adr/0105-show-the-approvals-window-when-a-turn-starts-waiting.md index d9c15efb..69e1196c 100644 --- a/docs/adr/0105-show-the-approvals-window-when-a-turn-starts-waiting.md +++ b/docs/adr/0105-show-the-approvals-window-when-a-turn-starts-waiting.md @@ -127,18 +127,28 @@ denies, and **Approve** is armed only one second after a review renders. the wait; the shell's observer only posts one closure to the event loop. - Showing a hidden window still goes through tao's `show`, which calls `ShowWindow` with `SW_SHOW`, and unminimizing calls it with - `SW_RESTORE`; both flags request activation. When another application - owns the foreground, Windows' foreground restrictions should refuse that - activation, and no input is sent either way. The taskbar flash comes - from the shell's own `request_user_attention` call with - `UserAttentionType::Critical`, not from the refusal. A - non-activating show is not available through tao once a window exists: - its `MARKER_DONT_FOCUS` flag applies only at creation. A direct - `ShowWindow` with `SW_SHOWNOACTIVATE` would leave tao's visibility flag - clear, and tao skips a change that matches its flag, so a later `hide`, - such as closing the window, would do nothing. Where the shown window - lands in the stacking order while another application owns the - foreground was not checked on a Windows desktop. + `SW_RESTORE`; both flags request activation, and no input is sent + either way. Microsoft documents that activating a window does not bring + it to the foreground when its application is in the background + (`SetActiveWindow`), and that a process that may not set the foreground + gets its taskbar button flashed instead (`SetForegroundWindow`). The + ownership recheck before `SetForegroundWindow` reads the system's + foreground window with `GetForegroundWindow`, not the thread's active + window, so an activation refused this way does not satisfy it. The + `ShowWindow` page does not restate these rules, and `SetForegroundWindow` + lists cases in which any process may set the foreground, such as an + expired foreground lock time-out or no foreground window at all; in + those cases Windows, not this code, may let the shown window come + forward. Windows may flash the button on a refusal, and the shell also + calls `request_user_attention` with `UserAttentionType::Critical`, so it + flashes until the operator comes to it either way. A non-activating show + is not available through tao once a window exists: its + `MARKER_DONT_FOCUS` flag applies only at creation. A direct `ShowWindow` + with `SW_SHOWNOACTIVATE` would leave tao's visibility flag clear, and tao + skips a change that matches its flag, so a later `hide`, such as closing + the window, would do nothing. Which window ends up in front, and where + the shown window lands in the stacking order, while another application + owns the foreground were not checked on a Windows desktop. - `omgcode-desktop` now depends on the workspace crate `omgcode-platform`. `omgcode-platform` gains two Windows-only functions with four `unsafe` calls; no third-party code is added. @@ -160,5 +170,7 @@ denies, and **Approve** is armed only one second after a review renders. - [docs/desktop-interface.md](../desktop-interface.md#approvals) - [ADR-0063](0063-deny-prompt-or-allow-each-preference-wait-for-approvals-in-the-turn-and-journal-model-actions.md), [ADR-0059](0059-configure-trusted-settings-in-an-isolated-desktop-settings-window.md) -- Microsoft, [`SetForegroundWindow`](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setforegroundwindow) +- Microsoft, [`SetForegroundWindow`](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setforegroundwindow), + [`SetActiveWindow`](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setactivewindow), + [`ShowWindow`](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-showwindow), and [`GetWindowThreadProcessId`](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getwindowthreadprocessid) From 77c53a7003c64ae312683690bfcf56abd6d96822 Mon Sep 17 00:00:00 2001 From: James Chapman Date: Thu, 26 Nov 2026 18:19:29 +0000 Subject: [PATCH 12/12] docs: say which foreground helper is Windows-only ADR-0105 called both new omgcode-platform functions Windows-only. this_process_owns_foreground exists on every platform and returns None outside Windows; only activate_if_foreground_owner is Windows-only. Co-Authored-By: Claude Opus 5.5 --- ...show-the-approvals-window-when-a-turn-starts-waiting.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/adr/0105-show-the-approvals-window-when-a-turn-starts-waiting.md b/docs/adr/0105-show-the-approvals-window-when-a-turn-starts-waiting.md index 69e1196c..3a0c1221 100644 --- a/docs/adr/0105-show-the-approvals-window-when-a-turn-starts-waiting.md +++ b/docs/adr/0105-show-the-approvals-window-when-a-turn-starts-waiting.md @@ -150,8 +150,11 @@ denies, and **Approve** is armed only one second after a review renders. the shown window lands in the stacking order, while another application owns the foreground were not checked on a Windows desktop. - `omgcode-desktop` now depends on the workspace crate `omgcode-platform`. - `omgcode-platform` gains two Windows-only functions with four `unsafe` - calls; no third-party code is added. + `omgcode-platform` gains `foreground::this_process_owns_foreground`, on + every platform, which answers only on Windows and returns `None` + elsewhere, and the Windows-only + `foreground::activate_if_foreground_owner`. Their Windows code makes four + `unsafe` calls; no third-party code is added. - Every time the operator switches to the approvals window it makes one extra `approvals_list` call, which reads the approval store as each poll does.