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
1 change: 0 additions & 1 deletion QUEUE.md
Original file line number Diff line number Diff line change
Expand Up @@ -2319,7 +2319,6 @@ and the Linux headless CPU renderer without claiming display frame timing.

- Changing an in-flight upload's finite `with` context makes a worker source's reply miss its original argument key (`data/src/placed.rs`, `parse_with`); the main-thread source takes the new context.

- The web JS auth hold outlives a superseded mutation when its replacement does not call `openAuthSession` (`host/web-js/auth.js`). Replacing a sign-in mutation with a synchronous cancellation leaves its auth ticket in `state.pending`; a late callback can resume the old source and write its session. A browser regression test reproduced both effects. The supersession cleanup runs only when another auth session opens. Match the runner's let-go behavior.
- `SheetSurfaceMacTests.testAuthoredGroundMatchesAnAppKitSheetInDarkMode` should report an unavailable window-server reference capture before reading its pixel colour. On a locked or asleep display it fails at `SheetSurfaceMacTests.swift:20` with no NSColor.
- A `target/` with hundreds of thousands of files in `debug/deps` makes socket tests time out on a test binary's first run on a Mac. Seen 2026-11-14 with two worktrees at about 700 GB and 600,000 to 760,000 files each: after a relink, twelve `launch_preloads` tests of `exact-apple` failed at their 10 s wait and every later run of the same binary passed; with `target/` deleted and rebuilt the suite passed first time in under 2 s, against 13 to 20 s. Which step is slow in a large `deps` is not known. Until it is, delete a worktree's `target/` when it passes a few hundred gigabytes.

Expand Down
497 changes: 497 additions & 0 deletions host/web-js/auth-let-go.test.mjs

Large diffs are not rendered by default.

193 changes: 135 additions & 58 deletions host/web-js/auth.js

Large diffs are not rendered by default.

154 changes: 153 additions & 1 deletion host/web-js/auth.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ let currentOrigin = "app";
const personRequired = [];
const Origin = { now: () => currentOrigin, personRequired: id => personRequired.push(id) };
const Invocation = { id: 0 };
mock.module("./rt.js", () => ({ clock, journal, nextTicket: () => ++ticket, Origin, Invocation }));
const LetGo = [];
mock.module("./rt.js", () => ({ clock, journal, nextTicket: () => ++ticket, Origin, Invocation, LetGo }));
const realAuthGlue = await import("../web/auth-glue.js?web-js-auth-test");
let glueImported = false;
mock.module("./auth-glue.js", () => {
Expand Down Expand Up @@ -404,3 +405,154 @@ test("non-app origins are refused 403 without holding or opening, and tool calls
active = null;
}
});

test("letting go of a browser auth session closes its popup and clears timers immediately", async () => {
const names = ['window', 'navigator', 'location', 'performance', 'BroadcastChannel',
'requestAnimationFrame', 'addEventListener', 'removeEventListener', 'setTimeout',
'clearTimeout', 'setInterval', 'clearInterval', 'exact'];
const saved = names.map(name => [name, Object.getOwnPropertyDescriptor(globalThis, name)]);
const timers = [], popups = [];
let timerNumber = 0, listener = null, channel = null, target = 'first', active = null;
const timer = (callback, delay, repeat) => {
const value = { id: ++timerNumber, callback, delay: Number(delay), repeat, active: true };
timers.push(value);
return value;
};
const clear = value => { if (value) value.active = false; };
const define = (name, value) => Object.defineProperty(globalThis, name, { configurable: true, writable: true, value });
define('setTimeout', (callback, delay = 0) => timer(callback, delay, false));
define('clearTimeout', clear);
define('setInterval', (callback, delay = 0) => timer(callback, delay, true));
define('clearInterval', clear);
define('performance', { timeOrigin: 1000, now: () => 0 });
define('location', { origin: 'https://app.example', search: '' });
define('navigator', { userActivation: { isActive: true } });
define('BroadcastChannel', class { constructor() { channel = this; } close() { this.closed = true; } });
define('addEventListener', (type, value) => { if (type === 'message') listener = value; });
define('removeEventListener', (type, value) => { if (type === 'message' && listener === value) listener = null; });
define('requestAnimationFrame', callback => { callback(); return 1; });
define('exact', { authHost: realAuthGlue });
define('window', { open(url) {
const popup = { closed: false, location: { href: String(url) }, close() { this.closed = true; } };
popups.push(popup);
return popup;
} });
clock.agent = false;
try {
install('auth.session https://login.example.com\nauth.callback https://app.example/.exact/auth/callback\nauth.google client-id', () => target, () => active);
const loadTimer = timers.find(t => t.active && t.delay === 0);
if (loadTimer) { loadTimer.active = false; loadTimer.callback(); }
await import('./auth-glue.js');
await Promise.resolve();

const owner = { ticket: null };
let settled = false, recounted = 0, abandoned = 0;
const call = {
origin: 'app',
owner,
recount: () => { recounted++; },
abandon: () => { abandoned++; },
};
active = call;
const first = openAuthSession('https://login.example.com/authorize', { callback: authCallback(), state: 'first' });
first.then(() => { settled = true; }, () => { settled = true; });
const ticket = { id: 99, owner, waiting: true };
call.ticket = ticket;
owner.ticket = ticket;
const firstPopup = popups.at(-1);
expect(firstPopup.closed).toBe(false);
expect(timers.filter(t => t.active).length).toBeGreaterThan(0);

// Supersede the owning mutation without calling openAuthSession.
owner.ticket = null;
for (const f of LetGo) f();

expect(firstPopup.closed).toBe(true);
expect(channel.closed).toBe(true);
expect(listener).toBeNull();
expect(timers.filter(t => t.active)).toEqual([]);
expect(ticket.closed).toBe(true);
expect(ticket.waiting).toBe(false);
expect(recounted).toBe(1);
expect(abandoned).toBe(1);

// Late opener or BroadcastChannel delivery cannot resume the old session.
channel.onmessage?.({ data: { type: 'exact-auth', url: `${authCallback()}?code=late&state=first` } });
await Promise.resolve();
expect(settled).toBe(false);

// Another target can open without hitting a stale 409.
target = 'second';
active = null;
const callback = `${authCallback()}?code=ok&state=second`;
const second = openAuthSession('https://login.example.com/authorize', { callback: authCallback(), state: 'second' });
listener({ origin: location.origin, source: popups.at(-1), data: { type: 'exact-auth', url: callback } });
expect(await second).toBe(callback);

// Package sign-in cancellation (`exact.authSession.open`) also closes its popup immediately.
let cancelPkg = null;
const pkg = globalThis.exact.authSession.open({
url: 'https://accounts.google.com/o/oauth2/v2/auth?client_id=client-id',
callback: authCallback(),
state: 'pkg',
cancelled: fn => { cancelPkg = fn; },
});
const pkgPopup = popups.at(-1);
expect(pkgPopup.closed).toBe(false);
cancelPkg();
expect(pkgPopup.closed).toBe(true);
expect(timers.filter(t => t.active)).toEqual([]);
await expect(pkg).rejects.toMatchObject({ status: 499 });
} finally {
clock.agent = true;
for (const [name, descriptor] of saved) {
if (descriptor) Object.defineProperty(globalThis, name, descriptor);
else delete globalThis[name];
}
}
});

test("an unadopted prepared window closes when its auth hold is let go or started after let-go", async () => {
const priorWindow = globalThis.window;
const priorNavigator = globalThis.navigator;
const priorLocation = globalThis.location;
const priorExact = globalThis.exact;
const popups = [];
clock.agent = true;
globalThis.window = { open: () => { const p = { closed: false, close() { this.closed = true; } }; popups.push(p); return p; } };
globalThis.navigator = { userActivation: { isActive: true } };
globalThis.location = new URL('https://app.example/');
globalThis.exact = {};
let active = null;
try {
install('auth.session https://login.example.com\nauth.callback https://app.example/.exact/auth/callback', () => 'logout', () => active);

// Hold with a prepared window, then let go of its owner.
const owner = { ticket: null };
active = { origin: 'app', owner };
const prepared1 = prepareAuthSession();
void openAuthSession('https://login.example.com/logout', { callback: authCallback(), state: 's1', logout: true, prepared: prepared1 });
const t1 = { id: 1, owner, waiting: true };
active.ticket = t1;
owner.ticket = t1;
expect(holds()).toHaveLength(1);
expect(popups[0].closed).toBe(false);

owner.ticket = null;
for (const f of LetGo) f();
expect(holds()).toEqual([]);
expect(popups[0].closed).toBe(true);

// Already-let-go call invoking openAuthSession with a prepared window closes it immediately.
const prepared2 = prepareAuthSession();
expect(popups[1].closed).toBe(false);
void openAuthSession('https://login.example.com/logout', { callback: authCallback(), state: 's2', logout: true, prepared: prepared2 });
expect(holds()).toEqual([]);
expect(popups[1].closed).toBe(true);
} finally {
globalThis.window = priorWindow;
globalThis.navigator = priorNavigator;
globalThis.location = priorLocation;
globalThis.exact = priorExact;
}
});
2 changes: 1 addition & 1 deletion host/web-js/build.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -844,7 +844,7 @@ if (ts) writeFileSync(resolve(gen, 'ts-data.js'), localImports((seamLazy ? "impo
.replace(storageFlag, production && !storageGrants ? 'const STORAGE_GRANTED = false;' : storageFlag)
.replace('const appId = source.appId;', `const appId = ${JSON.stringify((await import('../../scripts/app.mjs')).readManifest(appDir, app).app.id)};`)
.replace('__AUTH_IMPORT__', auth ? "import { install as signIn } from './auth.js';" : '')
.replace('__AUTH_INSTALL__', auth ? `signIn(${JSON.stringify(grants)}, () => asking, () => activeCall());` : '')
.replace('__AUTH_INSTALL__', auth ? `signIn(${JSON.stringify(grants)}, () => asking || authCall()?.name || '', authCall);` : '')
.replace("'__FETCH_MODULE__'", JSON.stringify(fetchRefused ? './ts-fetch-refused.js' : './ts-fetch.js'))));
writeFileSync(resolve(gen, 'grant-admission.js'), admitsNothing ? emptyGrantAdmission() : await bundleHostModule(root, 'grant-admission.js', { production }));
// With nothing admitted no request leaves the page's origin, so the driver's faults (LLP 1103), which fail a request
Expand Down
10 changes: 8 additions & 2 deletions host/web-js/rt.js
Original file line number Diff line number Diff line change
Expand Up @@ -714,6 +714,7 @@ export function commit(f, what = 'commit', finished, presenceSnap = false) {
safe(() => Output?.done(cmds));
for (const go of out.splice(sent)) safe(() => go.refused?.(why));
for (const follow of out.followUps ?? []) safe(() => follow.refused());
for (const f of LetGo) safe(f);
if (threw) throw firstErr;
};
const link = Nav?.holdLink();
Expand Down Expand Up @@ -774,12 +775,16 @@ export function commit(f, what = 'commit', finished, presenceSnap = false) {
Sched?.forget();
return false;
}
if (!ok) return (Sched?.scan(false), false);
if (!ok) {
for (const f of LetGo) f();
return (Sched?.scan(false), false);
}
clock.epoch++;
Store.persist();
for (const r of Resources) retainedAnswer(r, say);
while (sent < out.length) out[sent++]();
if (Open.size) closeLetGo(inflight, say);
for (const f of LetGo) f();
for (const c of cmds) command(...c);
if (!Output?.settled(cmds)) {
Sounds.apply?.(cmds);
Expand Down Expand Up @@ -847,7 +852,8 @@ export function recommit(f, what, reader) {
export const Reporting = { now: null, watched: new Set(), own: new Set() };
export const After = [],
Before = [],
Clocked = [];
Clocked = [],
LetGo = [];
/** `-exact-fit` (LLP 1116.001 D1.4): fitted texts are scaled after each tree update (navigation.js `fitText`). */
export const fitTexts = () => installFits(After);
/** SF Symbol effects' stand-ins (LLP 1077 D12) play after each tree update (navigation.js `playSymbolEffects`). */
Expand Down
2 changes: 1 addition & 1 deletion host/web-js/rust-data.js
Original file line number Diff line number Diff line change
Expand Up @@ -335,7 +335,7 @@ export async function install(data, sources, load = p => fetchHostAsset(p).then(
// Beside app.ts, each source goes to the module its name gives (ts-data.js `install`): one the crate's RUST_SOURCES
// lists to Rust, even when Rust calls it unknown, as natively; every other to app.ts.
const owns = data.rustSources;
data.answer = ts ? (source, args, store, target, mutation, forced, owner) => owns.has(source) ? rust(source, args, store, target, mutation, forced, owner) : ts(source, args, store, target, mutation, forced) : rust;
data.answer = ts ? (source, args, store, target, mutation, forced, owner) => owns.has(source) ? rust(source, args, store, target, mutation, forced, owner) : ts(source, args, store, target, mutation, forced, owner) : rust;
// A stream's messages that arrived together (request-send.js): each parsed in order (LLP 1016.000 D4), the last
// one's answer theirs; one that answers with a request (the stream asked again) ends them there.
// A two-way socket's `open` or frame is its own mapper's turn (LLP 1016.003 D4): it may send on that socket.
Expand Down
11 changes: 6 additions & 5 deletions host/web-js/ts-data.js
Original file line number Diff line number Diff line change
Expand Up @@ -641,6 +641,7 @@ export function install(data, rustSources = null, modules = null) {
Object.defineProperty(e, 'status', { value: 501, enumerable: true });
return Promise.reject(e);
};
const authCall = () => answering.call ?? (answering.promiseCall?.name !== undefined ? answering.promiseCall : null) ?? activeCall();
__AUTH_INSTALL__
// A module's `kept(source, args, value)` is given the answers its page was
// rendered with, once, before it is first asked: they are its own answers,
Expand All @@ -659,22 +660,22 @@ export function install(data, rustSources = null, modules = null) {
}
}
};
const ts = (name, args, store, target, mutation = false, forced) => {
const ts = (name, args, store, target, mutation = false, forced, owner = null) => {
if (!seeded) seed();
const types = sourceTypes[name], [params, result] = types ?? [[], 'u'];
// The store as the module sees it (LLP 1018): a read marks the answer.
const seen = createSecretFacade(store, tsGrantSet, kept);
// A call that read the store and then threw read it too: its resource is a store reader (LLP 1146 §2.3).
threwRead = false; threwClock = false; threwWatches = null;
try { return answerWith(name, args, target, mutation, types, params, result, seen, forced); } catch (e) { threwRead = !!seen.read; throw e; }
try { return answerWith(name, args, target, mutation, types, params, result, seen, forced, owner); } catch (e) { threwRead = !!seen.read; throw e; }
};
const answerWith = (name, args, target, mutation, types, params, result, seen, forced) => {
const answerWith = (name, args, target, mutation, types, params, result, seen, forced, owner) => {
// A kept key's work is counted on its answer as an ordinary fetch is (LLP 1016.000 D9).
for (const name of ['key', 'keepKey', 'exclusive']) { const op = seen[name]; seen[name] = (...a) => ordinary(() => op(...a)); }
asking = target ?? name; watching = name;
for (const sources of moduleWatched.values()) sources.delete(name);
// The origin of the commit that asked it (LLP 1133.002 D12), which a fetch it makes carries (LLP 1133.036 D6).
const call = answering.call = { stream: null, mutation, forced, name: target ?? name, turn: true, input: mutation && rt.Origin.input === true, origin: rt.Origin.now(), invocation: rt.Invocation?.id ?? 0, watches: new Set() }, target_ = target ?? name;
const call = answering.call = { stream: null, mutation, forced, owner, name: target ?? name, turn: true, input: mutation && rt.Origin.input === true, origin: rt.Origin.now(), invocation: rt.Invocation?.id ?? 0, watches: new Set() }, target_ = target ?? name;
if (call.origin !== 'app') answering.untraced.add(call);
// What the source sent goes once the commit that asked it stands: an answer in flight's (a resource's, or a mutation's that
// answers with a promise) whatever it then answers, a refused commit saying so (LLP 1016.000 D7, amended 2026-10-18).
Expand Down Expand Up @@ -729,7 +730,7 @@ export function install(data, rustSources = null, modules = null) {
// routes them natively.
data.uploads = ledger; // the uploads a resource asks are asked once (LLP 1016.000 D10)
const rust = data.rustSources = rustSources && new Set(rustSources);
data.answer = rust ? (name, args, store, target, mutation, forced) => rust.has(name) ? null : ts(name, args, store, target, mutation, forced) : ts;
data.answer = rust ? (name, args, store, target, mutation, forced, owner) => rust.has(name) ? null : ts(name, args, store, target, mutation, forced, owner) : ts;
// An overlay (`overlay.js`): what a resource shows while writes affect it, in overlay mode; `undefined` without one,
// and for a Rust source, whose overlay is the Rust module's.
overlaying.say = line => rt.journal.push(`t=${rt.clock.now} ${line}`);
Expand Down
Loading
Loading