Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/webui-ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,9 @@ jobs:
with:
node-version: "24"
cache: pnpm
- name: Verify the public source inventory on the clean checkout
if: runner.os == 'Linux' && matrix.lane.name == 'checks'
run: pnpm check:source
- run: pnpm install --frozen-lockfile
- name: Check WebUI types
if: matrix.lane.name == 'checks'
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ dist-webui-npm/
!.env.example
.DS_Store
.idea/
.openidea/
.codegraph/
dist-*.zip
dist-store-*/
Expand Down
12 changes: 6 additions & 6 deletions packages/webui/docs/client/composer.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ the notice shows a transfer error beside its action so the user can select anoth
## Workspace folder selection

On the home page, `选择新项目` opens the system folder chooser in the browser
paired by an interactive local `mcode-webui` launch. Windows opens the native
on the computer running `mcode-webui`. Windows opens the native
`IFileOpenDialog` from a short-lived koffi worker, which also brings the dialog
to the foreground when the server was started in the background; macOS uses its
system dialog. On a Linux desktop the launcher uses Zenity or KDialog. Zenity opens
Expand All @@ -48,14 +48,14 @@ Cancelling returns to the home page with the previous selection.

The tab opened by the launcher exchanges its temporary grant for a browser key
and a separate HttpOnly session cookie. Reloaded pages and other tabs on the
same origin use that pairing. After a restart, the launcher tab renews it for
the browser. A remote or unpaired browser can select a recent project or
`不需要项目`. Requesting a new folder without a native chooser displays a notice.
same origin use that pairing. A manually opened local page can establish a
pairing through a temporary loopback listener. Remote pages can select a recent
project or `不需要项目`. Requesting a new folder without a native chooser displays a notice.

A local desktop host that embeds the page can receive the same grant URL through
`WEBUI_LAUNCH_URL_FILE` when it starts `mcode-webui` with `WEBUI_DESKTOP_HOST=1`.
The file is owner-only and the grant remains one-time; the route's loopback,
Host, Origin, cookie, grant and browserKey checks are unchanged. `WEBUI_OPEN_BROWSER`
The file is owner-only. The route checks loopback, Host, Origin, credentials and
browser pairing. `WEBUI_OPEN_BROWSER`
still controls only the system browser.

## Where the pieces live
Expand Down
5 changes: 5 additions & 0 deletions packages/webui/docs/client/ownership.md
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,11 @@ execution. Stop acknowledgements are fenced by the generation captured at invoca
acknowledgement cannot settle a newer turn. Execution activity, delivery completion and persistence
confirmation remain separate facts.

The sessions owner refreshes the rail's project records on a committed `session.created`
event, including sessions created by `/new` or another client. Multiple creations during a
pending read trigger one fresh lookup after it settles. Sending the first message can proceed
while that lookup is pending.

The selected session's metadata is read from the catalogue entity map, independently of the flat
and tree pages' membership. Selection acquires missing metadata through the existing `getSession`
operation; concurrent same-identity reads coalesce, and navigation does not redirect their result.
Expand Down
3 changes: 2 additions & 1 deletion packages/webui/docs/verification/gates.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ document: [`browser-suite.md`](browser-suite.md).

| Gate | Proves | Fails on |
| --- | --- | --- |
| `pnpm check:source` | The clean checkout matches the published source inventory. WebUI CI runs this in its Linux checks job before installing dependencies. | Missing declared files, undeclared source files or source integrity violations |
| `pnpm typecheck:webui` | Every source file and every test file compiles under `strict`: the server/runtime/shared config, the client config, and one test program whose `include` is the whole `test/` and `src/` tree | A port member without its stub, a missing binding, a wrong DTO, a test fixture that no longer matches the signature it calls |
| `pnpm check:webui-dependency` | Import direction and role ownership over the resolved source graph, including `import type` edges | A forbidden direction, a role violation, a business holding one role in two homes, a private cross-business import, or an unclassified source |
| `pnpm check:webui-presentation` | Every client UI source module (`features/*/ui/`, `shell/`, the shared `ui/`) is classified in `scripts/lib/webui-presentation-inventory.json`, and the inventory agrees with the modules on disk | An unclassified module, an entry whose module is gone, an undefined disposition, kind or family, a business exception without a reason, a module classified as newly-adopted-contract that renders or calls nothing from the shared home |
Expand All @@ -18,7 +19,7 @@ document: [`browser-suite.md`](browser-suite.md).
| `pnpm check:webui-motion` | Every duration and every `@keyframes` in the client's stylesheets is inventoried per file in `docs/design/motion-inventory.json` against a named family (feedback, surface, disclosure, loading) or recorded as a distinct effect with its reason; and, in source, that motion belongs to a shared component — shared `ui/` components opt into the feedback family, and feature code owns no timing, rotation, interaction transform, smooth scroll or raw motion utility. The approved feature exceptions are `features/account/ui/account.css`, `features/transcript/ui/transcript.css`, the sign-in success effect, the transcript message entrance and turn-jump highlight, and the rose-loader Lottie asset | A new raw duration or keyframe, a recorded entry that has gone, a value that claims a family but is not that family's token, a distinct effect with no reason, a feature stylesheet declaring motion without an approved exception, a raw motion utility or inline motion style in a component, a hand-rolled `role="button"`, `data-webui-motion` outside the shared components, a native `<details>`, inline SVG animation, an animation-engine import outside `ui/feedback.tsx`, a `WebuiDialog` without an explicit `open` state, or a shared control that forgets to opt into the feedback family |
| `pnpm build:webui` | The client and server bundles build, and prints input counts | A module that is written but not wired (counts do not move) |
| `pnpm check:webui-boundary` | The combined client/server build graph contains required entries and inputs within declared package roots; direct WebUI workspace imports use exported subpaths; the artifact integrity record matches current inputs and outputs | A retired source path, the terminal renderer, a private direct workspace import, a forbidden internal reference, or a stale/modified build artifact |
| `pnpm test:webui-package` | Installs the candidate, verifies startup and the browser bridge, and on Windows selects a project from the launcher's home page | Packaging drift, native folder selection failure, a session using the wrong directory |
| `pnpm test:webui-package` | Installs the candidate and checks startup and the browser bridge. On Windows, tests the automatically opened page, the manually opened launcher URL and the desktop host's handoff URL in separate browser profiles. From each home page it selects and cancels a foreground system dialog, then finds the new session under its chosen project both before and after reloading. | A broken entry, a background-only dialog, a dropped selection, a stale project list or a session that fails to persist |
| `pnpm test:webui` | The registered WebUI Vitest group (unit, integration and verification-gate tests) | Behaviour change, unregistered new test file |
| `pnpm test:webui-browser` | Every Playwright spec collected under `packages/webui/test/browser/`: the built client and deterministic in-page transport, plus explicit real-browser bridge and production-host/native-PTY harnesses. The screenshot comparisons run against the font files committed under `packages/webui/test/browser/fonts/`, so their result does not depend on the fonts the machine has installed | Behaviour change in the built bundle, a real bridge path, or native lifecycle |
| `pnpm check:source` | `release/public-source.json` lists exactly the delivered files | A new, moved or deleted file without inventory regeneration |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,15 +45,12 @@ export interface WebuiTaskSessionStorage {
/**
* The catalogue reads creation completion invalidates. Injected because
* `client/application/` composes owners rather than calling transport itself.
* The project list is one of those reads: a session created in a new directory
* adds a project row the rail only sees after this read.
*/
export interface WebuiTaskSessionCatalogue {
readonly canLoadFlat: boolean;
readonly canLoadTree: boolean;
readonly loadFlat: () => Promise<void>;
readonly loadTree: () => Promise<void>;
readonly loadProjects?: () => Promise<unknown>;
}

export interface WebuiTaskSessionDeps {
Expand Down Expand Up @@ -295,12 +292,6 @@ export function createWebuiTaskSessionWorkflows(
// the created session and does not trigger a second creation.
catalogueError = formatWebuiError(error);
}
// A session created in a new directory adds a project row. The session
// catalogue above does not carry project records, so the rail would keep
// its pre-creation grouping until a full page reload without this read.
// The projects owner keeps its own error state; a failure here must not
// turn a successful creation into a failed one.
try { await catalogue.loadProjects?.(); } catch { /* Projects owns the rail's retry/error surface. */ }

return {
kind: "created",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -409,12 +409,32 @@ export function createWebuiSessionWorkflows(deps: {
let archived: WebuiArchivedSessionsState = initialWebuiArchivedSessionsState;
let projects: WebuiProjectsState = { loading: false };
let projectRequestVersion = 0;
let projectsInvalidated = false;
let disposed = false;
const projectListeners = new Set<() => void>();
const setProjects = (next: WebuiProjectsState): void => {
projects = next;
for (const listener of [...projectListeners]) listener();
};
async function loadProjects(): Promise<readonly WebuiClientProject[]> {
if (!port.loadProjects || disposed) return projects.projects ?? [];
const version = ++projectRequestVersion;
projectsInvalidated = false;
setProjects({ ...projects, loading: true, error: undefined });
try {
const result = await port.loadProjects();
if (!disposed && version === projectRequestVersion && !projectsInvalidated)
setProjects({ loading: false, projects: result });
return result;
} catch (error) {
if (!disposed && version === projectRequestVersion && !projectsInvalidated)
setProjects({ ...projects, loading: false, error: message(error) });
throw error;
} finally {
if (!disposed && version === projectRequestVersion && projectsInvalidated)
void loadProjects().catch(() => undefined);
}
}
const archivedListeners = new Set<() => void>();
const setArchived = (next: WebuiArchivedSessionsState): void => {
archived = next;
Expand Down Expand Up @@ -766,6 +786,10 @@ export function createWebuiSessionWorkflows(deps: {
if (disposed || removedSessionIds.has(fact.sessionId)) return;
retireCatalogReads();
if (fact.kind === "created") {
// Creating from another client or /new changes the same rail as a home
// submission. A read started before the commit needs one trailing read.
if (projects.loading) projectsInvalidated = true;
else void loadProjects().catch(() => undefined);
// A creation normally names an entity this client has never read.
// Repair through the authoritative query before applying known-only patches.
if (flatPending === undefined) void loadFlat();
Expand Down Expand Up @@ -946,27 +970,7 @@ export function createWebuiSessionWorkflows(deps: {
projectListeners.add(listener);
return () => projectListeners.delete(listener);
},
loadProjects: async () => {
if (!port.loadProjects) return [];
if (disposed) return projects.projects ?? [];
const version = ++projectRequestVersion;
setProjects({ ...projects, loading: true, error: undefined });
try {
const result = await port.loadProjects();
if (disposed || version !== projectRequestVersion) return result;
setProjects({ loading: false, projects: result });
return result;
} catch (error) {
if (!disposed && version === projectRequestVersion) {
setProjects({ loading: false, ...(projects.projects ? { projects: projects.projects } : {}), error: message(error) });
}
throw error;
} finally {
if (!disposed && version === projectRequestVersion && projects.loading) {
setProjects({ ...projects, loading: false });
}
}
},
loadProjects,
retainedDeletionDrafts: () => retainedSnapshot,
subscribeRetainedDrafts: (listener) => {
retainedListeners.add(listener);
Expand Down
48 changes: 42 additions & 6 deletions packages/webui/src/client/platform/native-directory-picker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,10 @@ function localTarget() {
target?.origin === url.origin && target.token) return target;
}

async function pairBrowser(origin: string, token: string, grant: string): Promise<string | undefined> {
async function pairBrowser(origin: string, token: string, headers: Record<string, string>, signal?: AbortSignal): Promise<string | undefined> {
const response = await globalThis.fetch(`${origin}/native-directory-picker/authorize`, {
method: "POST", mode: "same-origin", credentials: "same-origin", redirect: "error",
headers: { "X-Webui-Native-Grant": grant, "X-Webui-Token": token },
headers: { ...headers, "X-Webui-Token": token }, ...(signal ? { signal } : {}),
});
if (!response.ok) return;
const result: unknown = await response.json();
Expand All @@ -33,6 +33,34 @@ async function pairBrowser(origin: string, token: string, grant: string): Promis
return result.browserKey;
}

async function pairLocalBrowser(origin: string, token: string, signal: AbortSignal): Promise<string | undefined> {
// A forwarded WebUI can return the host's port number, but the new address
// resolves on the browser's own computer. Never send a credential to it.
try {
const challenge = await fetch(`${origin}/native-directory-picker/authorize`, {
method: "POST", mode: "same-origin", credentials: "same-origin", redirect: "error", signal,
headers: { "X-Webui-Native-Local": "1", "X-Webui-Token": token },
});
if (!challenge.ok) return;
const { localOrigin } = await challenge.json();
if (typeof localOrigin !== "string") return;
const url = new URL(localOrigin);
if (url.origin !== localOrigin || url.protocol !== "http:" || url.hostname !== new URL(origin).hostname ||
url.origin === origin || !url.port) return;
const receipt = await fetch(localOrigin + "/", {
method: "POST", mode: "cors", credentials: "omit", referrerPolicy: "no-referrer", redirect: "error",
signal: AbortSignal.any([signal, AbortSignal.timeout(5_000)]),
});
if (!receipt.ok) return;
const { proof } = await receipt.json();
if (typeof proof !== "string" || !uuid.test(proof)) return;
return await pairBrowser(origin, token, { "X-Webui-Native-Local": "1", "X-Webui-Native-Proof": proof }, signal);
} catch (error) {
if (signal.aborted) throw error;
return;
}
}

export function captureNativeDirectoryLaunchGrant(): void {
launchPairing = undefined;
const url = new URL(globalThis.location.href);
Expand All @@ -45,7 +73,7 @@ export function captureNativeDirectoryLaunchGrant(): void {
globalThis.history.replaceState(globalThis.history.state, "", url.href);
const target = localTarget();
if (target && uuid.test(grant)) {
launchPairing = pairBrowser(target.origin, target.token, grant).catch(() => undefined);
launchPairing = pairBrowser(target.origin, target.token, { "X-Webui-Native-Grant": grant }).catch(() => undefined);
}
}
export async function pickNativeWorkspaceDirectory(signal: AbortSignal): Promise<NativeWorkspaceDirectoryResult> {
Expand All @@ -55,11 +83,19 @@ export async function pickNativeWorkspaceDirectory(signal: AbortSignal): Promise
// A later launch may have paired another tab since this page loaded.
try { browserKey = getWebuiBrowserStorage()?.getItem(pairingKey) ?? browserKey; }
catch { /* Use this tab's key when browser storage cannot be read. */ }
if (!browserKey || !uuid.test(browserKey)) return { kind: "unavailable" };
const response = await globalThis.fetch(`${target.origin}/native-directory-picker`, {
const choose = (key: string) => globalThis.fetch(`${target.origin}/native-directory-picker`, {
method: "POST", mode: "same-origin", credentials: "same-origin", redirect: "error", signal,
headers: { "X-Webui-Native-Browser": browserKey, "X-Webui-Token": target.token },
headers: { "X-Webui-Native-Browser": key, "X-Webui-Token": target.token },
});
let response = browserKey && uuid.test(browserKey) ? await choose(browserKey) : undefined;
// A stale key from the previous server process is refused before the
// provider is invoked. Re-pair once; never repeat a submitted selection.
if (!response || (response.status === 403 && !launchPairing)) {
browserKey = await pairLocalBrowser(target.origin, target.token, signal);
if (!browserKey) return { kind: "unavailable" };
launchPairing = Promise.resolve(browserKey);
response = await choose(browserKey);
}
if ([401, 403, 404].includes(response.status)) return { kind: "unavailable" };
if (!response.ok) throw new Error(response.status === 409 ? "已有系统目录选择窗口,请先完成或取消。" : "系统目录选择失败,请重试。");
const result: unknown = await response.json();
Expand Down
Loading
Loading