{
diff --git a/src/client/channel/components/ChannelShareControl.tsx b/src/client/channel/components/ChannelShareControl.tsx
index eaaff1a60..02b6c2892 100644
--- a/src/client/channel/components/ChannelShareControl.tsx
+++ b/src/client/channel/components/ChannelShareControl.tsx
@@ -3,6 +3,7 @@ import { CaptureSourcePicker, type NativeSourceList } from "../../components/liv
import { Btn } from "../../components/living/primitives";
import { useAnchoredPopover } from "../../components/living/use-anchored-popover";
import { useCopy } from "../../ui/copy";
+import { activateNativePicker } from "../../native/activation";
import type { ChannelController } from "../types";
import "./channel-share-control.css";
@@ -21,6 +22,7 @@ export function ChannelShareControl({ channel, roomId, disabled }: {
const { appConnected, nativeSources, startNativeScreen, startScreen } = channel;
const browserSupported = typeof navigator !== "undefined" && typeof navigator.mediaDevices?.getDisplayMedia === "function";
const busy = channel.pending.has(`screen:${roomId}`);
+ const captureRequest = channel.nativeCaptureRequest(roomId);
const available = browserSupported || appConnected;
const label = lang === "zh" ? "分享屏幕" : "Share screen";
useAnchoredPopover(trigger, panel, { maxHeight: 560, minVisibleHeight: 240 });
@@ -47,11 +49,16 @@ export function ChannelShareControl({ channel, roomId, disabled }: {
};
return <>
-
+ activateNativePicker(captureRequest.activationURL)} />
+ { void channel.stopScreen(captureRequest.publicationId).catch(() => {}); }} />
+ > : { if (!appConnected) start(() => startScreen(roomId)); }} />
+ onClick={() => { if (!appConnected) start(() => startScreen(roomId)); }} />}
setOpen(event.newState === "open")}>
diff --git a/src/client/channel/components/channel-share-control.css b/src/client/channel/components/channel-share-control.css
index ca6d7bd8f..fedcbe72d 100644
--- a/src/client/channel/components/channel-share-control.css
+++ b/src/client/channel/components/channel-share-control.css
@@ -1,4 +1,4 @@
-.c3-share-control { display: inline-flex; }
+.c3-share-control { display: inline-flex; gap: 8px; }
.lr-anchored-card.c3-share-picker {
width: min(720px, calc(100vw - 16px));
height: min(560px, calc(100dvh - 16px));
diff --git a/src/client/channel/session.ts b/src/client/channel/session.ts
index ebf2e95a2..c32e35e03 100644
--- a/src/client/channel/session.ts
+++ b/src/client/channel/session.ts
@@ -673,18 +673,24 @@ export class ChannelSession {
await this.publish("screen", roomId, stream);
});
nativeSources = async (): Promise => (await this.connectApp()).sources();
+ nativeCaptureRequest = (roomId: string) => this.app?.captureRequest(roomId);
startNativeScreen = (roomId: string, target: NativeCaptureTarget, audio = false): Promise => this.action(`screen:${roomId}`, async () => {
const epoch = this.captureEpoch;
const app = await this.connectApp();
if (epoch !== this.captureEpoch) throw new Error("closed");
- const id = await app.startCapture(roomId, target, audio);
- if (epoch !== this.captureEpoch || this.app !== app) {
- await app.stopCapture(id);
- throw new Error("closed");
- }
+ const id = crypto.randomUUID();
+ const starting = app.startCapture(id, roomId, target, audio);
this.patch({});
- // Native owns the source; this page previews it through the ordinary route.
- await this.watch(id, roomId);
+ await starting;
+ this.patch({});
+ try {
+ if (epoch !== this.captureEpoch || this.app !== app) throw new Error("closed");
+ // Native owns the source; this page previews it through the ordinary route.
+ await this.watch(id, roomId);
+ } catch (error) {
+ await app.stopCapture(id).catch(() => {});
+ throw error;
+ }
});
stopScreen = (publicationId: string): Promise => this.action(`stop:${publicationId}`, async () => {
if (this.app?.screens.has(publicationId)) {
diff --git a/src/client/channel/types.ts b/src/client/channel/types.ts
index 8eb6138e5..700e29a22 100644
--- a/src/client/channel/types.ts
+++ b/src/client/channel/types.ts
@@ -1,7 +1,7 @@
import type { ChannelMessage, ChannelSnapshot, ChannelUser, RoomSettings } from "./protocol";
import type { ChannelAttachments, DraftFile } from "./attachments";
import type { NativeCaptureTarget } from "../native/wire";
-import type { NativeCaptureSources, ChannelRemoteControlState } from "./app-link";
+import type { NativeCaptureRequest, NativeCaptureSources, ChannelRemoteControlState } from "./app-link";
import type { RemoteStopShortcut } from "../native/wire";
import type { InputTransport } from "../remote-control/input-route";
import type { RemoteControlMode } from "../remote-control/protocol";
@@ -49,6 +49,7 @@ export interface ChannelActions {
setRoles(userId: string, roles: string[]): Promise;
startScreen(roomId: string): Promise;
nativeSources(): Promise;
+ nativeCaptureRequest(roomId: string): NativeCaptureRequest | undefined;
startNativeScreen(roomId: string, target: NativeCaptureTarget, audio?: boolean): Promise;
stopScreen(publicationId: string): Promise;
watch(publicationId: string): Promise;
diff --git a/src/client/channel/use-channel.ts b/src/client/channel/use-channel.ts
index 1a5335db7..9cb81de04 100644
--- a/src/client/channel/use-channel.ts
+++ b/src/client/channel/use-channel.ts
@@ -33,6 +33,7 @@ export function useChannel(onInvitation?: (roomId: string) => void): ChannelCont
attachments: session.attachments, loadHistory: session.loadHistory, loadLatestHistory: session.loadLatestHistory,
setRoles: session.setRoles, startScreen: session.startScreen,
nativeSources: session.nativeSources, startNativeScreen: session.startNativeScreen,
+ nativeCaptureRequest: session.nativeCaptureRequest,
stopScreen: session.stopScreen, watch: session.watch, unwatch: session.unwatch, screenPresentation: session.screenPresentation,
inputPolicy: session.inputPolicy, inputDecide: session.inputDecide, inputSimultaneous: session.inputSimultaneous, inputShortcut: session.inputShortcut,
joinVoice: session.joinVoice, leaveVoice: session.leaveVoice, setMuted: session.setMuted,
diff --git a/src/client/native/activation.ts b/src/client/native/activation.ts
index fee2a9038..6d2f97120 100644
--- a/src/client/native/activation.ts
+++ b/src/client/native/activation.ts
@@ -1,6 +1,8 @@
// Android intents only foreground Piik. App-owned pending requests still own
// permission, and the normal loopback approval/health checks own Site access.
export function androidAppIntent(action: unknown, userAgent = typeof navigator === "undefined" ? "" : navigator.userAgent): string | null {
+ // A connected App can name its installed package without frontend version rules.
+ if (typeof action === "string" && /^intent:\/\/media#Intent;scheme=piik;package=[A-Za-z0-9_.]+;end$/.test(action)) return action;
if (action !== "piik://app" && action !== "piik://media") return null;
// A connected App supplies its own media action. Android tablets can report
// a desktop UA; only an unconnected cold wake needs the browser OS hint.
diff --git a/src/client/native/wire.ts b/src/client/native/wire.ts
index e105e1aac..131c86740 100644
--- a/src/client/native/wire.ts
+++ b/src/client/native/wire.ts
@@ -94,7 +94,7 @@ const nativeDisplayTargetSchema = z
const nativePickerTargetSchema = z
.object({
kind: z.literal("picker"),
- sourceId: decimalIdentifierSchema,
+ sourceId: decimalIdentifierSchema.or(z.literal("0")),
title: z.string().min(1).max(4096),
})
.strict();
diff --git a/tests/channel-session.test.ts b/tests/channel-session.test.ts
index b6af22eb4..9306ef2d4 100644
--- a/tests/channel-session.test.ts
+++ b/tests/channel-session.test.ts
@@ -3,6 +3,7 @@ import { ChannelConversation } from "../src/client/channel/conversation";
import { ChannelSession } from "../src/client/channel/session";
import * as hosting from "../src/client/channel/hosting";
import * as appLink from "../src/client/channel/app-link";
+import * as nativeActivation from "../src/client/native/activation";
import * as launchSession from "../src/client/lib/session";
import { ChannelMedia } from "../src/client/channel/media";
import { ChannelTransport } from "../src/client/channel/transport";
@@ -281,11 +282,11 @@ test("local stop does not retire another capture acknowledged before its authori
});
test("Native capture previews before its snapshot, keeps picture on audio failure, and stops through its App owner", async () => {
+ vi.stubGlobal("navigator", { userAgent: "test", userActivation: { isActive: false } });
vi.mocked(launchSession.isClientActivated).mockReturnValue(true);
vi.spyOn(appLink, "discoverChannelAppHealth").mockResolvedValue({ service: "piik-channel-app", protocol: 1, port: 8793, token: "approved" });
const { session, socket } = await setup();
const app = ChannelSocket.current;
- const publicationId = crypto.randomUUID();
try {
await app.onopen?.();
app.receive({ id: app.sent.at(-1)!.id, result: null });
@@ -293,14 +294,19 @@ test("Native capture previews before its snapshot, keeps picture on audio failur
const target = { kind: "display" as const, sourceId: "1", title: "Test display" };
const listing = session.nativeSources();
await vi.waitFor(() => expect(app.sent.at(-1)?.type).toBe("targets"));
- const sources = { sources: [target], processAudio: false, systemAudio: true };
+ const activationURL = "intent://media#Intent;scheme=piik;package=tv.piik.android.test;end";
+ const sources = { sources: [target], processAudio: false, systemAudio: true, activationURL };
app.receive({ id: app.sent.at(-1)!.id, result: sources });
await expect(listing).resolves.toEqual(sources);
const starting = session.startNativeScreen("first", target, true);
await vi.waitFor(() => expect(app.sent.at(-1)?.type).toBe("start_capture"));
- expect(app.sent.at(-1)).toMatchObject({ type: "start_capture", roomId: "first", target, audio: true });
- app.receive({ id: app.sent.at(-1)!.id, result: { publicationId } });
+ const publicationId = app.sent.at(-1)!.publicationId as string;
+ expect(app.sent.at(-1)).toMatchObject({ type: "start_capture", publicationId, roomId: "first", target, audio: true });
+ expect(session.nativeCaptureRequest("first")).toEqual({ publicationId, activationURL });
+ app.receive({ id: app.sent.at(-1)!.id, result: null });
await vi.waitFor(() => expect(socket.sent.at(-1)?.type).toBe("subscribe"));
+ expect(session.nativeCaptureRequest("first")).toBeUndefined();
+ expect(session.getSnapshot().pending.has("screen:first")).toBe(true);
const watch = socket.sent.at(-1)!;
const state = session.getSnapshot().state!;
socket.receive({ type: "state", state });
@@ -315,7 +321,7 @@ test("Native capture previews before its snapshot, keeps picture on audio failur
expect(session.getSnapshot().state?.subscriptions).toEqual([publicationId]);
const controllerSessionId = crypto.randomUUID(), intent = crypto.randomUUID().replaceAll("-", "");
- const remote = { mode: "ask", platform: "windows", requests: [{ id: intent, peerId: controllerSessionId, state: "pending" }] };
+ const remote = { mode: "ask", platform: "windows", canSetStopShortcut: false, requests: [{ id: intent, peerId: controllerSessionId, state: "pending" }] };
app.receive({ type: "input_state", publicationId, state: remote });
expect(session.getSnapshot().remoteControls.get(publicationId)).toEqual(remote);
await expect(session.inputShortcut(publicationId)).resolves.toEqual({ key: 10, available: false });
@@ -363,6 +369,68 @@ test("Native capture previews before its snapshot, keeps picture on audio failur
} finally { session.close(); }
});
+test("pending Native capture stays page-owned through same-page stop and close", async () => {
+ vi.mocked(launchSession.isClientActivated).mockReturnValue(true);
+ vi.spyOn(appLink, "discoverChannelAppHealth").mockResolvedValue({ service: "piik-channel-app", protocol: 1, port: 8793, token: "approved" });
+ const { session, socket } = await setup();
+ const app = ChannelSocket.current;
+ try {
+ await app.onopen?.();
+ app.receive({ id: app.sent.at(-1)!.id, result: null });
+ await vi.waitFor(() => expect(session.getSnapshot().appConnected).toBe(true));
+ const target = { kind: "display" as const, sourceId: "1", title: "Test display" };
+ const activationURL = "intent://media#Intent;scheme=piik;package=tv.piik.android.test;end";
+ const sources = { sources: [target], processAudio: false, systemAudio: true, activationURL };
+ const capabilities = session.nativeSources();
+ await vi.waitFor(() => expect(app.sent.at(-1)?.type).toBe("targets"));
+ app.receive({ id: app.sent.at(-1)!.id, result: sources });
+ await capabilities;
+ const activate = vi.spyOn(nativeActivation, "activateNativePicker").mockImplementation(() => {
+ expect(app.sent.at(-1)?.type).toBe("start_capture");
+ });
+ const starting = session.startNativeScreen("first", target).catch(error => error);
+ await vi.waitFor(() => expect(app.sent.at(-1)?.type).toBe("start_capture"));
+ const request = app.sent.at(-1)!;
+ const publicationId = request.publicationId as string;
+ expect(publicationId).toEqual(expect.any(String));
+ expect(session.getSnapshot().ownedScreens.has(publicationId)).toBe(true);
+ expect(session.nativeCaptureRequest("first")).toEqual({ publicationId, activationURL });
+ expect(activate).toHaveBeenCalledWith(activationURL);
+
+ const listing = session.nativeSources();
+ await vi.waitFor(() => expect(app.sent.at(-1)?.type).toBe("targets"));
+ app.receive({ id: app.sent.at(-1)!.id, result: sources });
+ await listing;
+ const stopping = session.stopScreen(publicationId);
+ expect(app.sent.at(-1)).toMatchObject({ type: "stop_capture", publicationId });
+ app.receive({ id: app.sent.at(-1)!.id, result: null });
+ app.receive({ id: request.id, error: "capture_cancelled" });
+ await stopping;
+ expect(await starting).toMatchObject({ name: "AbortError" });
+ expect(session.getSnapshot().ownedScreens.size).toBe(0);
+ expect(session.nativeCaptureRequest("first")).toBeUndefined();
+ expect(session.getSnapshot().error).toBeNull();
+ expect(socket.sent.some(command => command.type === "subscribe")).toBe(false);
+
+ const failed = session.startNativeScreen("first", target).catch(error => error);
+ await vi.waitFor(() => expect(app.sent.at(-1)?.type).toBe("start_capture"));
+ app.receive({ id: app.sent.at(-1)!.id, error: "capture_failed" });
+ await vi.waitFor(() => expect(app.sent.at(-1)?.type).toBe("stop_capture"));
+ expect(session.nativeCaptureRequest("first")).toBeUndefined();
+ app.receive({ id: app.sent.at(-1)!.id, result: null });
+ expect((await failed).message).toBe("capture_failed");
+
+ const closing = session.startNativeScreen("first", target).catch(error => error);
+ await vi.waitFor(() => expect(app.sent.at(-1)?.type).toBe("start_capture"));
+ expect(session.getSnapshot().ownedScreens.size).toBe(1);
+ session.close();
+ expect((await closing).message).toBe("app_disconnected");
+ expect(app.readyState).toBe(3);
+ expect(session.getSnapshot().ownedScreens.size).toBe(0);
+ expect(session.nativeCaptureRequest("first")).toBeUndefined();
+ } finally { session.close(); }
+});
+
test("remembered App intent does not prevent Browser hosting when no App is connected", async () => {
vi.mocked(launchSession.isClientActivated).mockReturnValue(true);
const discovery = vi.spyOn(appLink, "discoverChannelAppHealth").mockResolvedValue(null);
diff --git a/tests/native-activation.test.ts b/tests/native-activation.test.ts
index 0777f2457..1083a488f 100644
--- a/tests/native-activation.test.ts
+++ b/tests/native-activation.test.ts
@@ -41,6 +41,16 @@ describe("Android App foreground actions", () => {
expect(androidAppIntent("piik://app", desktop)).toBeNull();
});
+ it("uses a connected App's complete package-specific media capability", () => {
+ const activation = "intent://media#Intent;scheme=piik;package=tv.piik.android.test;end";
+ const assign = vi.fn();
+ vi.stubGlobal("navigator", { userAgent: "desktop", userActivation: { isActive: true } });
+ vi.stubGlobal("window", { location: { assign } });
+ activateNativePicker(activation);
+ expect(assign).toHaveBeenCalledWith(activation);
+ expect(androidAppIntent(activation.replace(";end", ";S.extra=value;end"))).toBeNull();
+ });
+
it("keeps activation optional and validates the known health extension", () => {
const health = { protocol: NATIVE_CLIENT_PROTOCOL, service: "piik-client", port: NATIVE_CLIENT_PORT_START,
instanceToken: "a".repeat(43), nativeMedia: {} };
diff --git a/tests/native-client.test.ts b/tests/native-client.test.ts
index e8f557660..8f269dbd1 100644
--- a/tests/native-client.test.ts
+++ b/tests/native-client.test.ts
@@ -898,7 +898,7 @@ describe("native App private wire", () => {
} finally { client.close(); }
});
- it("keeps 64-bit Windows identities as exact decimal strings", () => {
+ it("keeps exact positive physical identities and accepts system picker zero", () => {
expect(
nativeCaptureTargetSchema.safeParse({
kind: "window",
@@ -931,6 +931,15 @@ describe("native App private wire", () => {
title: "System picker",
}).success,
).toBe(true);
+ expect(nativeCaptureTargetSchema.safeParse({
+ kind: "picker", sourceId: "0", title: "System picker",
+ }).success).toBe(true);
+ expect(nativeCaptureTargetSchema.safeParse({
+ kind: "display", sourceId: "0", title: "Display",
+ }).success).toBe(false);
+ expect(nativeCaptureTargetSchema.safeParse({
+ kind: "window", sourceId: "0", pid: 1234, creationTime: "134327999999999999", title: "Game",
+ }).success).toBe(false);
});
it("fences native events by share and connection identity", () => {