mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-02 22:52:58 +00:00
Let plugins stream live events and binary data to the app (#8527)
* feat(plugins): stream events and bytes between plugins and the app
Plugins can declare a subscription with defineSubscription, handle it with
server.handle(contract, (input, { push, signal })), and listen from a surface
with useSubscription or client.subscribe. A top-level Uint8Array in an event,
an RPC output, or an RPC input crosses the wire as a binary frame (opcodes
0x20-0x2f) without JSON or base64; a nested one fails validation on the sender.
Each subscriber runs its own handler, owned by the session that subscribed,
so release, disconnect, plugin stop and reload need no plugin code. The
runtime buffers pushes until the subscribe response has gone out, so a client
never sees an event for a subscription it does not know yet.
Gated on server_info.features.pluginSubscriptions; binary outputs reach only
clients that advertise plugin_binary_payloads.
* fix(plugins): close subscription gaps found in review
- Losing daemon.manage now releases the session's plugin subscriptions;
binary events bypass the outbound permission check, so streams would
otherwise outlive the revocation.
- A subscribe that times out sends unsubscribe, since the plugin may
still start the handler after the daemon gave up.
- The byte limit leaves room for the largest frame header and routing,
and lives in assertPluginWireValue so events, outputs and inputs share it.
- A release right after the host accepted keeps `ready` resolved, so a
handler that returns at once reports closed rather than an error.
- Session trace logging tolerates loggers without isLevelEnabled.
* fix(plugins): withhold binary plugin results after plugin access is revoked
A binary RPC output or event skipped the outbound permission check its
JSON form passes, so an RPC in flight when daemon.manage was revoked still
delivered its bytes. Each frame now checks the permission of the JSON
message it stands in for.
* test(plugins): cover subscriptions in a real browser instead of JSDOM
The app subscription tests mounted hooks in JSDOM, which docs/testing.md
rules out. The adapter and contract behavior is now a plain unit test,
and a Playwright spec drives the diff-watch and media-stream examples:
JSON events following file changes, streamed bytes, and an upload.
* test(plugins): add the plain subscription unit test and the browser spec
* fix(plugins): apply subscription schema transforms once
Both ends parsed each subscription value, and the sender sent its parse
output, so the receiver parsed a schema's output as fresh input. An event
schema like z.string().transform((s) => s.length) closed the stream as
invalid. The sender now validates and sends the value as given; the
receiver's parse produces what the handler or callback sees.
* fix(plugins): parse a subscription's input once in the plugin process
server.handle wrapped subscription handlers in a second input parse, so a
transforming input schema rejected its own parsed output before the
handler ran.
This commit is contained in:
@@ -0,0 +1,7 @@
|
||||
# Live changes
|
||||
|
||||
See which files differ from `HEAD` in a workspace panel that updates as you edit. The daemon watches the workspace and pushes the changed-file list to the panel; the panel never polls.
|
||||
|
||||
Open **Open live changes** in the Command Center, or pick **Live changes** from the workspace tab menu. Each open panel runs its own watcher, which stops when you close the panel.
|
||||
|
||||
The watcher reads the working tree recursively, so a checkout with very large ignored directories makes it slower to start.
|
||||
@@ -0,0 +1,14 @@
|
||||
# Diff watch plugin example
|
||||
|
||||
A workspace panel subscribes to a daemon-side watcher and lists the files that differ from `HEAD`,
|
||||
updating as files change.
|
||||
|
||||
```bash
|
||||
paseo plugin add /absolute/path/to/paseo/plugin-examples/diff-watch
|
||||
```
|
||||
|
||||
- `shared/diff.ts` defines the `diff.watch` subscription contract.
|
||||
- `index.server.ts` handles it: an async handler that loops until the subscriber leaves, pushing
|
||||
the file list whenever it changes. A git failure rejects the handler and closes the subscription
|
||||
with that error.
|
||||
- `client/diff-panel.tsx` calls `useSubscription` and renders the latest list.
|
||||
@@ -0,0 +1,65 @@
|
||||
import {
|
||||
useSubscription,
|
||||
useWorkspace,
|
||||
type PluginWorkspacePanelProps,
|
||||
} from "@getpaseo/plugin/client";
|
||||
import { useMemo, useState } from "react";
|
||||
import { ScrollView, StyleSheet, Text, View } from "react-native";
|
||||
import { diffWatch, type ChangedFile } from "../shared/diff";
|
||||
|
||||
const BASE = "HEAD";
|
||||
|
||||
export function DiffPanel({ workspaceId, theme, layout }: PluginWorkspacePanelProps) {
|
||||
const cwd = useWorkspace(workspaceId, (workspace) => workspace.directory);
|
||||
const styles = useStyles(theme, layout.compact);
|
||||
if (!cwd) return <Text style={styles.muted}>Workspace unavailable</Text>;
|
||||
return <ChangedFiles cwd={cwd} styles={styles} />;
|
||||
}
|
||||
|
||||
function ChangedFiles({ cwd, styles }: { cwd: string; styles: ReturnType<typeof useStyles> }) {
|
||||
const [files, setFiles] = useState<ChangedFile[] | null>(null);
|
||||
const subscription = useSubscription(diffWatch, { cwd, from: BASE }, (event) => {
|
||||
setFiles(event.files);
|
||||
});
|
||||
return (
|
||||
<ScrollView style={styles.screen} contentContainerStyle={styles.content}>
|
||||
<Text style={styles.title}>Changes against {BASE}</Text>
|
||||
<Text style={styles.muted}>{describe(subscription, files)}</Text>
|
||||
{files?.map((file) => (
|
||||
<View key={file.path} style={styles.row}>
|
||||
<Text style={styles.status}>{file.status}</Text>
|
||||
<Text style={styles.path} numberOfLines={1}>
|
||||
{file.path}
|
||||
</Text>
|
||||
</View>
|
||||
))}
|
||||
</ScrollView>
|
||||
);
|
||||
}
|
||||
|
||||
function describe(
|
||||
subscription: ReturnType<typeof useSubscription>,
|
||||
files: ChangedFile[] | null,
|
||||
): string {
|
||||
if (subscription.status === "error") return subscription.error.message;
|
||||
if (subscription.status === "closed") return "Stopped watching";
|
||||
if (!files) return "Reading changes…";
|
||||
if (files.length === 0) return "No changes";
|
||||
return files.length === 1 ? "1 file changed" : `${files.length} files changed`;
|
||||
}
|
||||
|
||||
function useStyles(theme: PluginWorkspacePanelProps["theme"], compact: boolean) {
|
||||
return useMemo(
|
||||
() =>
|
||||
StyleSheet.create({
|
||||
screen: { flex: 1, backgroundColor: theme.colors.surface0 },
|
||||
content: { padding: compact ? 16 : 24, gap: 8 },
|
||||
title: { color: theme.colors.foreground, fontSize: 18, fontWeight: "600" },
|
||||
muted: { color: theme.colors.foregroundMuted },
|
||||
row: { flexDirection: "row", gap: 12, alignItems: "center" },
|
||||
status: { color: theme.colors.foregroundMuted, width: 72 },
|
||||
path: { color: theme.colors.foreground, flex: 1 },
|
||||
}),
|
||||
[theme, compact],
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { PluginClientContext } from "@getpaseo/plugin/client";
|
||||
import { DiffPanel } from "./client/diff-panel";
|
||||
|
||||
export default function contribute(client: PluginClientContext) {
|
||||
client.addWorkspacePanel({
|
||||
id: "changes",
|
||||
title: "Live changes",
|
||||
icon: "GitCompare",
|
||||
context: "workspace",
|
||||
Component: DiffPanel,
|
||||
});
|
||||
client.addCommandCenterItem({
|
||||
id: "open-changes",
|
||||
title: "Open live changes",
|
||||
icon: "GitCompare",
|
||||
context: "workspace",
|
||||
onSelect({ openPanel }) {
|
||||
openPanel("changes");
|
||||
},
|
||||
});
|
||||
return () => {};
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import type { PluginServerContext } from "@getpaseo/plugin/server";
|
||||
import { readChangedFiles, watchDirectory } from "./server/diff";
|
||||
import { diffWatch } from "./shared/diff";
|
||||
|
||||
export default function contribute(server: PluginServerContext) {
|
||||
// The handler runs for as long as the panel is subscribed; a git failure closes it with the error.
|
||||
server.handle(diffWatch, async (input, { push, signal }) => {
|
||||
const directory = watchDirectory(input.cwd, signal);
|
||||
let previous = "";
|
||||
while (await directory.settled()) {
|
||||
const files = await readChangedFiles(input);
|
||||
const current = JSON.stringify(files);
|
||||
if (current === previous) continue;
|
||||
previous = current;
|
||||
await push({ type: "changes", files });
|
||||
}
|
||||
});
|
||||
return () => {};
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"id": "diff-watch",
|
||||
"requirements": {
|
||||
"paseo": ">=0.15.0-beta.2"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import { watch } from "node:fs";
|
||||
import type { SubscriptionInput } from "@getpaseo/plugin";
|
||||
import { execCommand } from "@getpaseo/plugin/server";
|
||||
import type { ChangedFile, diffWatch } from "../shared/diff";
|
||||
|
||||
const SETTLE_MS = 150;
|
||||
|
||||
const STATUSES: Record<string, ChangedFile["status"]> = {
|
||||
A: "added",
|
||||
M: "modified",
|
||||
D: "deleted",
|
||||
R: "renamed",
|
||||
};
|
||||
|
||||
/** Lists changed files the way `git diff --name-status` does, plus untracked files. */
|
||||
export async function readChangedFiles({
|
||||
cwd,
|
||||
from,
|
||||
to,
|
||||
}: SubscriptionInput<typeof diffWatch>): Promise<ChangedFile[]> {
|
||||
const range = to ? [from, to] : [from];
|
||||
const { stdout } = await execCommand("git", ["diff", "--name-status", "-z", ...range], { cwd });
|
||||
const files = parseNameStatus(stdout);
|
||||
if (!to) {
|
||||
const untracked = await execCommand(
|
||||
"git",
|
||||
["ls-files", "--others", "--exclude-standard", "-z"],
|
||||
{
|
||||
cwd,
|
||||
},
|
||||
);
|
||||
for (const path of untracked.stdout.split("\0").filter(Boolean))
|
||||
files.push({ path, status: "added" });
|
||||
}
|
||||
return files.sort((left, right) => left.path.localeCompare(right.path));
|
||||
}
|
||||
|
||||
function parseNameStatus(output: string): ChangedFile[] {
|
||||
const fields = output.split("\0").filter(Boolean);
|
||||
const files: ChangedFile[] = [];
|
||||
for (let index = 0; index < fields.length; index += 1) {
|
||||
const code = fields[index][0];
|
||||
// Renames carry the old path before the new one.
|
||||
if (code === "R") index += 1;
|
||||
const path = fields[index + 1];
|
||||
index += 1;
|
||||
if (path) files.push({ path, status: STATUSES[code] ?? "modified" });
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
/** Resolves each time the directory settles after a change, and with false once `signal` aborts. */
|
||||
export function watchDirectory(cwd: string, signal: AbortSignal) {
|
||||
let changed = true;
|
||||
let wake: (() => void) | null = null;
|
||||
const watcher = watch(cwd, { recursive: true }, () => {
|
||||
changed = true;
|
||||
wake?.();
|
||||
});
|
||||
signal.addEventListener(
|
||||
"abort",
|
||||
() => {
|
||||
watcher.close();
|
||||
wake?.();
|
||||
},
|
||||
{ once: true },
|
||||
);
|
||||
return {
|
||||
async settled(): Promise<boolean> {
|
||||
// The watcher and the abort both wake a wait.
|
||||
if (!changed && !signal.aborted) await new Promise<void>((resolve) => (wake = resolve));
|
||||
wake = null;
|
||||
if (signal.aborted) return false;
|
||||
await new Promise((resolve) => setTimeout(resolve, SETTLE_MS));
|
||||
changed = false;
|
||||
return !signal.aborted;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { defineSubscription } from "@getpaseo/plugin";
|
||||
import { z } from "zod";
|
||||
|
||||
export const ChangedFileSchema = z.object({
|
||||
path: z.string(),
|
||||
status: z.enum(["added", "modified", "deleted", "renamed"]),
|
||||
});
|
||||
|
||||
export type ChangedFile = z.infer<typeof ChangedFileSchema>;
|
||||
|
||||
/** Files that differ between `from` and `to`; without `to`, the working tree. */
|
||||
export const diffWatch = defineSubscription({
|
||||
name: "diff.watch",
|
||||
input: z.object({ cwd: z.string(), from: z.string(), to: z.string().optional() }),
|
||||
event: z.object({ type: z.literal("changes"), files: z.array(ChangedFileSchema) }),
|
||||
});
|
||||
Reference in New Issue
Block a user