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
181 changes: 153 additions & 28 deletions products/maka/ios-shell/src/bridge.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@

use maka_remote_client::{
Attachments, DeviceIdentity, HostProfile, PairingNameError, PendingPairing, ReadResource,
RelayAuthorization, RemoteCallHandle, RemoteClientError, RemoteHostConnection, SavedHosts,
TlsTrust, validate_pairing_name,
RelayAuthorization, RemoteCallHandle, RemoteClientError, RemoteHostConnection,
RemoteSubscription, SavedHosts, TlsTrust, validate_pairing_name,
};
use nsh_engine::{HostCall, HostChannel, HostSender};
use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -1801,16 +1801,31 @@ impl Bridge {
async fn open_subscription(
&self,
data: Value,
caller: HostSender,
sender: HostSender,
) -> Result<(RootId, String, u64, oneshot::Sender<()>), String> {
let rpc = read_only_rpc(data)?;
let (root, active, calls) = self.calls(&rpc).await?;
let id = rpc.subscription_id.ok_or("missing subscription ID")?;
let mut subscription = calls
let subscription = calls
.subscribe(&rpc.endpoint, &rpc.method, rpc.input)
.await
.map_err(error)?;
self.register_subscription(root, active, id, sender, subscription)
.await
}

async fn register_subscription(
&self,
root: RootId,
active: u64,
id: String,
sender: HostSender,
mut subscription: RemoteSubscription,
) -> Result<(RootId, String, u64, oneshot::Sender<()>), String> {
let mut state = self.state.lock().await;
if sender.is_closed() {
return Err("app closed during subscription setup".into());
}
if state.current(&root, active).is_none() {
return Err("remote Host changed during subscription setup".into());
}
Expand All @@ -1820,41 +1835,41 @@ impl Bridge {
let key = id.clone();
let host_root = root.clone();
let task = self.runtime.spawn(async move {
let outcome = if wait.await.is_err() {
None
} else {
loop {
let next = tokio::select! {
biased;
_ = caller.closed() => break None,
next = subscription.next() => next,
};
match next {
Ok(Some(item)) => {
if !caller.send(
"ios.subscriptionItem",
json!({
"rootId": host_root, "subscriptionId": key, "generation": generation, "item": item,
}),
).expect("valid subscription event name") {
break None;
let outcome = tokio::select! {
biased;
_ = sender.closed() => None,
outcome = async {
wait.await.ok()?;
loop {
match subscription.next().await {
Ok(Some(item)) => {
if !sender.send(
"ios.subscriptionItem",
json!({
"rootId": host_root, "subscriptionId": key, "generation": generation, "item": item,
}),
).expect("valid subscription event name") {
return None;
}
}
Ok(None) => return Some(Ok(())),
Err(err) => return Some(Err(err)),
}
Ok(None) => break Some(None),
Err(err) => break Some(Some(err.to_string())),
}
}
} => outcome,
};
drop(subscription);
let mut state = bridge.state.lock().await;
if let Some(host) = state.connections.get_mut(&host_root)
&& host.subscriptions.get(&key).is_some_and(|(current, _)| *current == generation)
{
host.subscriptions.remove(&key);
if let Some(error) = outcome {
caller.send(
if let Some(outcome) = outcome {
sender.send(
"ios.subscriptionEnded",
json!({
"rootId": host_root, "subscriptionId": key, "generation": generation, "error": error,
"rootId": host_root, "subscriptionId": key, "generation": generation,
"error": outcome.err().map(error),
}),
).expect("valid subscription event name");
}
Expand Down Expand Up @@ -2902,6 +2917,116 @@ mod tests {
(call["method"].as_str().unwrap().to_owned(), ws)
}

async fn accept_subscription(
listener: &TcpListener,
session: Uuid,
) -> tokio_tungstenite::WebSocketStream<tokio::net::TcpStream> {
let (method, mut stream) = open_rpc(listener, session).await;
assert_eq!(method, "watch");
send_frame(&mut stream, json!({"kind":"subscribed"})).await;
stream
}

#[tokio::test]
async fn reloading_closes_live_subscriptions_and_rejects_late_registrations() {
let dir = tempfile::tempdir().unwrap();
let channel = HostChannel::new();
let host =
HostBridge::attach(channel.clone(), dir.path().into(), Handle::current()).unwrap();
let (events, mut received) = tokio::sync::mpsc::unbounded_channel();
channel.handle("test.event", move |mut call| {
events.send((call.sender(), call.take_data())).unwrap();
});
let bundle = nsh_engine::Bundle::source(
r#"
import { host } from 'nsh';
host.on('ios.subscriptionItem', event => host.post('test.event', {item: event.item}));
host.on('ios.subscriptionEnded', event => host.post('test.event', {ended: event}));
host.on('test.subscribe', async data => {
const handle = await host.call('ios.subscribe', data, {timeout: 0});
host.post('test.event', {handle});
});
host.on('test.unsubscribe', async handle => {
const reply = await host.call('ios.unsubscribe', handle);
host.post('test.event', reply);
});
host.post('test.event', 'ready');
"#
.to_owned(),
)
.with_capabilities_json(Some(r#"{"host":true}"#))
.unwrap();
let mut config = nsh_engine::EngineConfig::new(bundle);
config.host = channel.clone();
let bridge = &host.bridge;
let _original = nsh_testing::Headless::start(config.clone()).unwrap();
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
tokio::time::timeout(Duration::from_secs(5), async {
let (active, session, _anchor) = progress_host(bridge, &listener, "root").await;
let (old_caller, ready) = received.recv().await.unwrap();
assert_eq!(ready, "ready");
let id = "stream";
let input = json!({
"rootId":"root", "generation":active, "endpoint":"agent",
"method":"watch", "subscriptionId":id, "input":{},
});
let accept = || accept_subscription(&listener, session);
channel.send("test.subscribe", input.clone()).unwrap();
let mut old_stream = accept().await;
let (_, reply) = received.recv().await.unwrap();
let old_handle = &reply["handle"];
assert_eq!(old_handle["subscriptionId"], id);
assert_eq!(read_frame(&mut old_stream).await["kind"], "pull");
send_frame(&mut old_stream, json!({"kind":"item","value":"old app"})).await;
assert_eq!(received.recv().await.unwrap().1, json!({"item":"old app"}));
assert_eq!(read_frame(&mut old_stream).await["kind"], "pull");

let (_, _, calls) = bridge
.calls(&read_only_rpc(input.clone()).unwrap())
.await
.unwrap();
// Park a second old call after its handshake, before registration.
let (late_subscription, mut late_stream) =
tokio::join!(calls.subscribe("agent", "watch", json!({})), accept());
let late_subscription = late_subscription.unwrap();

// Keep the original engine alive: taking over its channel must
// wake the idle stream without waiting for the next remote item.
let _replacement = nsh_testing::Headless::start(config).unwrap();
assert_eq!(received.recv().await.unwrap().1, "ready");
// On this single-thread runtime, the task closes the stream and
// unregisters it before the server can observe the disconnect.
assert!(matches!(old_stream.next().await, None | Some(Err(_))));
channel
.send("test.unsubscribe", old_handle.clone())
.unwrap();
assert_eq!(received.recv().await.unwrap().1, json!({"cancelled":false}));

channel.send("test.subscribe", input).unwrap();
let mut new_stream = accept().await;
assert_eq!(
received.recv().await.unwrap().1["handle"]["subscriptionId"],
id
);
assert_eq!(read_frame(&mut new_stream).await["kind"], "pull");
let late = bridge
.register_subscription(
"root".into(),
active,
id.into(),
old_caller,
late_subscription,
)
.await;
assert_eq!(late.unwrap_err(), "app closed during subscription setup");
assert!(matches!(late_stream.next().await, None | Some(Err(_))));
send_frame(&mut new_stream, json!({"kind":"item","value":"new app"})).await;
assert_eq!(received.recv().await.unwrap().1, json!({"item":"new app"}));
})
.await
.expect("reloading must close the old stream without disturbing the replacement");
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn receipts_are_read_for_both_early_and_late_registrations() {
let dir = tempfile::tempdir().unwrap();
Expand Down
64 changes: 61 additions & 3 deletions scripts/ci.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -443,15 +443,58 @@ test('native pixel and desktop regressions run only on their native OS workers',
assert.equal(plan.suites.gpui, undefined);
});

test('NSH shader, GPU and AppKit changes reach the macOS rendering suite', () => {
const packages = ['nsh-gpu', 'nsh-engine', 'nsh-platform-macos'].map((name) => ({
name,
id: name,
source: null,
manifest_path: join(root, 'third-party/nsh/crates', name, 'Cargo.toml'),
}));
const metadata = {
root: { packages: [], workspace_members: [], resolve: { nodes: [] } },
nsh: {
packages,
workspace_members: packages.map(({ id }) => id),
resolve: {
nodes: packages.map(({ id }, i) => ({
id,
deps: i === 0 ? [] : [{ pkg: packages[i - 1].id }],
})),
},
},
};
for (const [pkg, file] of [
['nsh-gpu', 'src/lib.rs'],
['nsh-engine', 'src/shader.rs'],
['nsh-platform-macos', 'tests/native/shader_content.rs'],
]) {
const plan = createPlan({
root,
changes: [`third-party/nsh/crates/${pkg}/${file}`],
metadata,
revision: 'head',
baseline: 'base',
});
assert.equal(plan.full, false);
const worker = plan.workers.find(({ id }) => id === 'macos-nsh');
assert.ok(worker?.suites.includes('macos-nsh'), pkg);
assert.match(worker.runner, /^macos-/);
assert.match(plan.suites['macos-nsh'].reason, /nsh-platform-macos/);
}
});

test('non-archived native regressions fail empty selections and GTK runs under Xvfb', async () => {
const calls = [];
const appKitModes = [];
const nativeTarget = join(root, 'native-nsh-target');
const exec = executor(
root,
{},
{
run: async (exe, args) => {
run: async (exe, args, { env }) => {
calls.push({ exe, args });
if (args.includes('native') && args.includes('--ignored'))
appKitModes.push([env.NSH_MENU_LABELS_CHECK_ONLY, env.NSH_SHADER_CONTENT_CHECK_ONLY]);
return args[0] === 'metadata' ? JSON.stringify({ target_directory: nativeTarget }) : '';
},
},
Expand All @@ -471,7 +514,18 @@ test('non-archived native regressions fail empty selections and GTK runs under X
}
assert(calls.some(({ args }) => args.includes('native-pixels')));
assert(calls.some(({ args }) => args.includes('terminal_native') && !args.includes('--lib')));
assert(calls.some(({ args }) => args.includes('native') && args.includes('--ignored')));
assert.deepEqual(appKitModes, [
['1', undefined],
[undefined, 'resize'],
]);
const macUnits = calls.find(
({ args }) => args.includes('nextest') && args.includes('nsh-platform-macos'),
);
assert.ok(macUnits.args.includes('nsh-engine'));
assert.ok(macUnits.args.includes('--lib'));
assert.ok(
macUnits.args[macUnits.args.indexOf('--features') + 1].split(',').includes('nsh-engine/shader'),
);
assert(
calls.some(({ args }) => args.includes('crates/nsh-platform-macos/tests/host/Undo.test.tsx')),
);
Expand Down Expand Up @@ -529,7 +583,11 @@ test('non-archived native regressions fail empty selections and GTK runs under X
const nativeCheck = macCalls.find(({ args }) => args[0] === 'check');
assert.equal(nativeCheck.exe, 'cargo');
assert(nativeCheck.args.includes('--all-targets'));
assert(nativeCheck.args.includes('nsh-platform-macos/terminal'));
assert.ok(
nativeCheck.args[nativeCheck.args.indexOf('--features') + 1]
.split(',')
.includes('nsh-platform-macos/terminal'),
);
assert(!nativeCheck.args.includes('--lib'));
const hostBuild = macCalls.find(({ args }) => args[0] === 'build');
assert.equal(hostBuild.exe, 'cargo');
Expand Down
13 changes: 10 additions & 3 deletions scripts/ci/run.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -628,10 +628,10 @@ export function executor(
await run(join(target, 'ci/maka-bridge'), ['--version']);
await nextest(id);
} else if (id === 'macos-nsh') {
await runSuites(['unit', 'menu', 'undo'], async (stage) => {
await runSuites(['unit', 'menu', 'shader-resize', 'undo'], async (stage) => {
if (stage === 'unit')
await nextest(id, false, filter, ['--no-tests=fail', '-j', '1', ...extra]);
else if (stage === 'menu')
else if (stage === 'menu' || stage === 'shader-resize')
await cargo(
[
'test',
Expand All @@ -647,7 +647,14 @@ export function executor(
'--',
'--ignored',
],
{ env: { ...suiteEnv(id), NSH_MENU_LABELS_CHECK_ONLY: '1' } },
{
env: {
...suiteEnv(id),
...(stage === 'menu'
? { NSH_MENU_LABELS_CHECK_ONLY: '1' }
: { NSH_SHADER_CONTENT_CHECK_ONLY: 'resize' }),
},
},
);
else {
const metadata = JSON.parse(
Expand Down
6 changes: 4 additions & 2 deletions scripts/ci/suites.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -309,17 +309,19 @@ export const suites = {
},
'macos-nsh': {
workspace: 'nsh',
packages: ['nsh-platform-apple', 'nsh-platform-macos', 'nsh-cli'],
packages: ['nsh-engine', 'nsh-platform-apple', 'nsh-platform-macos', 'nsh-cli'],
cargoArgs: [
'--locked',
'--manifest-path',
manifests.nsh,
'-p',
'nsh-engine',
'-p',
'nsh-platform-apple',
'-p',
'nsh-platform-macos',
'--features',
'nsh-platform-macos/terminal',
'nsh-engine/shader,nsh-platform-macos/terminal',
'--lib',
],
},
Expand Down
5 changes: 5 additions & 0 deletions third-party/nsh/SOURCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,11 @@ terminal surfaces. Desktop window operations take explicit `WindowRef` values.
surface copies share the submission queue with surface and readback draws.
Apple and Windows surface pools keep frames that finish during collection
when they are newer than the selected frame.
`ShaderView::set_size` synchronously retires displayed/in-flight frames and
active transitions on zero-area collapse, keeps collapsed and idle
transitions off the frame clock, and platform layout hooks clear displayed
surfaces and child masks immediately (including UIKit and desktop root
resizes for screen shaders).
- **iOS keyboard geometry:** `nsh-platform-ios` ignores floating or undocked
keyboard frames that leave the bottom edge clear when the docked guide covers
only the safe area. Animated updates start from the notification's end
Expand Down
Loading