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
2 changes: 1 addition & 1 deletion .github/extensions/replica-prototype/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ The Replica prototype canvas puts a local prototype in the Copilot app alongside

**Options** in the canvas toolbar reads `/controls.replica.json` from the preview and binds its eleven supported field types to ordinary app behavior. Existing sets, flat groups and conditions render in the shared panel. Options work independently of Hub and comments; dismissal keeps the same iframe and route. The AI accepts both "options" and "controls".

The injected adapter applies JSON defaults and valid URL overrides. Missing definitions mean no options; invalid definitions produce a local error while the ordinary app remains usable. Missing, ambiguous or stale targets disable only the affected control and reconnect when valid. App rejection, clamping and async failures are explicit; actions are never automatically replayed.
The injected adapter applies JSON defaults and valid URL overrides. API values with `initial: "app"` instead adopt the app's current value and are never saved in `rc.*`; edits and reset still write through the app API. See the [page-selector recipe](../../../starters/shared/.agents/skills/prototype-controls/references/authoring.md#switch-between-app-pages). Missing definitions mean no options; invalid definitions produce a local error while the ordinary app remains usable. Missing, ambiguous or stale targets disable only the affected control and reconnect when valid. App rejection, clamping and async failures are explicit; actions are never automatically replayed.

Canvas and Hub save overrides in prototype URLs as `rc.<scope>.<controlId>`, never in private renderer/proxy capability URLs. Edits preserve history state without reload or extra entries. Back/Forward restores settings; reset-all removes overrides and resets inactive sets. Conditional hiding discards overrides, while ordinary page unmount/return preserves cached values. Private value files are no longer read or written; existing files remain untouched.

Expand Down

Large diffs are not rendered by default.

Large diffs are not rendered by default.

10 changes: 5 additions & 5 deletions .github/extensions/replica-prototype/assets/renderer.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion .github/extensions/replica-prototype/plugin.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
"name": "replica-prototype",
"description": "Wrap a running prototype with Replica publish controls and repository status.",
"version": "1.10.1",
"version": "1.10.2",
"author": {
"name": "GitHub"
},
Expand Down
8 changes: 4 additions & 4 deletions hub/.storybook/preview-fixtures/build-controls/controls.js

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,7 @@ export function App({ config }: Props) {
revision: shareContext?.target,
onChange: sharing.setControlPreference,
},
controls.connection?.getControlValuesError(),
)

useLayoutEffect(() => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { afterEach, expect, it, vi } from "vitest"

import { getControlsRuntime } from "@utils/prototype-controls/controls.mjs"
import { installControlsBridge } from "./controls"
import { controlsEnvelope } from "@utils/prototype-controls-protocol"
import { controlsEnvelope, type ControlsEnvelope } from "@utils/prototype-controls-protocol"

const origin = "http://127.0.0.1:1234"
let dispose: (() => void) | undefined
Expand Down Expand Up @@ -128,6 +128,211 @@ it("rejects foreign frames, origins, epochs and stale commands without changing
frame.remove()
})

it("ignores legacy app-owned overrides and never saves route edits as rc values", async () => {
let page = "/current"
const write = vi.fn((next: string) => {
page = next
})
vi.stubGlobal("initialRouteApi", {
read: () => page,
write,
subscribe: () => () => {},
})
const post = await setup({
...declaration,
controls: [
...declaration.controls,
{
id: "page",
label: "Page",
type: "text",
default: "/default",
binding: {
type: "api",
object: "initialRouteApi",
read: "read",
write: "write",
subscribe: "subscribe",
initial: "app",
},
},
],
})
const controller = getControlsRuntime().list()[0]!
hello({
controlQuery: "rc.canvasPage.page=%22%2Fold-saved%22&rc.canvasPage.title=%22Saved+title%22",
})
await vi.waitFor(() =>
expect(post.mock.calls.at(-1)?.[0]).toMatchObject({ type: "reply", requestId: "hello" }),
)
expect(new URLSearchParams(window.location.search).has("rc.canvasPage.page")).toBe(false)
async function command(requestId: string, operation: string, fields: object) {
message({
protocol: "replica:controls",
version: 1,
epoch: "canvas-epoch",
requestId,
type: "command",
command: {
operation,
scope: "canvasPage",
fingerprint: JSON.stringify(controller.declaration),
revision: controller.getSnapshot().revision,
...fields,
},
})
await vi.waitFor(() =>
expect(post.mock.calls.at(-1)?.[0]).toMatchObject({ type: "reply", requestId }),
)
expect(post.mock.calls.at(-1)?.[0]).not.toHaveProperty("error")
}
await command("restore-legacy", "restore", {
values: { page: "/old-saved", title: "Saved title" },
})
expect(page).toBe("/current")
expect(controller.getSnapshot().values).toMatchObject({
page: "/current",
title: "Saved title",
})
expect(write).not.toHaveBeenCalled()
expect(new URLSearchParams(window.location.search).get("rc.canvasPage.title")).toBe(
'"Saved title"',
)
expect(new URLSearchParams(window.location.search).has("rc.canvasPage.page")).toBe(false)

await command("edit-route", "update", { id: "page", value: "/next" })
expect(page).toBe("/next")
expect(write).toHaveBeenCalledExactlyOnceWith("/next")
expect(new URLSearchParams(window.location.search).has("rc.canvasPage.page")).toBe(false)
expect(new URLSearchParams(window.location.search).get("rc.canvasPage.title")).toBe(
'"Saved title"',
)
})

it("removes inactive app-owned overrides from the URL before the set mounts", async () => {
const post = await setup({
version: 1,
sets: [
declaration,
{
version: 1,
scope: "inactive",
container: "#unmounted-page",
controls: [
{
id: "page",
label: "Page",
type: "text",
default: "/default",
binding: {
type: "api",
object: "inactivePage",
read: "read",
write: "write",
subscribe: "subscribe",
initial: "app",
},
},
],
},
],
})
hello({
controlQuery: "rc.inactive.page=%22%2Fold%22&rc.inactive.title=%22Saved%22",
})
await vi.waitFor(() =>
expect(post.mock.calls.at(-1)?.[0]).toMatchObject({
type: "reply",
requestId: "hello",
state: {
inactiveDeclarations: [{ scope: "inactive" }],
},
}),
)
expect(new URLSearchParams(window.location.search).has("rc.inactive.page")).toBe(false)
expect(new URLSearchParams(window.location.search).get("rc.inactive.title")).toBe('"Saved"')
window.history.pushState({}, "", "/other")
expect(new URLSearchParams(window.location.search).has("rc.inactive.page")).toBe(false)
expect(new URLSearchParams(window.location.search).get("rc.inactive.title")).toBe('"Saved"')
})

it("adopts a history entry without rc values without writing its app-owned route", async () => {
window.history.replaceState({ router: "current" }, "", "/current")
const restoreHistory = window.history.replaceState.bind(window.history)
const write = vi.fn((next: string) => {
window.history.pushState({ router: next }, "", next)
})
vi.stubGlobal("historyRouteApi", {
read: () => window.location.pathname,
write,
subscribe(listener: () => void) {
window.addEventListener("popstate", listener)
return () => window.removeEventListener("popstate", listener)
},
})
const post = await setup({
version: 1,
scope: "historyRoute",
controls: [
{
id: "page",
label: "Page",
type: "text",
default: "/default",
binding: {
type: "api",
object: "historyRouteApi",
read: "read",
write: "write",
subscribe: "subscribe",
initial: "app",
},
},
],
})
const controller = getControlsRuntime().list()[0]!
expect(controller.getSnapshot().values.page).toBe("/current")
expect(write).not.toHaveBeenCalled()

restoreHistory({ router: "previous" }, "", "/previous")
window.dispatchEvent(new PopStateEvent("popstate", { state: { router: "previous" } }))
await vi.waitFor(() => expect(controller.getSnapshot().values.page).toBe("/previous"))
const notifications = post.mock.calls.map(([data]) => data as ControlsEnvelope)
expect(notifications.some((data) => data.type === "snapshot" && data.controlQuery === "")).toBe(
true,
)
hello({ fromFrameUrl: true, controlQuery: "" })
await vi.waitFor(() =>
expect(post.mock.calls.at(-1)?.[0]).toMatchObject({ type: "reply", requestId: "hello" }),
)
message({
protocol: "replica:controls",
version: 1,
epoch: "canvas-epoch",
requestId: "restore-history",
type: "command",
command: {
operation: "restore",
scope: "historyRoute",
fingerprint: JSON.stringify(controller.declaration),
revision: controller.getSnapshot().revision,
values: {},
},
})
await vi.waitFor(() =>
expect(post.mock.calls.at(-1)?.[0]).toMatchObject({
type: "reply",
requestId: "restore-history",
}),
)
expect(post.mock.calls.at(-1)?.[0]).not.toHaveProperty("error")
expect(controller.getSnapshot().values.page).toBe("/previous")
expect(window.location.pathname).toBe("/previous")
expect(window.history.state).toEqual({ router: "previous" })
expect(write).not.toHaveBeenCalled()
expect(new URLSearchParams(window.location.search).has("rc.historyRoute.page")).toBe(false)
})

it("adopts defaulted Build URLs and preserves router state without history entries", async () => {
window.history.replaceState({ router: "startup" }, "", "/?rc=1")
const post = await setup()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ import {
import { scopeProjection } from "@utils/prototype-controls-protocol/scope-projection"
import { validControlsValues } from "@utils/prototype-controls-protocol/valid-values"
import { installControlsUrl } from "@utils/install-prototype-controls-url"
import { nonDefaultValues } from "@utils/prototype-controls-url/non-default-values"
import { savedValues } from "@utils/prototype-controls-url/saved-values"
import { excludeAppOwnedValues } from "@utils/prototype-controls-url/exclude-app-owned-values"
import { controlsStatus } from "@utils/prototype-controls-status"

export function installControlsBridge(parentOrigin: string) {
Expand Down Expand Up @@ -40,14 +41,19 @@ export function installControlsBridge(parentOrigin: string) {
.filter((controller) => restoredScopes.has(controller.declaration.scope))
.map((controller) => [
controller.declaration.scope,
nonDefaultValues(scopeProjection(controller)),
savedValues(scopeProjection(controller)),
]),
),
(message) => {
if (urlError === message) return
urlError = message
send("snapshot", "event")
},
(values) =>
excludeAppOwnedValues(
values,
(runtime?.list() ?? []).map((controller) => controller.declaration),
),
)
async function load() {
try {
Expand Down Expand Up @@ -133,8 +139,18 @@ export function installControlsBridge(parentOrigin: string) {
}
}
function state(): ControlsState {
const inactiveDeclarations = (runtime?.list() ?? [])
.filter(
(controller) =>
controller.mountedCount === 0 &&
controller.declaration.controls.some(
(control) => control.binding?.type === "api" && control.binding.initial === "app",
),
)
.map((controller) => controller.declaration)
return {
...runtimeState(),
...(inactiveDeclarations.length ? { inactiveDeclarations } : {}),
scopeErrors: [],
reconnectRequired,
...(reconnectRequired ? { error: "Reconnect controls before sending more commands." } : {}),
Expand Down Expand Up @@ -252,9 +268,10 @@ export function installControlsBridge(parentOrigin: string) {
seen.clear()
reconnectRequired = false
restoredScopes.clear()
if (!loaded) await ready
if (disposed || epoch !== data.epoch) return
const fromFrameUrl = data.fromFrameUrl && controlsUrl?.managed()
controlsUrl?.set(fromFrameUrl ? controlsUrl.current() : (data.controlQuery ?? ""))
if (!loaded) await ready
send("reply", data.requestId, undefined, fromFrameUrl ? controlsUrl?.current() : undefined)
return
}
Expand Down Expand Up @@ -330,7 +347,17 @@ export function installControlsBridge(parentOrigin: string) {
throw new Error("Controls changed. The stale command was not applied.")
if (command.operation === "restore") {
if (!validControlsValues(command.values)) throw new Error("Invalid saved controls.")
await bindings?.restore(controller, command.values, guard)
const appOwned = new Set(
controller.declaration.controls
.filter(
(control) => control.binding?.type === "api" && control.binding.initial === "app",
)
.map((control) => control.id),
)
const overrides = Object.fromEntries(
Object.entries(command.values).filter(([id]) => !appOwned.has(id)),
)
await bindings?.restore(controller, overrides, guard)
restoredScopes.add(controller.declaration.scope)
controlsUrl?.refresh()
} else if (command.operation === "reset") {
Expand Down

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,29 @@ it("blocks configured link actions when state is too large, without hiding the e
expect(result.current.error).toBe("")
})

it("blocks unavailable settings only while including them", () => {
const unavailable = "Control settings cannot be verified."
const { result, rerender } = renderHook(
({ error }) => useShareControlSettings("prototype-a", {}, undefined, error),
{ initialProps: { error: unavailable } },
)
expect(result.current.included).toBe(false)
expect(result.current.blocked).toBe(false)
expect(result.current.error).toBe("")

act(() => result.current.onChange(true))
expect(result.current.blocked).toBe(true)
expect(result.current.error).toBe(unavailable)
rerender({ error: "" })
expect(result.current.blocked).toBe(false)
expect(result.current.error).toBe("")

rerender({ error: unavailable })
act(() => result.current.onChange(false))
expect(result.current.blocked).toBe(false)
expect(result.current.error).toBe("")
})

it("uses the canvas preference transport instead of the ephemeral browser origin", async () => {
const read = vi.spyOn(Storage.prototype, "getItem")
const write = vi.spyOn(Storage.prototype, "setItem")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export function useShareControlSettings(
revision?: string
onChange: (included: boolean) => Promise<void>
},
availabilityError?: string,
) {
const remoteIncluded = remote?.included
const remoteError = remote?.error
Expand Down Expand Up @@ -45,8 +46,8 @@ export function useShareControlSettings(
? preference
: initialPreference
let query = ""
let queryError = ""
if (current.included) {
let queryError = current.included ? (availabilityError ?? "") : ""
if (current.included && !queryError) {
try {
query = encodeControlValues(values)
} catch (error) {
Expand Down
Loading
Loading