Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Make app editing persistent and simplify app management

Regan Bell38b50ef50244
diff --git a/deploy/web-ui/Dockerfile b/deploy/web-ui/Dockerfile
index 84c2fcbda..7bb55afba 100644
--- a/deploy/web-ui/Dockerfile
+++ b/deploy/web-ui/Dockerfile
@@ -15,6 +15,7 @@ COPY plugins/web-ui/package.json plugins/web-ui/package-lock.json ./
RUN npm ci --omit=dev && rm package-lock.json \
&& rm -rf /root/.npm /tmp/node-compile-cache
COPY plugins/web-ui/server ./server
+COPY plugins/web-ui/src/app-edit.ts ./src/app-edit.ts
COPY plugins/admin/src /admin/src
COPY plugins/admin/public /admin/public
COPY plugins/chassis/src /chassis/src
diff --git a/docs/qa/app-shell/README.md b/docs/qa/app-shell/README.md
new file mode 100644
index 000000000..584baed58
--- /dev/null
+++ b/docs/qa/app-shell/README.md
@@ -0,0 +1,23 @@
+# App shell and management QA
+
+Screenshots from a local web dev instance using the real Vite/Lit web UI, core, isolated Postgres, and a disposable Fieldnotes deployment. No UI or API responses are mocked. Loopback adapters supply the local development session and app host routing; the instance is not publicly accessible.
+
+## App and chat
+
+![Slim bar and full-height chat drawer](drawer.png)
+
+The agent identified the app from server-supplied conversation context, then published the requested background changes. The screenshot shows the green version requested during QA. The surrounding bar stays neutral.
+
+## Manage
+
+![Compact app management](manage.png)
+
+Long histories show the latest ten versions initially. “Show older versions” reveals ten more per click; tests exercise up to 150 versions.
+
+## Permissions
+
+![Owner permissions dialog](permissions.png)
+
+Browser QA covered opening and closing the drawer, top-level escape, staging a person without granting access, the custom access menu, and the manage page. Earlier QA exercised adding view access, changing it to manage, and revoking the test grant. Tests cover dialog-bound menu placement and frame-denying upstream responses.
+
+The picker adds people. Existing project/channel grants can be edited or removed; adding those scope types and an in-bar version selector are outside this change. The top-level escape applies to the current URL; navigation that drops its query parameter restores the shell.
diff --git a/docs/qa/app-shell/drawer.png b/docs/qa/app-shell/drawer.png
new file mode 100644
index 000000000..6367aa18e
Binary files /dev/null and b/docs/qa/app-shell/drawer.png differ
diff --git a/docs/qa/app-shell/manage.png b/docs/qa/app-shell/manage.png
new file mode 100644
index 000000000..026b87b7e
Binary files /dev/null and b/docs/qa/app-shell/manage.png differ
diff --git a/docs/qa/app-shell/permissions.png b/docs/qa/app-shell/permissions.png
new file mode 100644
index 000000000..073be7101
Binary files /dev/null and b/docs/qa/app-shell/permissions.png differ
diff --git a/plugins/web-ui/server/index.ts b/plugins/web-ui/server/index.ts
index a76165d9d..24cf6bea3 100644
--- a/plugins/web-ui/server/index.ts
+++ b/plugins/web-ui/server/index.ts
@@ -1,3 +1,4 @@
+import { appEditSlug } from "../src/app-edit.ts";
import { composioCallbackUrl } from "./composio-return.ts";
import { sharedSessionHtml } from "./shared-session.ts";
import { createServer, type IncomingMessage, type ServerResponse, type Server } from "node:http";
@@ -335,12 +336,18 @@ function webTurnBase(
text: string,
) {
const displayName = resolveIdentity(req)?.name ?? null;
+ const appSlug = appEditSlug(threadRef, user);
return {
surface: "web",
actor: { externalId: user, ...(displayName ? { displayName } : {}) },
conversation,
liveActor: true,
deliveryTarget: threadRef,
+ ...(appSlug
+ ? {
+ conversationHeader: `The user is chatting beside their deployed app ${JSON.stringify(appSlug)}. Requests about this app refer to that deployment. Use the existing app source and publish updates to the same deployment when requested. This context does not grant additional permissions.`,
+ }
+ : {}),
text,
};
}
@@ -2014,20 +2021,6 @@ const apiRoutes: readonly WebRoute[] = [
return relayCap(res, "DELETE", `/v1/keychain/credentials/${encodeURIComponent(id)}`);
},
},
- {
- method: "GET",
- path: "/api/deployments/:id/owner-url",
- handle: async (c) => {
- const { res, user } = c;
- const id = c.params.id!;
- if (!id || id.includes("/")) return json(res, 404, { error: "not_found" });
- return relayCore(
- res,
- "GET",
- `/v1/deployments/${encodeURIComponent(id)}/owner-url?principalId=${encodeURIComponent(user)}`,
- );
- },
- },
{
method: "GET",
path: "/api/deployments",
@@ -2075,6 +2068,25 @@ const apiRoutes: readonly WebRoute[] = [
}
},
},
+ {
+ method: "GET",
+ path: "/api/deployments/:id/share",
+ handle: async ({ res, params }) => relayCap(res, "GET", `/v1/deployments/${encodeURIComponent(params.id!)}/share`),
+ },
+ {
+ method: "POST",
+ path: "/api/deployments/:id/share",
+ handle: async ({ req, res, params }) => {
+ const body = await readJson<{ scope?: unknown; recipient?: unknown; access?: unknown }>(req, res, false);
+ if (!body) return;
+ return relayCap(
+ res,
+ "POST",
+ `/v1/deployments/${encodeURIComponent(params.id!)}/share`,
+ JSON.stringify({ scope: body.scope, recipient: body.recipient, access: body.access }),
+ );
+ },
+ },
{
method: "POST",
path: "/api/deployments/:id/display-name",
diff --git a/plugins/web-ui/src/app-edit.ts b/plugins/web-ui/src/app-edit.ts
new file mode 100644
index 000000000..019e5de30
--- /dev/null
+++ b/plugins/web-ui/src/app-edit.ts
@@ -0,0 +1,7 @@
+export function appEditSlug(threadRef: string | null | undefined, user: string | null | undefined): string | null {
+ if (!threadRef || !user) return null;
+ const prefix = `web:${user}:app-edit:`;
+ if (!threadRef.startsWith(prefix)) return null;
+ const slug = threadRef.slice(prefix.length);
+ return /^[a-z0-9-]{1,63}$/.test(slug) ? slug : null;
+}
diff --git a/plugins/web-ui/src/chat.ts b/plugins/web-ui/src/chat.ts
index cfbc7685a..e0dbe4154 100644
--- a/plugins/web-ui/src/chat.ts
+++ b/plugins/web-ui/src/chat.ts
@@ -1,3 +1,4 @@
+import { appEditSlug } from "./app-edit";
import { isConnectionReturn } from "./connection-return";
import "./onboarding-welcome";
import { setupContent } from "./setup-widget";
@@ -538,7 +539,7 @@ export function createChatSurface(
scopeId: string | null,
messages: ReturnType<typeof entriesToMessages>,
): boolean {
- if (appState.me?.welcomeCohort) return false;
+ if (appState.me?.welcomeCohort || appEditSlug(threadRef, appState.me?.user)) return false;
if (
!shouldStartProactiveOpener({
started: proactiveOpenerStarted,
@@ -1326,9 +1327,12 @@ export function createChatSurface(
: currentMessages;
updateSpeakerLabels(messages);
const isNewUser = sessionsState.list.filter((s) => s.id).length === 0;
- const showWelcome = appState.me?.welcomeCohort
- ? isWelcomeConversation(sessionsState.list, appState.me.user, chatState.threadRef, chatState.scopeId)
- : isNewUser && !messages.length;
+ const editingApp = appEditSlug(chatState.threadRef, appState.me?.user);
+ const showWelcome =
+ !editingApp &&
+ (appState.me?.welcomeCohort
+ ? isWelcomeConversation(sessionsState.list, appState.me.user, chatState.threadRef, chatState.scopeId)
+ : isNewUser && !messages.length);
let messageContent: Array<TemplateResult | typeof nothing> | TemplateResult | typeof nothing = nothing;
const inheritedOffset = chatState.inheritedExpanded ? chatState.inheritedMessages.length : 0;
if (messages.length) {
@@ -1342,8 +1346,8 @@ export function createChatSurface(
render(
html`
<div
- class="custom-chat-shell ${ctx.pane ? "in-pane" : ""} ${ctx.composer.state.dragging ? "dragging" : ""} ${
- emptyChat && !glanceTier ? "empty-chat" : ""
+ class="custom-chat-shell ${editingApp ? "app-edit-chat" : ""} ${ctx.pane ? "in-pane" : ""} ${ctx.composer.state.dragging ? "dragging" : ""} ${
+ emptyChat && !glanceTier && !editingApp ? "empty-chat" : ""
}"
@dragenter=${(e: DragEvent) => ctx.composer.onDragEnter(e)}
@dragover=${(e: DragEvent) => ctx.composer.onDragOver(e)}
@@ -1357,20 +1361,21 @@ export function createChatSurface(
</div>`
: nothing
}
- ${glanceTier || ctx.pane ? nothing : sessionTopbar()}
+ ${glanceTier || ctx.pane || editingApp ? nothing : sessionTopbar()}
${glanceTier ? paneGlance(agent, messages, glanceTier) : nothing}
<section class="chat-scroll">
${pinnedStrip()}
<div class="message-stack ${emptyChat ? "empty-stack" : ""}">
${showWelcome ? welcomeGreeting(!messages.length) : nothing} ${inheritedHeader()}
${chatState.earlierCount > 0 ? earlierNotice(agent) : nothing} ${messageContent}
- ${emptyChat && !isNewUser && !showWelcome ? html`<h1 class="chat-cta">${chatCta()}</h1>` : nothing}
+ ${emptyChat && !isNewUser && !editingApp && !showWelcome ? html`<h1 class="chat-cta">${chatCta()}</h1>` : nothing}
${showStateError(messages, agent.state.errorMessage) ? html`<div class="composer-error inline">${agent.state.errorMessage}</div>` : nothing}
</div>
</section>
<div class="chat-bottom-dock">
${
emptyChat &&
+ !editingApp &&
!(isNewUser && appState.me?.welcomeCohort) &&
!glanceTier &&
(!ctx.pane || tier === "full") &&
diff --git a/plugins/web-ui/src/composer.ts b/plugins/web-ui/src/composer.ts
index b4c8bb240..f145d2a02 100644
--- a/plugins/web-ui/src/composer.ts
+++ b/plugins/web-ui/src/composer.ts
@@ -1,3 +1,4 @@
+import { appEditSlug } from "./app-edit";
import { getRuntimeConfig, loadRuntimeConfig, saveRuntimeConfig, subscribeRuntimeConfig } from "./runtime-config-store";
import type { Agent, AgentMessage } from "@earendil-works/pi-agent-core";
import { createFileDragState } from "./file-drag";
@@ -504,7 +505,7 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {
const runtimePending = activeRuntimeConfig === null;
const inputBlocked = runtimePending || ctx.chat.state.resolvingApprovals.size > 0 || blockingPauses.length > 0;
const attachingDisabled = inputBlocked;
- let placeholder = "Ask anything";
+ let placeholder = appEditSlug(ctx.chat.state.threadRef, appState.me?.user) ? "Describe a change…" : "Ask anything";
if (inputBlocked) placeholder = runtimePending ? "Loading runtime…" : "Approve or deny to continue";
else if (agent.state.isStreaming) placeholder = "Queue a message for after this turn…";
let composerNotice: TemplateResult | typeof nothing = nothing;
diff --git a/plugins/web-ui/src/contexts.ts b/plugins/web-ui/src/contexts.ts
index 88ce60c53..1f4cc8f5a 100644
--- a/plugins/web-ui/src/contexts.ts
+++ b/plugins/web-ui/src/contexts.ts
@@ -1,3 +1,4 @@
+import { peopleResults, type DirectoryMatch } from "./people-results";
import { html, nothing, render, type TemplateResult } from "lit";
import {
ArrowLeft,
@@ -69,12 +70,6 @@ interface ScopeResourcesView {
manageable: boolean;
}
-interface DirectoryMatch {
- principalId: string;
- displayName: string;
- type: string;
-}
-
export const contextsState = {
list: [] as CoreContext[],
loaded: false,
@@ -791,22 +786,7 @@ function memberPicker(context: CoreContext): TemplateResult {
${icon(X, 15)}
</button>
</div>
- <div class="project-member-results">
- ${matches.map(
- (match) => html`
- <button
- class="project-member-result"
- type="button"
- ?disabled=${contextsState.memberSearching || contextsState.memberBusy}
- @click=${() => void addProjectMember(context, match)}
- >
- <span class="project-member-avatar" aria-hidden="true">${initials(match.displayName)}</span>
- <span class="project-member-name" dir="auto">${match.displayName}</span>
- ${icon(Plus, 15)}
- </button>
- `,
- )}
- </div>
+ ${peopleResults(matches, contextsState.memberSearching || contextsState.memberBusy, (match) => void addProjectMember(context, match))}
<div class="project-member-status" aria-live="polite">${memberStatus}</div>
</form>
`;
diff --git a/plugins/web-ui/src/deploy-permissions.ts b/plugins/web-ui/src/deploy-permissions.ts
new file mode 100644
index 000000000..532dc66af
--- /dev/null
+++ b/plugins/web-ui/src/deploy-permissions.ts
@@ -0,0 +1,240 @@
+import { html, render, nothing } from "lit";
+import { live } from "lit/directives/live.js";
+import { Search, X } from "lucide";
+import { api } from "./core-bridge";
+import { closeFormMenus, icon, initials, menuSelect } from "./ui";
+import { scopeChip } from "./contexts";
+import { friendlyPrincipal } from "./deploy-view";
+import { errMessage } from "../../chassis/src/errors";
+import { peopleResults, type DirectoryMatch } from "./people-results";
+
+interface Grant {
+ scope: string;
+ permission: "read" | "write";
+}
+
+export async function openDeploymentPermissions(id: string, title: string, owner: string): Promise<void> {
+ const opener = document.activeElement as HTMLElement | null;
+ const dialog = document.createElement("dialog");
+ dialog.className = "project-dialog deployment-permissions-dialog";
+ dialog.setAttribute("aria-labelledby", "deployment-permissions-heading");
+ document.body.append(dialog);
+ let grantees: Grant[] = [];
+ let matches: DirectoryMatch[] = [];
+ let query = "";
+ let access = "view";
+ let selected: DirectoryMatch | null = null;
+ let searchSequence = 0;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ let searching = false;
+ const names = new Map<string, string>();
+ let busy = true;
+ let loaded = false;
+ let error = "";
+ let searched = false;
+ const endpoint = `/api/deployments/${encodeURIComponent(id)}/share`;
+ const close = () => {
+ clearTimeout(timer);
+ searchSequence++;
+ closeFormMenus();
+ dialog.close();
+ dialog.remove();
+ if (opener?.isConnected) opener.focus();
+ };
+ dialog.addEventListener("cancel", (event) => {
+ event.preventDefault();
+ if (closeFormMenus()) return;
+ close();
+ });
+ const change = async (scope: string, value: string) => {
+ if (busy) return;
+ closeFormMenus();
+ busy = true;
+ error = "";
+ draw();
+ try {
+ const response = await api<{ grantees: Grant[] }>(endpoint, {
+ method: "POST",
+ body: JSON.stringify({ scope, access: value }),
+ });
+ grantees = response.grantees;
+ selected = null;
+ query = "";
+ searched = false;
+ searchSequence++;
+ matches = [];
+ } catch (e) {
+ error = errMessage(e, "Could not update permissions.");
+ } finally {
+ busy = false;
+ if (dialog.isConnected) draw();
+ }
+ };
+ const search = async () => {
+ const sequence = ++searchSequence;
+ const term = query.trim();
+ if (!term) {
+ matches = [];
+ searched = false;
+ searching = false;
+ draw();
+ return;
+ }
+ searching = true;
+ error = "";
+ draw();
+ try {
+ const response = await api<{ matches?: DirectoryMatch[] }>(
+ `/api/directory/resolve?q=${encodeURIComponent(term)}`,
+ );
+ if (sequence !== searchSequence || !dialog.isConnected) return;
+ matches = (response.matches ?? [])
+ .filter(
+ (person) =>
+ `personal:${person.principalId}` !== owner &&
+ !grantees.some((grant) => grant.scope === `personal:${person.principalId}`),
+ )
+ .slice(0, 8);
+ searched = true;
+ } catch (e) {
+ if (sequence === searchSequence) error = errMessage(e, "Could not find people.");
+ } finally {
+ if (sequence === searchSequence && dialog.isConnected) {
+ searching = false;
+ draw();
+ }
+ }
+ };
+ const permissionMenu = (value: string, label: string, update: (value: string) => void, removable = false) =>
+ html`<fieldset class="permission-control" ?disabled=${busy}>
+ ${menuSelect({
+ value,
+ ariaLabel: label,
+ options: [
+ { value: "view", label: "Can view" },
+ { value: "manage", label: "Can manage" },
+ ...(removable ? [{ value: "none", label: "Remove access" }] : []),
+ ],
+ onSelect: (next) => {
+ if (next) update(next);
+ },
+ })}
+ </fieldset>`;
+ const draw = () =>
+ render(
+ html`
+ <div class="project-dialog-head">
+ <div>
+ <h2 id="deployment-permissions-heading">App permissions</h2>
+ <p>${title}</p>
+ </div>
+ <button class="chip-x" type="button" aria-label="Close" @click=${close}>${icon(X, 16)}</button>
+ </div>
+ ${
+ loaded
+ ? html` <div class="permission-search">
+ ${
+ selected
+ ? html`<div class="permission-invite">
+ <div class="permission-person">
+ <span class="project-member-avatar">${initials(selected.displayName)}</span
+ ><span class="permission-person-label"
+ >${selected.displayName}<small>${selected.principalId}</small></span
+ >
+ </div>
+ <button
+ class="chip-x"
+ aria-label="Cancel selection"
+ ?disabled=${busy}
+ @click=${() => {
+ selected = null;
+ draw();
+ }}
+ >
+ ${icon(X, 14)}
+ </button>
+ <div class="permission-invite-actions">
+ ${permissionMenu(access, "New person's access", (value) => {
+ access = value;
+ draw();
+ })}<button
+ class="btn primary"
+ ?disabled=${busy}
+ @click=${() => {
+ if (selected) {
+ names.set(`personal:${selected.principalId}`, selected.displayName);
+ void change(`personal:${selected.principalId}`, access);
+ }
+ }}
+ >
+ Add
+ </button>
+ </div>
+ </div>`
+ : html`<form
+ @submit=${(event: SubmitEvent) => {
+ event.preventDefault();
+ clearTimeout(timer);
+ void search();
+ }}
+ >
+ <div class="project-member-search-row">
+ ${icon(Search, 16)}<input
+ id="app-people-query"
+ aria-label="Add people"
+ placeholder="Add people by name or handle"
+ type="search"
+ autocomplete="off"
+ maxlength="80"
+ .value=${live(query)}
+ ?disabled=${busy}
+ @input=${(event: Event) => {
+ query = (event.currentTarget as HTMLInputElement).value;
+ searchSequence++;
+ matches = [];
+ searched = false;
+ clearTimeout(timer);
+ timer = setTimeout(() => void search(), 200);
+ }}
+ />
+ </div>
+ ${peopleResults(matches, busy, (person) => {
+ selected = person;
+ closeFormMenus();
+ draw();
+ })}
+ ${searching ? html`<p class="permission-note" role="status">Searching…</p>` : nothing}
+ ${!searching && searched && !matches.length ? html`<p class="permission-note">No additional people found.</p>` : nothing}
+ </form>`
+ }
+ </div>`
+ : nothing
+ }
+ <div class="permission-section-label">People with access</div>
+ <div class="project-member-list">
+ <div class="permission-row">
+ <span class="project-member-avatar" aria-hidden="true">${initials(owner.replace("personal:", ""))}</span
+ ><span class="permission-person-label"
+ >${owner.startsWith("personal:") ? friendlyPrincipal(owner.slice(9)) : scopeChip(owner)}</span
+ ><span class="permission-owner">Owner</span>
+ </div>
+ ${grantees.map((grant) => html`<div class="permission-row"><span class="project-member-avatar" aria-hidden="true">${initials(grant.scope.replace("personal:", ""))}</span><span class="permission-person-label">${names.get(grant.scope) ?? (grant.scope.startsWith("personal:") ? grant.scope.slice(9) : scopeChip(grant.scope))}${names.has(grant.scope) ? html`<small>${grant.scope.replace("personal:", "")}</small>` : nothing}</span>${permissionMenu(grant.permission === "write" ? "manage" : "view", `Access for ${grant.scope}`, (value) => void change(grant.scope, value), true)}</div>`)}
+ </div>
+ ${busy ? html`<p role="status">Loading…</p>` : nothing}
+ ${error ? html`<p class="composer-error" role="alert">${error}</p>` : nothing}
+ <div class="project-dialog-actions actions"><button class="btn" @click=${close}>Done</button></div>
+ `,
+ dialog,
+ );
+ draw();
+ dialog.showModal();
+ try {
+ grantees = (await api<{ grantees: Grant[] }>(endpoint)).grantees;
+ loaded = true;
+ } catch (e) {
+ error = errMessage(e, "Could not load permissions.");
+ } finally {
+ busy = false;
+ if (dialog.isConnected) draw();
+ }
+}
diff --git a/plugins/web-ui/src/deploys.ts b/plugins/web-ui/src/deploys.ts
index f5933a200..77fc969d8 100644
--- a/plugins/web-ui/src/deploys.ts
+++ b/plugins/web-ui/src/deploys.ts
@@ -1,6 +1,7 @@
+import { openDeploymentPermissions } from "./deploy-permissions";
import { html, nothing, render, type TemplateResult } from "lit";
import { live } from "lit/directives/live.js";
-import { Archive, Check, Copy, ExternalLink, Pencil, RotateCcw, X } from "lucide";
+import { Archive, Check, Copy, ExternalLink, RotateCcw, X } from "lucide";
import { api, withBase } from "./core-bridge";
import { errMessage } from "../../chassis/src/errors";
import { copyText, icon, relTime } from "./ui";
@@ -51,6 +52,7 @@ let deployQuery = "";
let deployTab: DeploymentTab = "yours";
let deployPageHost: HTMLElement | null = null;
let activeDeploy: DeploymentView | null = null;
+let visibleVersionCount = 10;
let editingDeploy: { id: string; field: "displayName" | "name" } | null = null;
let deployDraft = "";
let deploySaving = false;
@@ -96,11 +98,11 @@ function permissionBadge(d: DeploymentView): TemplateResult {
function ownerLabel(d: DeploymentView): string {
const me = appState.me?.user;
- if (d.ownerScopeId === `personal:${me}`) return "Your personal context";
+ if (d.ownerScopeId === `personal:${me}`) return "Owned by you";
if (d.ownerScopeId?.startsWith("personal:"))
- return `${friendlyPrincipal(d.ownerScopeId.slice("personal:".length))} · Personal`;
+ return `Owned by ${friendlyPrincipal(d.ownerScopeId.slice("personal:".length))}`;
if (d.ownerScopeId?.startsWith("org:")) return "Organization";
- return d.createdBy ? `Shared context · created by ${friendlyPrincipal(d.createdBy)}` : "Shared context";
+ return "Shared context";
}
function deployTabs(): TemplateResult {
@@ -234,6 +236,7 @@ export function openDeployById(id: string): void {
}
async function openDeploy(d: DeploymentView): Promise<void> {
+ visibleVersionCount = 10;
editingDeploy = null;
deployDraft = "";
deployNotices = withoutDeploymentDetailNotice(deployNotices);
@@ -254,7 +257,7 @@ async function openDeploy(d: DeploymentView): Promise<void> {
function drawDeployDetail(d: DeploymentView, loading = false): void {
if (appState.currentView !== "deploys" || !appState.mainEl || activeDeploy?.id !== d.id) return;
- const host = document.createElement("div");
+ const host = appState.mainEl.querySelector<HTMLElement>(".deploy-detail-pane") ?? document.createElement("div");
host.className = "resource-pane deploy-detail-pane";
const versions = [...(d.versions ?? [])].sort((a, b) => b.version - a.version);
const running = d.status === "running";
@@ -275,86 +278,36 @@ function drawDeployDetail(d: DeploymentView, loading = false): void {
</div>
<div class="actions">
${running && d.webUrl ? html`<a class="btn primary" href=${withBase(d.webUrl)} target="_blank" rel="noreferrer">Open app ${icon(ExternalLink, 14)}</a>` : nothing}
- ${running && canManage(d) ? html`<button class="btn" type="button" @click=${(event: Event) => void openLiveEdit(d, event.currentTarget as HTMLButtonElement)}>${icon(Pencil, 14)}<span>Edit live</span></button>` : nothing}
${d.webUrl ? html`<button class="btn" type="button" @click=${(event: Event) => void copyText(new URL(withBase(d.webUrl!), window.location.href).href, event.currentTarget as HTMLButtonElement)}>${icon(Copy, 14)}<span>Copy URL</span></button>` : nothing}
</div>
</div>
${loading ? html`<div class="hint">Loading authoritative app details…</div>` : nothing}
${deployNotices.detail?.id === d.id ? html`<div class="status">${deployNotices.detail.text}</div>` : nothing}
- <section class="deploy-detail-section">
- <h3>Overview</h3>
- <div class="deploy-facts">
- <div><span>Status</span><strong>${statusLabel(d)}</strong></div>
- <div><span>Live version</span><strong>${d.appliedVersion ?? d.currentVersion ?? "None"}</strong></div>
- <div><span>Latest version</span><strong>${d.currentVersion ?? "None"}</strong></div>
- <div>
- <span>Last deployed</span
- ><strong>${deploymentLatestAt(d) ? new Date(deploymentLatestAt(d)).toLocaleString() : "Never"}</strong>
- </div>
- <div>
- <span>Last opened</span
- ><strong>${d.lastAccessAt ? relTime(d.lastAccessAt) : "No recorded access"}</strong>
- </div>
- <div><span>Access</span><strong>${permissionBadge(d)}</strong></div>
- </div>
- </section>
-
- <section class="deploy-detail-section">
- <h3>Ownership and access</h3>
- <div class="field">
- <label>Created in</label>
- <div class="value">${contextScope ? scopeChip(contextScope) : "Unknown"}</div>
- </div>
- <div class="field">
- <label>Owner</label>
- <div class="value">${ownerLabel(d)}</div>
+ <div class="deploy-summary">
+ <span>Live v${d.appliedVersion ?? d.currentVersion ?? "—"}</span>
+ ${d.currentVersion !== undefined && d.appliedVersion !== undefined && d.currentVersion !== d.appliedVersion ? html`<span>Latest v${d.currentVersion}</span>` : nothing}
+ ${deploymentLatestAt(d) ? html`<span ${tip(new Date(deploymentLatestAt(d)).toLocaleString())}>Updated ${relTime(deploymentLatestAt(d))}</span>` : nothing}
+ </div>
+ <div class="deploy-access-line">
+ <div>
+ <span>${ownerLabel(d)}</span>
+ ${contextScope && contextScope !== d.ownerScopeId ? html`<span class="deploy-secondary-context">Created in ${scopeChip(contextScope)}</span>` : nothing}
+ ${d.createdBy && d.ownerScopeId !== `personal:${d.createdBy}` ? html`<span class="deploy-secondary-context">Created by ${friendlyPrincipal(d.createdBy)}</span>` : nothing}
</div>
- ${
- d.createdBy
- ? html`<div class="field">
- <label>Created by</label>
- <div class="value">${friendlyPrincipal(d.createdBy)}</div>
- </div>`
- : nothing
- }
- ${
- d.gitUrl
- ? html`<div class="field deploy-git-field">
- <label>Git remote</label>
- <div class="value">
- <code>${d.gitUrl}</code
- ><button
- class="icon-btn subtle"
- type="button"
- ${tip("Copy Git remote")}
- aria-label="Copy Git remote"
- @click=${(event: Event) => void copyText(d.gitUrl!, event.currentTarget as HTMLButtonElement)}
- >
- ${icon(Copy, 14)}
- </button>
- </div>
- <p class="hint">
- ${d.permission === "write" ? "Clone or push a new version with this short-lived authenticated URL." : "Clone source with this short-lived read-only authenticated URL."}
- </p>
- </div>`
- : nothing
- }
- </section>
+ ${d.ownerScopeId === `personal:${appState.me?.user}` ? html`<button class="btn" type="button" @click=${() => void openDeploymentPermissions(d.id, deploymentTitle(d), d.ownerScopeId!)}>Permissions</button>` : permissionBadge(d)}
+ </div>
${
canManage(d)
? html`<section class="deploy-detail-section">
<h3>Settings</h3>
<div class="deploy-setting-row">
- <div>
- <strong>Display name</strong
- ><span>The human-friendly name shown here. This does not change the app URL.</span>
- </div>
- ${editingName ? deployEditForm(d, "displayName") : html`<div class="deploy-setting-value"><span dir="auto">${d.displayName || "Using URL slug"}</span><button class="btn" type="button" @click=${() => startEditDeploy(d, "displayName")}>Edit</button></div>`}
+ <div><strong>Display name</strong><span>Shown in the app bar and app list.</span></div>
+ ${editingName ? deployEditForm(d, "displayName") : html`<div class="deploy-setting-value"><span dir="auto">${deploymentTitle(d)}</span><button class="btn" type="button" @click=${() => startEditDeploy(d, "displayName")}>Edit</button></div>`}
</div>
<div class="deploy-setting-row">
- <div><strong>URL slug</strong><span>Changes the app URL. Existing links do not redirect.</span></div>
+ <div><strong>App URL</strong><span>Changes the app URL. Existing links do not redirect.</span></div>
${editingSlug ? deployEditForm(d, "name") : html`<div class="deploy-setting-value"><code>/d/${deploymentSlug(d)}/</code><button class="btn" type="button" @click=${() => startEditDeploy(d, "name")}>Change</button></div>`}
</div>
<div class="actions deploy-danger-actions">
@@ -382,7 +335,7 @@ function drawDeployDetail(d: DeploymentView, loading = false): void {
${
versions.length
? html`<div class="deploy-version-list">
- ${versions.map(
+ ${versions.slice(0, visibleVersionCount).map(
(version) => html`
<div class="deploy-version-row">
<div>
@@ -390,8 +343,7 @@ function drawDeployDetail(d: DeploymentView, loading = false): void {
>${version.version === d.appliedVersion ? html`<span class="badge ok">Live</span>` : nothing}${version.version === d.currentVersion && version.version !== d.appliedVersion ? html`<span class="badge">Latest</span>` : nothing}
</div>
<div>
- <span>${new Date(version.createdAt).toLocaleString()}</span
- >${version.commit ? html`<code ${tip(version.commit)}>${version.commit.slice(0, 10)}</code>` : nothing}
+ <span>${new Date(version.createdAt).toLocaleString()}</span>
</div>
</div>
`,
@@ -399,13 +351,27 @@ function drawDeployDetail(d: DeploymentView, loading = false): void {
</div>`
: html`<div class="empty compact">No version history available.</div>`
}
+ ${
+ versions.length > visibleVersionCount
+ ? html`<button
+ class="btn"
+ type="button"
+ @click=${() => {
+ visibleVersionCount += 10;
+ drawDeployDetail(d);
+ }}
+ >
+ Show older versions
+ </button>`
+ : nothing
+ }
</section>
</div>
${archiveCandidate ? archiveDialog(archiveCandidate) : nothing} ${deployToast ? undoToast(deployToast) : nothing}
`,
host,
);
- appState.mainEl.replaceChildren(host);
+ if (host.parentElement !== appState.mainEl) appState.mainEl.replaceChildren(host);
}
function returnToDeploysList(): void {
@@ -710,21 +676,6 @@ function undoToast(toast: { deployment: DeploymentView; text: string; undo?: boo
</div>`;
}
-async function openLiveEdit(d: DeploymentView, button: HTMLButtonElement): Promise<void> {
- const tab = window.open("about:blank", "_blank");
- try {
- const r = await api<{ url?: string }>(`/api/deployments/${encodeURIComponent(d.id)}/owner-url`);
- if (!r.url) throw new Error("no live URL for this app");
- if (tab) tab.location.href = r.url;
- else window.open(r.url, "_blank");
- } catch (error) {
- tab?.close();
- deployNotices = withDeploymentDetailNotice(deployNotices, d.id, errMessage(error, "Could not open live editing."));
- drawDeployDetail(activeDeploy ?? d);
- button.blur();
- }
-}
-
async function refreshDeployments(): Promise<"updated" | "failed" | "superseded"> {
const seq = ++deployRefreshSeq;
try {
diff --git a/plugins/web-ui/src/people-results.ts b/plugins/web-ui/src/people-results.ts
new file mode 100644
index 000000000..8c7d74105
--- /dev/null
+++ b/plugins/web-ui/src/people-results.ts
@@ -0,0 +1,25 @@
+import { html, type TemplateResult } from "lit";
+import { Plus } from "lucide";
+import { icon, initials } from "./ui";
+
+export interface DirectoryMatch {
+ principalId: string;
+ displayName: string;
+ type: string;
+}
+
+export function peopleResults(
+ matches: DirectoryMatch[],
+ busy: boolean,
+ select: (person: DirectoryMatch) => void,
+): TemplateResult {
+ return html`<div class="project-member-results">
+ ${matches.map(
+ (person) =>
+ html` <button class="project-member-result" type="button" ?disabled=${busy} @click=${() => select(person)}>
+ <span class="project-member-avatar" aria-hidden="true">${initials(person.displayName)}</span>
+ <span class="project-member-name" dir="auto">${person.displayName}</span>${icon(Plus, 15)}
+ </button>`,
+ )}
+ </div>`;
+}
diff --git a/plugins/web-ui/src/shell.css b/plugins/web-ui/src/shell.css
index 0f94e4eee..d1fa82beb 100644
--- a/plugins/web-ui/src/shell.css
+++ b/plugins/web-ui/src/shell.css
@@ -7080,7 +7080,7 @@ a.connector-widget:focus-visible {
opacity: 1;
}
.deploy-detail-pane {
- max-width: 960px;
+ max-width: 800px;
margin: 0 auto;
}
.deploy-detail-heading {
@@ -7104,48 +7104,41 @@ a.connector-widget:focus-visible {
font-size: 12.5px;
}
.deploy-detail-section {
- margin-top: 26px;
- padding-top: 22px;
+ margin-top: 20px;
+ padding-top: 16px;
border-top: 1px solid color-mix(in srgb, var(--border) 72%, transparent);
}
.deploy-detail-section h3 {
- margin: 0 0 14px;
+ margin: 0 0 6px;
font-size: 14px;
font-weight: 650;
}
-.deploy-facts {
- display: grid;
- grid-template-columns: repeat(3, minmax(0, 1fr));
- gap: 16px;
-}
-.deploy-facts > div {
+.deploy-summary {
display: flex;
- flex-direction: column;
- gap: 4px;
-}
-.deploy-facts > div > span {
+ flex-wrap: wrap;
+ gap: 6px 16px;
+ margin-top: 12px;
color: var(--muted-foreground);
- font-size: 11.5px;
-}
-.deploy-facts strong {
- min-height: 22px;
- font-size: 13px;
- font-weight: 550;
+ font-size: 12px;
}
-.deploy-git-field .value {
+.deploy-access-line {
display: flex;
align-items: center;
- gap: 8px;
+ justify-content: space-between;
+ gap: 16px;
+ margin-top: 20px;
+ padding: 14px 0;
+ border-block: 1px solid var(--border);
+ font-size: 13px;
}
-.deploy-git-field code {
- min-width: 0;
- max-width: 100%;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
+.deploy-access-line > div {
+ display: flex;
+ flex-direction: column;
+ gap: 5px;
}
-.deploy-git-field .hint {
- margin: 5px 0 0;
+.deploy-secondary-context {
+ font-size: 12px;
+ color: var(--muted-foreground);
}
.deploy-setting-row {
display: grid;
@@ -7287,9 +7280,6 @@ a.connector-widget:focus-visible {
color: inherit;
}
@media (max-width: 760px) {
- .deploy-facts {
- grid-template-columns: repeat(2, minmax(0, 1fr));
- }
.deploy-setting-row {
grid-template-columns: minmax(0, 1fr);
}
@@ -7305,9 +7295,7 @@ a.connector-widget:focus-visible {
.deploy-row-actions {
padding: 8px 0 0;
}
- .deploy-facts {
- grid-template-columns: minmax(0, 1fr);
- }
+
.deploy-version-row {
grid-template-columns: minmax(0, 1fr);
gap: 5px;
@@ -10625,15 +10613,6 @@ h3.ambient-field-label {
animation: sheet-in 0.24s cubic-bezier(0.2, 0.8, 0.2, 1);
overflow-y: auto;
}
- .menu-popover::before,
- .session-menu-popover::before {
- content: "";
- position: fixed;
- inset: 0;
- z-index: -1;
- background: color-mix(in srgb, var(--foreground) 34%, transparent);
- animation: backdrop-in 0.24s ease;
- }
.menu-popover::after,
.session-menu-popover::after {
content: "";
@@ -11780,6 +11759,209 @@ h3.ambient-field-label {
background: var(--background);
}
+body.app-edit-embed .layout {
+ padding: 0;
+ gap: 0;
+}
+body.app-edit-embed .sidebar,
+body.app-edit-embed .sidebar-scrim,
+body.app-edit-embed .sidebar-resize-handle,
+body.app-edit-embed .mobile-menu-btn {
+ display: none;
+}
+body.app-edit-embed .main {
+ margin: 0;
+ padding: 0;
+ border: 0;
+ border-radius: 0;
+ box-shadow: none;
+}
+.app-edit-chat {
+ grid-template-rows: minmax(0, 1fr) auto;
+}
+body.app-edit-embed .assistant-body,
+body.app-edit-embed .user-bubble {
+ font-size: 13px;
+ line-height: 1.6;
+}
+body.app-edit-embed .message-stack {
+ box-sizing: border-box;
+ width: 100%;
+ max-width: none;
+ margin: 0;
+ padding-inline: 24px;
+}
+body.app-edit-embed .composer-wrap {
+ --composer-font-size: 13px;
+ --composer-pad-inline: 16px;
+ --composer-pad-end: 16px;
+ box-sizing: border-box;
+ width: 100%;
+ max-width: none;
+ margin: 0;
+ border: 0;
+ border-top: 1px solid var(--border);
+ border-radius: 0;
+ box-shadow: none;
+}
+
+body.app-edit-embed .chat-scroll {
+ padding: 12px 0;
+ scrollbar-gutter: auto;
+}
+body.app-edit-embed .custom-chat-shell.app-edit-chat > .chat-bottom-dock {
+ margin-top: 0;
+}
+
+.deployment-permissions-dialog {
+ width: min(440px, calc(100vw - 32px));
+ padding: 24px;
+}
+.deployment-permissions-dialog .project-dialog-head {
+ margin-bottom: 20px;
+}
+.deployment-permissions-dialog .project-dialog-head h2 {
+ font-size: 17px;
+}
+.deployment-permissions-dialog .project-dialog-head p {
+ margin: 4px 0 0;
+ color: var(--muted-foreground);
+ font-size: 12px;
+}
+.permission-search {
+ margin-bottom: 24px;
+}
+.permission-search .project-member-results:not(:has(button)) {
+ display: none;
+}
+.permission-section-label {
+ font-size: 11px;
+ font-weight: 500;
+ color: var(--muted-foreground);
+ margin-bottom: 8px;
+}
+.permission-row,
+.permission-person {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ min-width: 0;
+}
+.permission-row {
+ min-height: 48px;
+}
+.permission-person-label {
+ flex: 1;
+ min-width: 0;
+ font-size: 13px;
+ overflow-wrap: anywhere;
+}
+.permission-person-label small {
+ display: block;
+ font-size: 11px;
+ color: var(--muted-foreground);
+}
+.permission-owner {
+ font-size: 12px;
+ color: var(--muted-foreground);
+ padding-right: 10px;
+}
+.permission-control {
+ border: 0;
+ margin: 0;
+ padding: 0;
+ min-width: 0;
+ flex: none;
+}
+.permission-control .menu-button {
+ font-size: 12px;
+ min-height: 30px;
+ border: 0;
+ background: transparent;
+ padding: 4px 8px;
+}
+.permission-control .menu-popover {
+ width: 170px;
+ left: auto;
+ right: 0;
+}
+.permission-control .menu-option {
+ font-size: 12px;
+}
+.permission-invite {
+ display: grid;
+ grid-template-columns: 1fr auto;
+ gap: 12px;
+ padding: 12px;
+ border: 1px solid var(--border);
+ border-radius: var(--radius-sm);
+}
+.permission-invite-actions {
+ grid-column: 1 / -1;
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+}
+.permission-note {
+ font-size: 12px;
+ color: var(--muted-foreground);
+ margin: 10px 0 0;
+}
+.deployment-permissions-dialog .project-dialog-actions {
+ margin-top: 20px;
+}
+
+.deployment-permissions-dialog .permission-control .menu-popover {
+ position: absolute !important;
+ inset: calc(100% + 6px) 0 auto auto !important;
+ width: 170px !important;
+ min-width: 170px;
+ max-height: 220px !important;
+ padding: 4px;
+ border: 1px solid var(--border);
+ border-radius: var(--radius-sm);
+ animation: none;
+}
+.deployment-permissions-dialog .permission-control .menu-popover::after {
+ display: none;
+}
+.deployment-permissions-dialog .permission-control .menu-option {
+ min-height: 34px;
+ padding: 6px 10px;
+}
+.deployment-permissions-dialog .permission-invite .menu-popover {
+ inset: calc(100% + 6px) auto auto 0 !important;
+}
+.deployment-permissions-dialog .permission-control .menu-popover.drop-up {
+ top: auto !important;
+ bottom: calc(100% + 6px) !important;
+}
+
+.deploy-access-line + .deploy-detail-section {
+ border-top: 0;
+ padding-top: 0;
+}
+.deploy-detail .deploy-setting-row {
+ grid-template-columns: minmax(0, 1fr) auto;
+ gap: 16px;
+ padding: 12px 0;
+}
+.deploy-detail .deploy-setting-value {
+ justify-content: flex-end;
+}
+.deploy-detail .deploy-setting-row > div:first-child span {
+ max-width: 250px;
+}
+@media (max-width: 520px) {
+ .deploy-detail .deploy-setting-row {
+ grid-template-columns: minmax(0, 1fr);
+ gap: 8px;
+ }
+ .deploy-detail .deploy-setting-value {
+ justify-content: flex-start;
+ }
+}
+
.conversation-error {
margin: auto;
padding: 48px 24px;
diff --git a/plugins/web-ui/src/shell.ts b/plugins/web-ui/src/shell.ts
index cc2af946d..e2a3e6750 100644
--- a/plugins/web-ui/src/shell.ts
+++ b/plugins/web-ui/src/shell.ts
@@ -961,12 +961,12 @@ function warmDeferredChunks(): void {
function openAppEditChat(slug: string): void {
const user = appState.me?.user ?? "anon";
const threadRef = `web:${user}:app-edit:${slug}`;
+ if (storedDraft(threadRef) === `Update my deployed app "${slug}": `) saveDraft(threadRef, "");
const existing = sessionsState.list.find((s) => s.threadRef === threadRef);
if (existing) {
void openSession(existing);
return;
}
- if (!storedDraft(threadRef)) saveDraft(threadRef, `Update my deployed app "${slug}": `);
startNewChat(null, null, threadRef);
renderList();
}
@@ -988,6 +988,7 @@ export async function boot(): Promise<void> {
session: wantedSession,
item: wantedItem,
} = parseDeepLink(UI_BASE, location.pathname, location.search);
+ document.body.classList.toggle("app-edit-embed", wanted === "app-edit" && params.get("embed") === "1");
const chatsLink = wanted === null || wanted === "chats";
const linkedId = wantedSession && chatsLink ? wantedSession : null;
let transcriptUnavailable = false;
diff --git a/plugins/web-ui/src/ui.ts b/plugins/web-ui/src/ui.ts
index e5dd2e7f7..2adec7a8d 100644
--- a/plugins/web-ui/src/ui.ts
+++ b/plugins/web-ui/src/ui.ts
@@ -381,16 +381,19 @@ function placeMenuPopover(menu: HTMLElement): void {
const margin = 8;
menu.style.transform = "";
menu.classList.remove("drop-up");
+ const dialog = menu.closest("dialog")?.getBoundingClientRect();
+ const left = Math.max(0, dialog?.left ?? 0) + margin;
+ const right = Math.min(window.innerWidth, dialog?.right ?? window.innerWidth) - margin;
+ const top = Math.max(0, dialog?.top ?? 0) + margin;
+ const bottom = Math.min(window.innerHeight, dialog?.bottom ?? window.innerHeight) - margin;
const rect = menu.getBoundingClientRect();
- const overflowRight = rect.right - (window.innerWidth - margin);
- const overflowLeft = margin - rect.left;
+ const overflowRight = rect.right - right;
+ const overflowLeft = left - rect.left;
if (overflowRight > 0)
- menu.style.transform = `translateX(${-Math.min(overflowRight, Math.max(0, rect.left - margin))}px)`;
- else if (overflowLeft > 0)
- menu.style.transform = `translateX(${Math.min(overflowLeft, window.innerWidth - margin - rect.right)}px)`;
+ menu.style.transform = `translateX(${-Math.min(overflowRight, Math.max(0, rect.left - left))}px)`;
+ else if (overflowLeft > 0) menu.style.transform = `translateX(${Math.min(overflowLeft, right - rect.right)}px)`;
const anchorTop = menu.parentElement?.getBoundingClientRect().top ?? rect.top;
- if (rect.bottom > window.innerHeight - margin && anchorTop - rect.height - margin >= margin)
- menu.classList.add("drop-up");
+ if (rect.bottom > bottom && anchorTop - rect.height - margin >= top) menu.classList.add("drop-up");
}
export function toggleFormMenu(e: Event): void {
diff --git a/plugins/web-ui/test/deployments-server-route.test.ts b/plugins/web-ui/test/deployments-server-route.test.ts
index 538491bfd..bf627ef87 100644
--- a/plugins/web-ui/test/deployments-server-route.test.ts
+++ b/plugins/web-ui/test/deployments-server-route.test.ts
@@ -16,6 +16,7 @@ interface Call {
method: string;
url: string;
body: Record<string, unknown>;
+ capability?: string;
}
const calls: Call[] = [];
@@ -35,10 +36,19 @@ const core = createServer((req: IncomingMessage, res) => {
req.on("end", () => {
const body = raw ? (JSON.parse(raw) as Record<string, unknown>) : {};
if (!(req.url ?? "").startsWith("/v1/surface-config")) {
- calls.push({ method: req.method ?? "GET", url: req.url ?? "", body });
+ calls.push({
+ method: req.method ?? "GET",
+ url: req.url ?? "",
+ body,
+ capability: req.headers["x-agent-capability"] as string | undefined,
+ });
}
res.writeHead(200, { "content-type": "application/json" });
- if (req.method === "GET" && req.url?.startsWith("/v1/deployments?")) {
+ if (req.url?.startsWith("/v1/session-cap")) {
+ res.end(JSON.stringify({ token: "signed-in-user-capability" }));
+ } else if (req.url?.startsWith("/v1/deployments/d1/share")) {
+ res.end(JSON.stringify({ grantees: [] }));
+ } else if (req.method === "GET" && req.url?.startsWith("/v1/deployments?")) {
res.end(JSON.stringify({ deployments: [deployment] }));
} else if (req.method === "GET") {
res.end(JSON.stringify({ deployment }));
@@ -91,3 +101,22 @@ test("deployment detail and restore bridge bind the signed-in principal", async
.find((call) => call.method === "POST" && isNoncedCoreCall(call.url, "/v1/deployments/status-page/restore"));
assert.deepEqual(slugRestoreCall?.body, { principalId: "alice" });
});
+
+test("deployment sharing uses the signed-in capability and drops caller identity fields", async () => {
+ const before = calls.length;
+ assert.equal((await fetch(`${base}/api/deployments/d1/share`, { headers })).status, 200);
+ assert.equal(
+ (
+ await fetch(`${base}/api/deployments/d1/share`, {
+ method: "POST",
+ headers,
+ body: JSON.stringify({ scope: "personal:bob", access: "view", actorId: "mallory", principalId: "mallory" }),
+ })
+ ).status,
+ 200,
+ );
+ const requests = calls.slice(before).filter((call) => call.url === "/v1/deployments/d1/share");
+ assert.equal(requests.length, 2);
+ assert.ok(requests.every((call) => call.capability === "signed-in-user-capability"));
+ assert.deepEqual(requests[1]?.body, { scope: "personal:bob", access: "view" });
+});
diff --git a/plugins/web-ui/test/deploys-source.test.ts b/plugins/web-ui/test/deploys-source.test.ts
index 2028d3116..e8e8029c1 100644
--- a/plugins/web-ui/test/deploys-source.test.ts
+++ b/plugins/web-ui/test/deploys-source.test.ts
@@ -3,6 +3,7 @@ import { readFileSync } from "node:fs";
import test from "node:test";
import { stripTypeScriptTypes } from "node:module";
import { createContext, runInContext } from "node:vm";
+import { JSDOM } from "jsdom";
import { deploymentListRefreshCanRedraw, type DeploymentView } from "../src/deploy-view.ts";
import {
withDeploymentListNotice,
@@ -121,6 +122,7 @@ function renderHarness(requestedId: string | null = null) {
deployLoading: false,
deployNotices: { list: "", detail: null },
activeDeploy: null,
+ visibleVersionCount: 70,
editingDeploy: null,
deployDraft: "",
deployRefreshSeq: 0,
@@ -170,6 +172,7 @@ test("the initial list refresh leaves an opened detail and its loading state unt
const rendering = h.render();
await new Promise((resolve) => setImmediate(resolve));
const opening = h.open();
+ assert.equal(h.context.visibleVersionCount, 10);
assert.equal(h.requests[0]!.path, "/api/deployments");
assert.equal(h.requests[1]!.path, "/api/deployments/opened-app");
h.requests[0]!.resolve({ deployments: [] });
@@ -217,3 +220,111 @@ test("the empty Yours tab does not imply the account has no deployments", () =>
const messages = readFileSync(new URL("../src/deploy-view.ts", import.meta.url), "utf8");
assert.doesNotMatch(messages, /You have no apps\./);
});
+
+for (const count of [0, 7, 23, 150]) {
+ test(`version history reveals ${count} versions in newest-first batches of ten`, () => {
+ const deployment = {
+ id: "history-app",
+ currentVersion: count,
+ appliedVersion: 1,
+ versions: Array.from({ length: count }, (_, index) => ({ version: index + 1, createdAt: 1000 })),
+ };
+ const handlers: Array<() => void> = [];
+ const redraws: unknown[] = [];
+ const context = createContext({
+ d: deployment,
+ nothing: "",
+ drawDeployDetail: (value: unknown) => redraws.push(value),
+ html(strings: TemplateStringsArray, ...values: unknown[]) {
+ const text = (value: unknown): string => {
+ if (typeof value === "function") {
+ handlers.push(value as () => void);
+ return "";
+ }
+ return Array.isArray(value) ? value.map(text).join("") : String(value);
+ };
+ return strings.reduce(
+ (result, part, index) => result + part + (index < values.length ? text(values[index]) : ""),
+ "",
+ );
+ },
+ });
+ const initialCount = source.match(/let visibleVersionCount = \d+;/)?.[0];
+ const orderedVersions = bodyOf("drawDeployDetail").match(/const versions = [^;]+;/)?.[0];
+ const section = source.match(
+ /<section class="deploy-detail-section">\s*<h3>Version history<\/h3>[\s\S]*?<\/section>/,
+ )?.[0];
+ assert.ok(initialCount && orderedVersions && section);
+ runInContext(stripTypeScriptTypes(initialCount + orderedVersions), context);
+ let shown = 10;
+ for (;;) {
+ handlers.length = 0;
+ const rendered = runInContext(stripTypeScriptTypes(`html\`${section}\``), context) as string;
+ const numbers = [...rendered.matchAll(/<strong>v(\d+)<\/strong/g)].map((match) => Number(match[1]));
+ assert.deepEqual(
+ numbers,
+ Array.from({ length: Math.min(shown, count) }, (_, index) => count - index),
+ );
+ assert.equal(rendered.includes("No version history available."), count === 0);
+ assert.equal(rendered.includes('class="badge ok">Live'), count > 0 && shown >= count);
+ assert.equal(rendered.includes('class="badge">Latest'), count > 1);
+ assert.equal(rendered.includes("Show older versions"), shown < count);
+ assert.equal(handlers.length, shown < count ? 1 : 0);
+ if (shown >= count) break;
+ handlers[0]!();
+ assert.equal(redraws.at(-1), deployment);
+ shown += 10;
+ }
+ assert.deepEqual(
+ deployment.versions.map((version) => version.version),
+ Array.from({ length: count }, (_, index) => index + 1),
+ );
+ });
+}
+
+test("detail redraws reuse the scroll container and retain focus", () => {
+ const dom = new JSDOM("<main></main>");
+ try {
+ const mainEl = dom.window.document.querySelector("main")!;
+ const deployment = { id: "app" };
+ const context = createContext({
+ appState: { currentView: "deploys", mainEl },
+ document: dom.window.document,
+ d: deployment,
+ activeDeploy: deployment,
+ editingDeploy: null,
+ deployNotices: {},
+ archiveCandidate: null,
+ deployToast: null,
+ visibleVersionCount: 10,
+ nothing: "",
+ html: () => "",
+ render(_template: unknown, host: HTMLElement) {
+ if (!host.firstChild) host.append(dom.window.document.createElement("button"));
+ },
+ deploymentContextScope: () => null,
+ listBackLink: () => "",
+ returnToDeploysList() {},
+ deploymentTitle: () => "App",
+ statusClass: () => "",
+ statusLabel: () => "",
+ deploymentSlug: () => "app",
+ deploymentLatestAt: () => null,
+ ownerLabel: () => "",
+ permissionBadge: () => "",
+ canManage: () => false,
+ });
+ runInContext(stripTypeScriptTypes(bodyOf("drawDeployDetail")), context);
+ runInContext("drawDeployDetail(d)", context);
+ const host = mainEl.firstElementChild as HTMLElement;
+ const button = host.querySelector("button")!;
+ host.scrollTop = 450;
+ button.focus();
+ runInContext("drawDeployDetail(d)", context);
+ assert.equal(mainEl.firstElementChild, host);
+ assert.equal(host.scrollTop, 450);
+ assert.equal(dom.window.document.activeElement, button);
+ } finally {
+ dom.window.close();
+ }
+});
diff --git a/plugins/web-ui/test/menu-placement.test.ts b/plugins/web-ui/test/menu-placement.test.ts
new file mode 100644
index 000000000..0493ea1cb
--- /dev/null
+++ b/plugins/web-ui/test/menu-placement.test.ts
@@ -0,0 +1,46 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { JSDOM } from "jsdom";
+import { toggleFormMenu, closeFormMenus } from "../src/ui.ts";
+
+for (const scenario of [
+ { name: "opens upward inside a shorter dialog", dialog: true, anchorTop: 340, upward: true },
+ { name: "stays downward when the dialog has room", dialog: true, anchorTop: 200, upward: false },
+ { name: "keeps viewport placement outside dialogs", dialog: false, anchorTop: 340, upward: false },
+ { name: "opens upward at the viewport bottom", dialog: false, anchorTop: 710, upward: true },
+]) {
+ test(`form menu ${scenario.name}`, () => {
+ const dom = new JSDOM(
+ `<body>${scenario.dialog ? "<dialog open>" : ""}<div class="form-menu-control"><button class="menu-button"></button><div class="menu-popover" hidden></div></div>${scenario.dialog ? "</dialog>" : ""}</body>`,
+ );
+ const previousWindow = Object.getOwnPropertyDescriptor(globalThis, "window");
+ const previousDocument = Object.getOwnPropertyDescriptor(globalThis, "document");
+ Object.defineProperty(globalThis, "window", { value: dom.window, configurable: true });
+ Object.defineProperty(globalThis, "document", { value: dom.window.document, configurable: true });
+ try {
+ const document = dom.window.document;
+ const control = document.querySelector<HTMLElement>(".form-menu-control")!;
+ const button = document.querySelector<HTMLButtonElement>("button")!;
+ const menu = document.querySelector<HTMLElement>(".menu-popover")!;
+ const box = (x: number, y: number, width: number, height: number) => new dom.window.DOMRect(x, y, width, height);
+ const dialog = document.querySelector("dialog");
+ if (dialog) dialog.getBoundingClientRect = () => box(100, 100, 440, 300);
+ control.getBoundingClientRect = () => box(300, scenario.anchorTop, 100, 30);
+ menu.getBoundingClientRect = () => box(300, scenario.anchorTop + 36, 170, 110);
+ button.addEventListener("click", toggleFormMenu);
+ button.click();
+ assert.equal(menu.hidden, false);
+ assert.equal(menu.classList.contains("drop-up"), scenario.upward);
+ assert.equal(button.getAttribute("aria-expanded"), "true");
+ closeFormMenus();
+ assert.equal(menu.hidden, true);
+ assert.equal(menu.classList.contains("drop-up"), false);
+ } finally {
+ if (previousWindow) Object.defineProperty(globalThis, "window", previousWindow);
+ else Reflect.deleteProperty(globalThis, "window");
+ if (previousDocument) Object.defineProperty(globalThis, "document", previousDocument);
+ else Reflect.deleteProperty(globalThis, "document");
+ dom.window.close();
+ }
+ });
+}
diff --git a/plugins/web-ui/test/new-chat-placement.test.ts b/plugins/web-ui/test/new-chat-placement.test.ts
index 3491d005c..8906aa3ec 100644
--- a/plugins/web-ui/test/new-chat-placement.test.ts
+++ b/plugins/web-ui/test/new-chat-placement.test.ts
@@ -290,3 +290,17 @@ test("splitting does not dispose a first turn waiting for its session ID", async
first.state.pendingSend = null;
});
});
+
+test("app edit chats suppress the general welcome and suggestions", async () => {
+ await withCanvas((canvas) => {
+ const conv = canvas.seededChat("web:tester:app-edit:example");
+ assert.ok(conv?.state.agent);
+ const shell = document.querySelector(".app-edit-chat");
+ assert.ok(shell);
+ assert.equal(shell.querySelector(".chat-cta"), null);
+ assert.equal(shell.querySelector("qm-onboarding-welcome"), null);
+ assert.equal(shell.querySelector(".suggested-activities"), null);
+ assert.ok(shell.querySelector(".composer-wrap"));
+ assert.deepEqual(conv.state.agent.state.messages, []);
+ });
+});
diff --git a/plugins/web-ui/test/pinned-composer-polish.test.ts b/plugins/web-ui/test/pinned-composer-polish.test.ts
index 1268524e4..e6816abf6 100644
--- a/plugins/web-ui/test/pinned-composer-polish.test.ts
+++ b/plugins/web-ui/test/pinned-composer-polish.test.ts
@@ -27,8 +27,14 @@ test("editable background activity is rendered inside the composer surface", ()
});
test("composer status rows share the responsive input font size", () => {
- const sizes = [...css.matchAll(/--composer-font-size: (\d+)px/g)].map((match) => Number(match[1]));
- assert.deepEqual(sizes, [15, 16]);
+ const sizes = [...css.matchAll(/([^{}]+)\{([^{}]*)\}/g)].flatMap((rule) =>
+ [...rule[2].matchAll(/--composer-font-size: (\d+)px/g)].map((match) => [rule[1].trim(), Number(match[1])]),
+ );
+ assert.deepEqual(sizes, [
+ [".composer-wrap", 15],
+ [".composer-wrap", 16],
+ ["body.app-edit-embed .composer-wrap", 13],
+ ]);
for (const selector of [".live-work-line", ".bg-activity-strip", ".composer-input"]) {
const blocks = css.matchAll(new RegExp(`${selector.replaceAll(".", "\\.")} \\{([^}]+)\\}`, "g"));
const declarations = [...blocks].flatMap((match) => [...match[1].matchAll(/font-size: ([^;]+);/g)]);
diff --git a/plugins/web-ui/test/split-single-header.test.ts b/plugins/web-ui/test/split-single-header.test.ts
index 5d256f16d..e57e01a88 100644
--- a/plugins/web-ui/test/split-single-header.test.ts
+++ b/plugins/web-ui/test/split-single-header.test.ts
@@ -1,13 +1,29 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
+import { runInNewContext } from "node:vm";
import test from "node:test";
const split = readFileSync(new URL("../src/split.ts", import.meta.url), "utf8");
const chat = readFileSync(new URL("../src/chat.ts", import.meta.url), "utf8");
const css = readFileSync(new URL("../src/shell.css", import.meta.url), "utf8");
-test("a pane renders one header: the chat's own session topbar stays out of panes", () => {
- assert.match(chat, /\$\{glanceTier \|\| ctx\.pane \? nothing : sessionTopbar\(\)\}/);
+test("only full standalone chats render their own session topbar", () => {
+ const expression = chat.match(/\$\{([^{}]+\? nothing : sessionTopbar\(\))\}/)?.[1];
+ assert.ok(expression);
+ for (const pane of [false, true]) {
+ for (const editingApp of [null, "my-app"]) {
+ for (const glanceTier of [null, "card", "strip"]) {
+ const shown = runInNewContext(expression, {
+ ctx: { pane },
+ editingApp,
+ glanceTier,
+ nothing: false,
+ sessionTopbar: () => true,
+ });
+ assert.equal(shown, !pane && !editingApp && !glanceTier);
+ }
+ }
+ }
});
test("the pane tab carries the scope / title breadcrumb", () => {
@@ -49,6 +65,20 @@ test("inline pane chrome is exactly tools, split, full screen, close", () => {
});
test("a topbar-less pane keeps the two-row grid: transcript bounded, composer at the bottom", () => {
- assert.match(chat, /class="custom-chat-shell \$\{ctx\.pane \? "in-pane" : ""\}/);
+ const classes = chat.match(/class="(custom-chat-shell [\s\S]*?)"\s+@dragenter/)?.[1];
+ assert.ok(classes);
+ for (const pane of [false, true]) {
+ for (const editingApp of [null, "my-app"]) {
+ const rendered: string[] = runInNewContext(`\`${classes}\``, {
+ ctx: { pane, composer: { state: { dragging: false } } },
+ editingApp,
+ emptyChat: false,
+ glanceTier: null,
+ }).split(/\s+/);
+ assert.equal(rendered.includes("in-pane"), pane);
+ assert.equal(rendered.includes("app-edit-chat"), Boolean(editingApp));
+ }
+ }
assert.match(css, /\.custom-chat-shell\.in-pane \{\s*grid-template-rows: minmax\(0, 1fr\) auto;\s*\}/);
+ assert.match(css, /\.app-edit-chat \{\s*grid-template-rows: minmax\(0, 1fr\) auto;\s*\}/);
});
diff --git a/plugins/web-ui/test/turn-idempotency-route.test.ts b/plugins/web-ui/test/turn-idempotency-route.test.ts
index ff3752daa..7b1ffca41 100644
--- a/plugins/web-ui/test/turn-idempotency-route.test.ts
+++ b/plugins/web-ui/test/turn-idempotency-route.test.ts
@@ -58,3 +58,34 @@ test("malformed client turn ids are not forwarded", async () => {
assert.equal(response.status, 202);
assert.equal(turns.at(-1)?.idempotencyKey, undefined);
});
+
+test("app editing forwards app context separately from the exact user message", async () => {
+ const response = await fetch(`${base}/api/turn`, {
+ method: "POST",
+ headers,
+ body: JSON.stringify({ text: "Make the title smaller", threadRef: "web:alice:app-edit:sample-app" }),
+ });
+ assert.equal(response.status, 202);
+ assert.equal(turns.at(-1)?.text, "Make the title smaller");
+ assert.match(String(turns.at(-1)?.conversationHeader), /deployed app "sample-app"/);
+});
+
+test("ordinary chats and invalid app references cannot inject app context", async () => {
+ for (const threadRef of ["web:alice:ordinary", "web:alice:app-edit:bad/name"]) {
+ const response = await fetch(`${base}/api/turn`, {
+ method: "POST",
+ headers,
+ body: JSON.stringify({ text: "hello", threadRef, conversationHeader: "injected" }),
+ });
+ assert.equal(response.status, 202);
+ assert.equal(turns.at(-1)?.conversationHeader, undefined);
+ }
+ const count = turns.length;
+ const response = await fetch(`${base}/api/turn`, {
+ method: "POST",
+ headers,
+ body: JSON.stringify({ text: "hello", threadRef: "web:bob:app-edit:sample-app" }),
+ });
+ assert.equal(response.status, 403);
+ assert.equal(turns.length, count);
+});
diff --git a/skills-seed/publish/SKILL.md b/skills-seed/publish/SKILL.md
index ace556be3..0f81bff9d 100644
--- a/skills-seed/publish/SKILL.md
+++ b/skills-seed/publish/SKILL.md
@@ -55,6 +55,18 @@ publish({ renameFrom: "s-1176-p-5050", name: "status-board" })
`publish` returns `{ id, name, version, url, dataDir? }` — give the user the `url` (`/d/<name>/`).
+## App bar and editing
+
+On a configured app subdomain, signed-in people who can manage the app automatically
+see a slim top bar. Chat opens a resizable editing conversation beside the app. Normal
+app links and refreshes keep editing available for the signed-in session; viewers with
+read-only access see the app alone.
+
+The bar uses a consistent neutral appearance, independent of the app's theme. Its
+name follows the app document title. The drawer opens directly into an empty composer;
+the app identity is supplied as conversation context, not pasted into the draft. The
+conversation survives app reloads after a publish.
+
## Durable data — where app state must live
The app's disk is **reset from source on every relaunch**, with one exception: when the
diff --git a/src/api/agent-api-catalog.ts b/src/api/agent-api-catalog.ts
index 5816a38de..f434eaf2f 100644
--- a/src/api/agent-api-catalog.ts
+++ b/src/api/agent-api-catalog.ts
@@ -434,7 +434,7 @@ const FAMILIES: AgentApiFamily[] = [
(m === "GET" && /^\/v1\/deployments\/[^/]+$/.test(p)) ||
(m === "GET" && /^\/v1\/deployments\/[^/]+\/fetch$/.test(p)) ||
(m === "GET" && /^\/v1\/deployments\/[^/]+\/logs$/.test(p)) ||
- (m === "GET" && /^\/v1\/deployments\/[^/]+\/git-url$/.test(p)) ||
+ (m === "GET" && /^\/v1\/deployments\/[^/]+\/(git-url|share)$/.test(p)) ||
(m === "POST" && /^\/v1\/deployments\/[^/]+\/(share|archive|restore|name|display-name|always-on)$/.test(p)),
guidance:
'To see the published apps you can reach across scopes, GET /v1/deployments (each row carries your permission and a clone/push gitUrl). Read what an app renders as the asking person with GET /v1/deployments/:id/fetch. A published app (`publish`) is reachable only by its owner plus whoever the owner shares it with. To widen or narrow that — "share it with everyone" or "share it with <teammate>" — POST /v1/deployments/:id/share with `scope:"org"` or `recipient:"<name>"`; no redeploy. To rename or take down an app, use name / display-name / archive. POST /v1/deployments/:id/always-on with `{alwaysOn:true|false}` keeps an app permanently warm (no idle cold starts) or returns it to sleep-when-idle. Anyone who manages the app can change these: its owner from any conversation, a current member of the channel/team it was published from, or someone granted "manage" access.',
@@ -469,6 +469,11 @@ const FAMILIES: AgentApiFamily[] = [
summary:
"get an authed git remote URL for a deployment you can reach (clone its source; push a new version if you have write access) — returns {url, permission}",
},
+ {
+ method: "GET",
+ path: "/v1/deployments/:id/share",
+ summary: "list access grants for an app you own (:id is its name or id) — returns {grantees}; owner-only",
+ },
{
method: "POST",
path: "/v1/deployments/:id/share",
diff --git a/src/api/routes/deployments.ts b/src/api/routes/deployments.ts
index 3ac07ff1c..1afb20064 100644
--- a/src/api/routes/deployments.ts
+++ b/src/api/routes/deployments.ts
@@ -12,7 +12,6 @@ import { spawn } from "node:child_process";
import { basename, dirname } from "node:path";
import { deploymentView, type App, type DeployInput } from "../app.ts";
import { errMessage } from "../../util/errors.ts";
-import { resolveBranding } from "../../resolution/branding.ts";
import { canonicalPayload, escapeHtml, sendJson, verifyOrReject } from "../http.ts";
import { mintPortalIdentity, verifyPortalIdentity, PORTAL_IDENTITY_HEADER } from "../../auth/portal-identity.ts";
import { audit, authorizeAdmin, isObj, orgScope } from "./shared.ts";
@@ -20,12 +19,7 @@ import { parseScopeId, scopeId, type Permission } from "../../types.ts";
import type { ApiCtx, BaseCtx, Route } from "./route.ts";
import { CONFIG_DEFAULTS } from "../../config.ts";
import { resolveShareTarget as resolveShareTargetGrammar } from "../artifact-share.ts";
-import {
- mintDeployOwnerToken,
- verifyDeployGitAccess,
- verifyDeployOwnerToken,
- viewerIdentityKey,
-} from "../../deploy/access-token.ts";
+import { verifyDeployGitAccess, viewerIdentityKey } from "../../deploy/access-token.ts";
import { APP_SHELL_PATH_PREFIX, appShellHtml } from "../../deploy/app-shell.ts";
import { principalDestination } from "../../reach/reach.ts";
import { portalSessionSub } from "../../deploy/viewer-session.ts";
@@ -761,14 +755,6 @@ async function fetchDeploymentResponse(
}
}
-function cookieValue(header: string | undefined, name: string): string {
- for (const part of (header ?? "").split(";")) {
- const p = part.trim();
- if (p.startsWith(`${name}=`)) return p.slice(name.length + 1);
- }
- return "";
-}
-
export async function proxyDeploymentSubdomain(ctx: BaseCtx): Promise<boolean> {
const { req, res, app, deps, url, pathname } = ctx;
const appsDomain = deps.deployAppsDomain;
@@ -803,7 +789,7 @@ export async function proxyDeploymentSubdomain(ctx: BaseCtx): Promise<boolean> {
pathname.startsWith("/") && !pathname.startsWith("//") && !/[\\\x00-\x1f]/.test(pathname) ? pathname : "/";
const staleAccess = url.searchParams.has("access");
url.searchParams.delete("access");
- const fromOwnerQuery = url.searchParams.get("owner") ?? "";
+ const staleOwner = url.searchParams.has("owner");
url.searchParams.delete("owner");
const signInAttempted = url.searchParams.get("dpl_signin") === "1";
url.searchParams.delete("dpl_signin");
@@ -812,72 +798,10 @@ export async function proxyDeploymentSubdomain(ctx: BaseCtx): Promise<boolean> {
res.writeHead(302, { location: safePathname + (qs ? `?${qs}` : ""), "cache-control": "no-store" });
res.end();
};
- let ownerCookie: string | null = null;
- if (fromOwnerQuery) {
- const session = await verifyDeployOwnerToken(gateSecret, fromOwnerQuery, slug);
- if (session && (await app.canManageDeployment(slug, session.sub))) {
- const maxAge = Math.max(1, Math.floor((session.exp - Date.now()) / 1000));
- ownerCookie = `dpl_owner=${fromOwnerQuery}; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=${maxAge}`;
- }
- }
- if (ownerCookie) {
- const qs = url.searchParams.toString();
- res.writeHead(302, {
- "set-cookie": [ownerCookie],
- location: safePathname + (qs ? `?${qs}` : ""),
- });
- res.end();
- return true;
- }
- if (staleAccess && ctx.method === "GET" && !cookieValue(req.headers.cookie, "dpl_owner")) {
+ if ((staleAccess || staleOwner) && ctx.method === "GET") {
cleanUrlRedirect();
return true;
}
- let ownerSub: string | null = null;
- const ownerCookieValue = cookieValue(req.headers.cookie, "dpl_owner");
- if (ownerCookieValue) {
- const session = await verifyDeployOwnerToken(gateSecret, ownerCookieValue, slug);
- if (session && (await app.canManageDeployment(slug, session.sub))) ownerSub = session.sub;
- }
- if (ownerSub && ctx.method === "GET" && pathname.startsWith(APP_SHELL_PATH_PREFIX)) {
- if (pathname === "/__claw__/version") {
- const d = await app.getDeployment(slug);
- if (!d) sendJson(res, 404, { error: "not_found" });
- else sendJson(res, 200, { version: d.appliedVersion ?? d.currentVersion });
- return true;
- }
- sendJson(res, 404, { error: "not_found" });
- return true;
- }
- if (ownerSub) {
- if (signInAttempted && ctx.method === "GET") {
- cleanUrlRedirect();
- return true;
- }
- // A top-level document load gets the owner shell: a slim top bar over the app
- // (framed same-origin) with a slide-out chat column for iterating on it. The
- // frame's own load carries sec-fetch-dest: iframe, so it proxies straight through.
- const isTopDocument = String(req.headers["sec-fetch-dest"] ?? "") === "document";
- if (ctx.method === "GET" && isTopDocument && deps.deployAppsLoginUrl) {
- const accent = (await resolveBranding(deps.config, orgScope(deps), deps.brandingDefault)).accent;
- res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" });
- res.end(
- appShellHtml({
- slug,
- portalUrl: deps.deployAppsLoginUrl,
- path: safePathname + url.search,
- ...(accent ? { accent } : {}),
- }),
- );
- return true;
- }
- const reach = await app.reachDeployment(slug, "", { bypassAcl: true });
- const sub = deps.deployAppsSessionSecret
- ? portalSessionSub(req.headers.cookie, deps.deployAppsSessionSecret)
- : null;
- await proxyReach(ctx, reach, pathname, sub ?? undefined);
- return true;
- }
const sessionSecret = deps.deployAppsSessionSecret;
const loginUrl = deps.deployAppsLoginUrl;
const wantsHtml = ctx.method === "GET" && String(req.headers.accept ?? "").includes("text/html");
@@ -905,7 +829,35 @@ export async function proxyDeploymentSubdomain(ctx: BaseCtx): Promise<boolean> {
}
return true;
}
- const reach = await app.reachDeployment(slug, sub);
+ const bareApp = url.searchParams.get("__qm_no_shell") === "1";
+ url.searchParams.delete("__qm_no_shell");
+ const isTopDocument = String(req.headers["sec-fetch-dest"] ?? "") === "document";
+ const isShellRequest = pathname.startsWith(APP_SHELL_PATH_PREFIX);
+ const canManage = await app.canManageDeployment(slug, sub);
+ if (ctx.method === "GET" && ((!bareApp && isTopDocument) || isShellRequest) && canManage) {
+ if (signInAttempted) {
+ cleanUrlRedirect();
+ return true;
+ }
+ const deployment = await app.getDeployment(slug);
+ if (isShellRequest) {
+ if (pathname === "/__claw__/version" && deployment)
+ sendJson(res, 200, { version: deployment.appliedVersion ?? deployment.currentVersion });
+ else sendJson(res, 404, { error: "not_found" });
+ return true;
+ }
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" });
+ res.end(
+ appShellHtml({
+ slug,
+ name: deployment?.displayName ?? slug,
+ portalUrl: loginUrl,
+ path: safePathname + url.search,
+ }),
+ );
+ return true;
+ }
+ const reach = await app.reachDeployment(slug, sub, canManage ? { bypassAcl: true } : undefined);
if (reach.status === "denied") {
const owner = (await app.getDeployment(slug).catch(() => null))?.ownerScopeId;
const ev = {
@@ -1234,29 +1186,6 @@ async function deploymentGitUrl(ctx: ApiCtx): Promise<void> {
return sendJson(res, 200, result);
}
-const OWNER_LINK_TTL_MS = 5 * 60 * 1000;
-
-async function deploymentOwnerUrl(ctx: ApiCtx): Promise<void> {
- const { res, app, params, deps } = ctx;
- const sub = ctx.capability?.actorId ?? ctx.actor?.p ?? ctx.url.searchParams.get("principalId");
- if (!sub) return sendJson(res, 403, { error: "forbidden", message: "an identified caller is required" });
- const gateSecret = deps.deployGateSecret;
- const appsDomain = deps.deployAppsDomain;
- const deployment = await app.getDeployment(params.id!);
- if (!deployment) return sendJson(res, 404, { error: "not_found" });
- const slug = deployment.name ?? deployment.id;
- if (!gateSecret || !appsDomain)
- return sendJson(res, 503, {
- error: "unavailable",
- message: `app subdomains are not configured — this app is reachable signed-in at /d/${slug}/; set DEPLOY_APPS_DOMAIN (with AWS_DEPLOY_GATE_SECRET) to enable per-app subdomains and live editing`,
- });
- if (!(await app.canManageDeployment(deployment.id, sub, ctx.capability?.scopeId)))
- return sendJson(res, 403, { error: "forbidden", message: "only someone who manages this app can edit it live" });
- const exp = Date.now() + OWNER_LINK_TTL_MS;
- const token = await mintDeployOwnerToken(gateSecret, { slug, sub, exp });
- return sendJson(res, 200, { url: `https://${slug}.${appsDomain}/?owner=${token}`, expiresAt: exp });
-}
-
async function createDeployment(ctx: ApiCtx): Promise<void> {
const { res, app, body } = ctx;
if (!isDeployInput(body)) return sendJson(res, 400, { error: "bad_request", message: "expected a DeployInput" });
@@ -1502,6 +1431,16 @@ export function resolveShareTarget(app: App, input: { scope?: string; recipient?
});
}
+export async function getDeploymentShares(ctx: ApiCtx): Promise<void> {
+ const { res, app, params, capability } = ctx;
+ if (!capability) return sendJson(res, 403, { error: "forbidden" });
+ const deployment = await app.getDeployment(params.id!);
+ if (!deployment) return sendJson(res, 404, { error: "not_found" });
+ if (deployment.ownerScopeId !== `personal:${capability.actorId}`)
+ return sendJson(res, 403, { error: "forbidden", message: "Only the owner can edit app permissions." });
+ return sendJson(res, 200, { grantees: await app.deploymentGrantees(deployment.id) });
+}
+
export async function shareDeployment(ctx: ApiCtx): Promise<void> {
const { res, app, params, body, capability } = ctx;
if (!capability)
@@ -1575,7 +1514,7 @@ export const deploymentRoutes: ReadonlyArray<Route<ApiCtx>> = [
{ method: "GET", path: "/v1/deployments/:id/fetch", auth: "either", handle: fetchDeployment },
{ method: "GET", path: "/v1/deployments/:id/logs", auth: "either", handle: deploymentLogs },
{ method: "GET", path: "/v1/deployments/:id/git-url", auth: "either", handle: deploymentGitUrl },
- { method: "GET", path: "/v1/deployments/:id/owner-url", auth: "source", handle: deploymentOwnerUrl },
+ { method: "GET", path: "/v1/deployments/:id/share", auth: "either", handle: getDeploymentShares },
{ method: "POST", path: "/v1/deployments/:id/share", auth: "either", handle: shareDeployment },
{ method: "POST", path: "/v1/deployments/:id/rollback", auth: "source", handle: rollbackDeployment },
{ method: "POST", path: "/v1/deployments/:id/redeploy", auth: "source", handle: redeployDeployment },
diff --git a/src/api/user-scoped-routes.ts b/src/api/user-scoped-routes.ts
index 65a80ebf7..b4ccf412c 100644
--- a/src/api/user-scoped-routes.ts
+++ b/src/api/user-scoped-routes.ts
@@ -102,6 +102,7 @@ const USER_SCOPED: Rule[] = [
pat("POST", "/v1/deployments/:id/restore"),
pat("POST", "/v1/deployments/:id/rollback"),
pat("POST", "/v1/deployments/:id/redeploy"),
+ pat("GET", "/v1/deployments/:id/share"),
pat("POST", "/v1/deployments/:id/share"),
pat("GET", "/v1/approvals/:id"),
pat("GET", "/v1/approvals/pending"),
diff --git a/src/deploy/access-token.ts b/src/deploy/access-token.ts
index 922a4ffc6..d231776a5 100644
--- a/src/deploy/access-token.ts
+++ b/src/deploy/access-token.ts
@@ -5,35 +5,6 @@ export function viewerIdentityKey(secret: string, deploymentId: string): string
return createHmac("sha256", secret).update(`viewer:${deploymentId}`).digest("base64url");
}
-export interface DeployOwnerSession {
- kind: "dpl-owner";
- slug: string;
- sub: string;
- version: 1;
- exp: number;
-}
-
-export function mintDeployOwnerToken(
- secret: string,
- session: Omit<DeployOwnerSession, "kind" | "version">,
-): Promise<string> {
- return mintSignedPayload({ ...session, kind: "dpl-owner", version: 1 } satisfies DeployOwnerSession, secret);
-}
-
-export async function verifyDeployOwnerToken(
- secret: string,
- token: string,
- slug: string,
- now = Date.now(),
-): Promise<DeployOwnerSession | null> {
- const session = (await verifySignedPayload(token, secret)) as DeployOwnerSession | null;
- if (!session || session.kind !== "dpl-owner" || session.version !== 1) return null;
- if (typeof session.slug !== "string" || session.slug !== slug) return null;
- if (typeof session.sub !== "string" || !session.sub) return null;
- if (typeof session.exp !== "number" || now >= session.exp) return null;
- return session;
-}
-
export interface DeployGitAccess {
deploymentId: string;
permission: "read" | "write";
diff --git a/src/deploy/app-shell.ts b/src/deploy/app-shell.ts
index 3efc6ed6a..0a2252563 100644
--- a/src/deploy/app-shell.ts
+++ b/src/deploy/app-shell.ts
@@ -4,63 +4,49 @@ function escAttr(value: string): string {
return value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
}
-/**
- * The owner shell: a Claude-artifacts-style top bar over the deployed app, with a
- * slide-out chat column for iterating on it. Served only to a signed-in owner on
- * top-level document loads; the app itself renders untouched inside a same-origin
- * iframe (its sub-resource and iframe requests carry a non-document sec-fetch-dest,
- * so the gateway proxies them straight through).
- */
-export function appShellHtml(opts: { slug: string; portalUrl: string; path: string; accent?: string }): string {
+export function appShellHtml(opts: { slug: string; name?: string; portalUrl: string; path: string }): string {
const slug = escAttr(opts.slug);
const path = escAttr(opts.path);
- const accent = /^[#a-zA-Z0-9(),.% -]{1,64}$/.test(opts.accent ?? "") ? (opts.accent as string) : "#4f46e5";
+ const name = escAttr(opts.name ?? opts.slug);
return `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex">
-<title>${slug}</title>
+<title>${name}</title>
<style>
- /* qm web-ui tokens (mini-lit default theme + shell.css) */
:root {
--background: oklch(1 0 0);
--foreground: oklch(0.145 0 0);
--secondary: oklch(0.97 0 0);
--muted-foreground: oklch(0.556 0 0);
--border: oklch(0.922 0 0);
- --brand-accent: ${accent};
+ --brand-accent: #4f46e5;
--radius-sm: 8px;
--app-font: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
- color-scheme: light dark;
- }
- @media (prefers-color-scheme: dark) {
- :root {
- --background: oklch(0.145 0 0);
- --foreground: oklch(0.985 0 0);
- --secondary: oklch(0.269 0 0);
- --muted-foreground: oklch(0.708 0 0);
- --border: oklch(0.269 0 0);
- }
+ color-scheme: light;
}
html, body { height: 100%; margin: 0; }
body { display: flex; flex-direction: column; font-family: var(--app-font); font-size: 14px; line-height: 1.5;
-webkit-font-smoothing: antialiased; background: var(--background); color: var(--foreground); }
- header { display: flex; align-items: center; gap: 10px; height: 44px; padding: 0 10px 0 16px; flex: none;
+ header { display: flex; align-items: center; gap: 8px; height: 32px; padding: 0 6px 0 12px; flex: none;
box-sizing: border-box; user-select: none;
- border-bottom: 1px solid color-mix(in srgb, var(--border) 68%, transparent);
- background: color-mix(in srgb, var(--background) 94%, var(--secondary)); }
- header .name { font-size: 14px; font-weight: 650; line-height: 1.25; color: var(--foreground);
+ border-bottom: 1px solid var(--border);
+ background: var(--background); }
+ header .name { font-size: 11px; font-weight: 500; line-height: 1.25; color: var(--foreground);
white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
- header .ver { color: var(--muted-foreground); font-size: 12px; line-height: 1.25; padding: 1px 8px;
- border: 1px solid var(--border); border-radius: 999px; }
+ header .ver { display: none; }
header .grow { flex: 1; }
- header button { appearance: none; border: 1px solid var(--border); background: var(--background);
- color: var(--foreground); border-radius: var(--radius-sm); padding: 5px 11px; font: inherit;
- font-size: 13px; cursor: pointer; white-space: nowrap; }
+ header button { appearance: none; border: 0; background: transparent;
+ color: var(--foreground); border-radius: var(--radius-sm); padding: 0 8px; min-height: 24px; font: inherit;
+ font-size: 11px; cursor: pointer; white-space: nowrap; }
header button:hover { background: var(--secondary); }
- header .chat-btn[data-on="1"] { background: var(--brand-accent); border-color: var(--brand-accent); color: #fff; }
+ header .chat-btn { display: inline-flex; align-items: center; gap: 6px; color: var(--muted-foreground); }
+ header .chat-btn svg { width: 14px; height: 14px; fill: none; stroke: currentColor; stroke-width: 1.5; }
+ header .chat-btn[data-on="1"] { color: var(--foreground); }
+ header .chat-btn::after { content: ""; width: 4px; height: 4px; border-radius: 50%; background: currentColor; visibility: hidden; }
+ header .chat-btn[data-on="1"]::after { visibility: visible; }
header .upd { display: none; border-color: color-mix(in srgb, var(--brand-accent) 45%, var(--border));
color: var(--brand-accent); font-weight: 600; }
header .upd.show { display: inline-block; }
@@ -74,51 +60,50 @@ export function appShellHtml(opts: { slug: string; portalUrl: string; path: stri
aside.open { display: flex; }
aside .drag { position: absolute; left: -3px; top: 0; bottom: 0; width: 6px; cursor: col-resize; }
#chat { border: 0; flex: 1; width: 100%; height: 100%; }
- #peek { position: fixed; top: 8px; right: 8px; z-index: 10; display: none; cursor: pointer;
- border: 1px solid var(--border); background: color-mix(in srgb, var(--background) 88%, transparent);
- color: var(--muted-foreground); border-radius: 999px; padding: 3px 11px;
- font-family: var(--app-font); font-size: 12px; }
- #peek:hover { color: var(--foreground); }
+ button:focus-visible, .drag:focus-visible { outline: 2px solid var(--foreground); outline-offset: -2px; }
+ @media (max-width: 640px) {
+ aside { min-width: 0; width: min(100vw, 420px); max-width: 100vw; }
+ body:not(.bare) main:has(aside.open) #app { display: none; }
+ aside.open { flex: 1; }
+ .drag { display: none; }
+ }
body.bare header, body.bare aside { display: none; }
- body.bare #peek { display: block; }
</style>
</head>
<body>
<header>
- <span class="name">${slug}</span>
+ <span class="name" id="name">${name}</span>
<span class="ver" id="ver"></span>
<span class="grow"></span>
<button type="button" class="upd" id="upd">Updated &#8635; Reload</button>
- <button type="button" class="chat-btn" id="chat-toggle">&#10022; Chat</button>
- <button type="button" class="hide-btn" id="hide" title="Hide bar" aria-label="Hide bar">&#10005;</button>
+ <button type="button" class="chat-btn" id="chat-toggle" aria-expanded="false" aria-controls="panel"><svg viewBox="0 0 20 20" aria-hidden="true"><path d="M4 3h12a1 1 0 0 1 1 1v9a1 1 0 0 1-1 1H8l-5 3V4a1 1 0 0 1 1-1Z"/></svg><span>Chat</span></button>
+ <button type="button" class="hide-btn" id="hide" title="Open app without bar" aria-label="Open app without bar">&#10005;</button>
</header>
<main>
<iframe id="app" src="${path}" title="${slug}"></iframe>
- <aside id="panel"><div class="drag" id="drag"></div><iframe id="chat" title="Chat about ${slug}"></iframe></aside>
+ <aside id="panel"><div class="drag" id="drag" role="separator" tabindex="0" aria-label="Resize chat" aria-orientation="vertical"></div><iframe id="chat" title="Chat about ${slug}"></iframe></aside>
</main>
-<button type="button" id="peek">${slug} &#9662;</button>
<script>
(() => {
if (window.top !== window.self) { document.body.className = "bare"; return; }
window.__qmAppShell = true;
- const slug = ${JSON.stringify(opts.slug)};
- const portal = ${JSON.stringify(opts.portalUrl.replace(/\/$/, ""))};
+ const slug = ${JSON.stringify(opts.slug).replace(/</g, "\\u003c")};
+ const portal = ${JSON.stringify(opts.portalUrl.replace(/\/$/, "")).replace(/</g, "\\u003c")};
const app = document.getElementById("app");
const panel = document.getElementById("panel");
const chat = document.getElementById("chat");
const toggle = document.getElementById("chat-toggle");
const upd = document.getElementById("upd");
const verEl = document.getElementById("ver");
- const peek = document.getElementById("peek");
const hide = document.getElementById("hide");
const drag = document.getElementById("drag");
const openKey = "qmChat:" + slug;
- // --- chat panel ---
const setOpen = (on) => {
if (on && !chat.src) chat.src = portal + "/app-edit?slug=" + encodeURIComponent(slug) + "&embed=1";
panel.classList.toggle("open", on);
toggle.dataset.on = on ? "1" : "0";
+ toggle.setAttribute("aria-expanded", String(on));
try { localStorage.setItem(openKey, on ? "1" : "0"); } catch {}
};
toggle.addEventListener("click", () => setOpen(!panel.classList.contains("open")));
@@ -126,7 +111,6 @@ export function appShellHtml(opts: { slug: string; portalUrl: string; path: stri
try { wantOpen = localStorage.getItem(openKey) === "1"; } catch {}
if (wantOpen) setOpen(true);
- // --- panel resize ---
drag.addEventListener("pointerdown", (e) => {
e.preventDefault();
drag.setPointerCapture(e.pointerId);
@@ -138,32 +122,36 @@ export function appShellHtml(opts: { slug: string; portalUrl: string; path: stri
};
drag.addEventListener("pointermove", move);
drag.addEventListener("pointerup", stop, { once: true });
+ drag.addEventListener("pointercancel", stop, { once: true });
});
- // --- hide / peek ---
- hide.addEventListener("click", () => { document.body.className = "bare"; });
- peek.addEventListener("click", () => { document.body.className = ""; });
+ drag.addEventListener("keydown", (event) => {
+ if (!["ArrowLeft", "ArrowRight"].includes(event.key)) return;
+ event.preventDefault();
+ panel.style.width = Math.max(320, panel.offsetWidth + (event.key === "ArrowLeft" ? 20 : -20)) + "px";
+ });
+ hide.addEventListener("click", () => {
+ const target = new URL(location.href);
+ target.searchParams.set("__qm_no_shell", "1");
+ location.assign(target.href);
+ });
- // --- keep the address bar and title in step with the app ---
+ const defaultName = document.getElementById("name").textContent;
let lastHref = null;
const sync = () => {
try {
+ const t = app.contentDocument && app.contentDocument.title;
+ document.getElementById("name").textContent = t || defaultName;
+ document.title = t || defaultName;
const loc = app.contentWindow.location;
if (loc.href === "about:blank" || loc.href === lastHref) return;
lastHref = loc.href;
history.replaceState(null, "", loc.pathname + loc.search + loc.hash);
- const t = app.contentDocument && app.contentDocument.title;
- document.title = t || slug;
} catch {}
};
setInterval(sync, 500);
app.addEventListener("load", sync);
-
- // --- new-version handling ---
- // Chat open = you're iterating and waiting on your own change: reload the app
- // frame automatically (the chat column is untouched, so the thread survives).
- // Chat closed = the update came from elsewhere: offer a pill, never yank the
- // page out from under someone mid-interaction.
+ if (location.hash) app.src += location.hash;
let base = null;
const reloadApp = (v) => {
base = v;
diff --git a/test/agent-api-discovery.test.ts b/test/agent-api-discovery.test.ts
index 869991599..e3dfda62f 100644
--- a/test/agent-api-discovery.test.ts
+++ b/test/agent-api-discovery.test.ts
@@ -193,7 +193,8 @@ test("the catalog IS the gate: discovery rows with real paths are admitted, unli
assert.equal(agentApiMatches("POST", "/v1/deployments/abc/share"), true);
assert.equal(agentApiMatches("GET", "/v1/deployments/abc"), true);
assert.equal(agentApiMatches("POST", "/v1/deployments/abc/restore"), true);
- assert.equal(agentApiMatches("GET", "/v1/deployments/abc/share"), false, "share is POST-only");
+ assert.equal(agentApiMatches("GET", "/v1/deployments/abc/share"), true, "owners can inspect app grants");
+ assert.equal(agentApiMatches("DELETE", "/v1/deployments/abc/share"), false, "app grants use GET and POST");
assert.equal(agentApiMatches("POST", "/v1/share"), true, "the uniform share verb is agent-callable");
assert.equal(agentApiMatches("GET", "/v1/share"), false, "share is POST-only");
assert.equal(agentApiMatches("POST", "/v1/crons"), true);
diff --git a/test/deploy-app-shell.test.ts b/test/deploy-app-shell.test.ts
index b5c2d8639..45b574b39 100644
--- a/test/deploy-app-shell.test.ts
+++ b/test/deploy-app-shell.test.ts
@@ -13,7 +13,7 @@ import { createAclStore } from "../src/acl/acl-store.ts";
import { createDirectoryStore } from "../src/directory/directory-store.ts";
import { createIdentityService } from "../src/identity/identity-service.ts";
import { createMemorySessionStore } from "../src/sessions/memory-session-store.ts";
-import { mintDeployOwnerToken } from "../src/deploy/access-token.ts";
+import { createCanReadScope, createCanWriteScope } from "../src/resolution/scope-membership.ts";
import { createHmac } from "node:crypto";
import { scopeId } from "../src/types.ts";
@@ -24,6 +24,7 @@ const PORTAL = "https://portal.example.com";
function appServingUpstream(upstreamPort: number) {
const deployStore = createDeployStore();
const acl = createAclStore();
+ const directory = createDirectoryStore();
const deploy = createDeployService({
deployStore,
provider: {
@@ -33,16 +34,19 @@ function appServingUpstream(upstreamPort: number) {
},
auditLog,
acl,
+ canReadScope: createCanReadScope({ directory }),
+ canWriteScope: createCanWriteScope({ directory }),
deployDir: mkdtempSync(join(tmpdir(), "app-shell-")),
});
- return createApp({
+ const app = createApp({
deploy,
acl,
- directory: createDirectoryStore(),
+ directory,
sessions: createMemorySessionStore(),
identity: createIdentityService(),
orgId: "acme",
} as unknown as Parameters<typeof createApp>[0]);
+ return { app, directory };
}
function httpGet(
@@ -72,13 +76,14 @@ async function widgetFixture(upstreamHandler?: Parameters<typeof createHttpServe
upstream.listen(0);
await new Promise((r) => upstream.once("listening", r));
const upstreamPort = (upstream.address() as AddressInfo).port;
- const app = appServingUpstream(upstreamPort);
+ const { app, directory } = appServingUpstream(upstreamPort);
const d = await app.deploy({
ownerScopeId: scopeId("personal", "U1"),
createdBy: "U1",
entrypoint: "x",
files: [],
name: "mysite",
+ createdInScope: scopeId("channel", "CBUILT"),
});
await app.shareDeployment(d.id, scopeId("personal", "U-viewer"), "read", { createdBy: "U1" });
const server = createInsecureTestServer(app, {
@@ -93,36 +98,25 @@ async function widgetFixture(upstreamHandler?: Parameters<typeof createHttpServe
await new Promise<void>((resolve) => server.close(() => resolve()));
await new Promise<void>((resolve) => upstream.close(() => resolve()));
};
- return { app, port, close };
+ return { app, directory, port, close };
}
const HOST = "mysite.apps.example.com";
-function mintPortalSession(sub: string): string {
+function mintPortalSession(sub: string, expiresInSeconds = 3600): string {
const key = createHmac("sha256", "portal-session-secret").update("portal.session.v1").digest();
const now = Math.floor(Date.now() / 1000);
- const body = Buffer.from(JSON.stringify({ k: "session", sub, org: "acme", iat: now, exp: now + 3600 })).toString(
- "base64url",
- );
+ const body = Buffer.from(
+ JSON.stringify({ k: "session", sub, org: "acme", iat: now, exp: now + expiresInSeconds }),
+ ).toString("base64url");
return `${body}.${createHmac("sha256", key).update(body).digest("base64url")}`;
}
const viewerCookie = () => `portal_session=${mintPortalSession("U-viewer")}`;
-const ownerToken = (sub: string, expInMs = 60_000) =>
- mintDeployOwnerToken(GATE_SECRET, { slug: "mysite", sub, exp: Date.now() + expInMs });
-
-test("app shell: a valid owner link becomes a host-only cookie and turns on the shell", async () => {
+test("app shell: a normal signed-in manager gets the shell without an edit link", async () => {
const f = await widgetFixture();
try {
- const token = await ownerToken("U1");
- const swallow = await httpGet(f.port, `/?owner=${encodeURIComponent(token)}`, { Host: HOST });
- assert.equal(swallow.status, 302, "the owner token is swallowed into a redirect");
- const setCookie = ([] as string[]).concat(swallow.headers["set-cookie"] as string[] | string).join("\n");
- assert.match(setCookie, /dpl_owner=/, "the owner session lands in a cookie");
- assert.match(setCookie, /HttpOnly/, "the owner cookie is HttpOnly");
- assert.equal(swallow.headers.location, "/", "the redirect drops the token from the URL");
-
const page = await httpGet(f.port, "/", {
Host: HOST,
- Cookie: `dpl_owner=${token}`,
+ Cookie: `portal_session=${mintPortalSession("U1")}`,
"Sec-Fetch-Dest": "document",
});
assert.equal(page.status, 200);
@@ -139,10 +133,9 @@ test("app shell: a valid owner link becomes a host-only cookie and turns on the
test("app shell: the frame's own load (sec-fetch-dest: iframe) proxies the app untouched", async () => {
const f = await widgetFixture();
try {
- const token = await ownerToken("U1");
const page = await httpGet(f.port, "/", {
Host: HOST,
- Cookie: `dpl_owner=${token}`,
+ Cookie: `portal_session=${mintPortalSession("U1")}`,
"Sec-Fetch-Dest": "iframe",
});
assert.equal(page.status, 200);
@@ -155,10 +148,9 @@ test("app shell: the frame's own load (sec-fetch-dest: iframe) proxies the app u
test("app shell: the frame src preserves the requested path and query", async () => {
const f = await widgetFixture();
try {
- const token = await ownerToken("U1");
const page = await httpGet(f.port, "/reports/q3?tab=2", {
Host: HOST,
- Cookie: `dpl_owner=${token}`,
+ Cookie: `portal_session=${mintPortalSession("U1")}`,
"Sec-Fetch-Dest": "document",
});
assert.equal(page.status, 200);
@@ -171,8 +163,7 @@ test("app shell: the frame src preserves the requested path and query", async ()
test("app shell: a client without fetch metadata gets the raw app, never a nested shell", async () => {
const f = await widgetFixture();
try {
- const token = await ownerToken("U1");
- const page = await httpGet(f.port, "/", { Host: HOST, Cookie: `dpl_owner=${token}` });
+ const page = await httpGet(f.port, "/", { Host: HOST, Cookie: `portal_session=${mintPortalSession("U1")}` });
assert.equal(page.status, 200);
assert.equal(page.body, "<html><body>APP</body></html>", "no sec-fetch-dest means a straight proxy");
} finally {
@@ -194,8 +185,10 @@ test("app shell: a plain visitor (granted, signed in) gets untouched HTML and no
test("app shell: the owner version endpoint reports the applied version", async () => {
const f = await widgetFixture();
try {
- const token = await ownerToken("U1");
- const version = await httpGet(f.port, "/__claw__/version", { Host: HOST, Cookie: `dpl_owner=${token}` });
+ const version = await httpGet(f.port, "/__claw__/version", {
+ Host: HOST,
+ Cookie: `portal_session=${mintPortalSession("U1")}`,
+ });
assert.equal(version.status, 200);
assert.equal(JSON.parse(version.body).version, 1, "the applied version is reported");
} finally {
@@ -206,10 +199,9 @@ test("app shell: the owner version endpoint reports the applied version", async
test("app shell: an owner's XHR/fetch HTML fragment is not shelled (sec-fetch-dest gate)", async () => {
const f = await widgetFixture();
try {
- const token = await ownerToken("U1");
const frag = await httpGet(f.port, "/fragment", {
Host: HOST,
- Cookie: `dpl_owner=${token}`,
+ Cookie: `portal_session=${mintPortalSession("U1")}`,
"Sec-Fetch-Dest": "empty",
});
assert.equal(frag.status, 200);
@@ -225,8 +217,11 @@ test("app shell: a 206 partial HTML response streams byte-exact through the fram
res.end("<html></h");
});
try {
- const token = await ownerToken("U1");
- const r = await httpGet(f.port, "/", { Host: HOST, Cookie: `dpl_owner=${token}`, "Sec-Fetch-Dest": "iframe" });
+ const r = await httpGet(f.port, "/", {
+ Host: HOST,
+ Cookie: `portal_session=${mintPortalSession("U1")}`,
+ "Sec-Fetch-Dest": "iframe",
+ });
assert.equal(r.status, 206);
assert.equal(r.body, "<html></h", "a range slice stays byte-exact");
} finally {
@@ -248,32 +243,33 @@ test("app shell: a non-owner request to /__claw__/ falls through to the app, not
}
});
-test("app shell: an owner token for someone who cannot manage the app grants nothing", async () => {
+test("app shell: forged and expired sessions cannot activate the shell", async () => {
const f = await widgetFixture();
try {
- const forged = await ownerToken("U-stranger");
- const swallow = await httpGet(f.port, `/?owner=${encodeURIComponent(forged)}`, { Host: HOST });
- assert.equal(swallow.status, 401, "a non-manager's owner token leaves them an anonymous visitor");
- assert.equal(swallow.headers["set-cookie"], undefined, "no owner cookie for a non-manager");
-
- const page = await httpGet(f.port, "/", {
- Host: HOST,
- Cookie: `dpl_owner=${forged}; ${viewerCookie()}`,
- "Sec-Fetch-Dest": "document",
- });
- assert.equal(page.status, 200, "the visitor's own grant still admits them");
- assert.doesNotMatch(page.body, /__qmAppShell/, "a forged owner cookie raises no shell");
+ for (const token of [mintPortalSession("U1") + "forged", mintPortalSession("U1", -1)]) {
+ const page = await httpGet(f.port, "/", {
+ Host: HOST,
+ Cookie: `portal_session=${token}`,
+ "Sec-Fetch-Dest": "document",
+ });
+ assert.equal(page.status, 401);
+ assert.doesNotMatch(page.body, /__qmAppShell/);
+ }
} finally {
await f.close();
}
});
-test("app shell: an expired owner token is rejected", async () => {
+test("app shell: an old owner cookie cannot override the signed-in viewer", async () => {
const f = await widgetFixture();
try {
- const expired = await ownerToken("U1", -1);
- const page = await httpGet(f.port, "/", { Host: HOST, Cookie: `dpl_owner=${expired}` });
- assert.equal(page.status, 401, "an expired owner session is just an anonymous visitor");
+ const page = await httpGet(f.port, "/", {
+ Host: HOST,
+ Cookie: `dpl_owner=old-token; ${viewerCookie()}`,
+ "Sec-Fetch-Dest": "document",
+ });
+ assert.equal(page.status, 200);
+ assert.doesNotMatch(page.body, /__qmAppShell/);
} finally {
await f.close();
}
@@ -285,8 +281,7 @@ test("app shell: non-HTML responses stream through untouched even for the owner"
res.end('{"data":true}');
});
try {
- const token = await ownerToken("U1");
- const r = await httpGet(f.port, "/api/data", { Host: HOST, Cookie: `dpl_owner=${token}` });
+ const r = await httpGet(f.port, "/api/data", { Host: HOST, Cookie: `portal_session=${mintPortalSession("U1")}` });
assert.equal(r.status, 200);
assert.equal(r.body, '{"data":true}', "JSON is byte-identical");
assert.equal(r.headers["content-length"], "13", "content-length survives the proxy");
@@ -313,17 +308,89 @@ test("app shell: an app cannot plant the owner cookie on its visitors", async ()
}
});
-test("owner-url mint: a manager gets an owner-token link; others are refused", async () => {
+test("app shell: manage grants are checked on every navigation and version request", async () => {
+ const f = await widgetFixture();
+ try {
+ await f.app.shareDeployment("mysite", scopeId("personal", "U-viewer"), "write", { createdBy: "U1" });
+ const page = await httpGet(f.port, "/", { Host: HOST, Cookie: viewerCookie(), "Sec-Fetch-Dest": "document" });
+ assert.match(page.body, /__qmAppShell/);
+ await f.app.shareDeployment("mysite", scopeId("personal", "U-viewer"), "read", { createdBy: "U1" });
+ const revoked = await httpGet(f.port, "/", { Host: HOST, Cookie: viewerCookie(), "Sec-Fetch-Dest": "document" });
+ assert.doesNotMatch(revoked.body, /__qmAppShell/);
+ const version = await httpGet(f.port, "/__claw__/version", { Host: HOST, Cookie: viewerCookie() });
+ assert.equal(version.body, "<html><body>APP</body></html>");
+ } finally {
+ await f.close();
+ }
+});
+
+test("app shell: a manager from the creation scope can load the app and its assets without a read grant", async () => {
const f = await widgetFixture();
try {
- const ok = await httpGet(f.port, "/v1/deployments/mysite/owner-url?principalId=U1", {});
- assert.equal(ok.status, 200);
- const { url } = JSON.parse(ok.body) as { url: string };
- assert.match(url, /^https:\/\/mysite\.apps\.example\.com\/\?owner=/, "the link targets the app's public origin");
- assert.doesNotMatch(url, /access=/, "the owner link carries no piggybacked capability token");
+ await f.directory.replaceChannels(
+ [{ channelId: "CBUILT", name: "builders", isPrivate: true }],
+ [{ channelId: "CBUILT", principalId: "U2" }],
+ );
+ assert.equal(await f.app.canManageDeployment("mysite", "U2"), true);
+ assert.equal((await f.app.reachDeployment("mysite", "U2")).status, "denied");
+ const headers = { Host: HOST, Cookie: `portal_session=${mintPortalSession("U2")}` };
+ const page = await httpGet(f.port, "/", { ...headers, "Sec-Fetch-Dest": "document" });
+ assert.match(page.body, /__qmAppShell/);
+ for (const dest of ["iframe", "script", "empty"]) {
+ const resource = await httpGet(f.port, "/asset", { ...headers, "Sec-Fetch-Dest": dest });
+ assert.equal(resource.status, 200);
+ assert.equal(resource.body, "<html><body>APP</body></html>");
+ }
+ await f.directory.replaceChannels([{ channelId: "CBUILT", name: "builders", isPrivate: true }], []);
+ const denied = await httpGet(f.port, "/", headers);
+ assert.equal(denied.status, 403);
+ } finally {
+ await f.close();
+ }
+});
- const denied = await httpGet(f.port, "/v1/deployments/mysite/owner-url?principalId=U-stranger", {});
- assert.equal(denied.status, 403, "a non-manager cannot mint an owner link");
+test("app shell: normal sign-in keeps editing available beyond the old five-minute window", async (t) => {
+ t.mock.timers.enable({ apis: ["Date"] });
+ const f = await widgetFixture();
+ try {
+ const headers = { Host: HOST, Cookie: `portal_session=${mintPortalSession("U1")}`, "Sec-Fetch-Dest": "document" };
+ const first = await httpGet(f.port, "/", headers);
+ assert.match(first.body, /__qmAppShell/);
+ t.mock.timers.tick(6 * 60 * 1000);
+ const later = await httpGet(f.port, "/reports?view=week", headers);
+ assert.equal(later.status, 200);
+ assert.match(later.body, /__qmAppShell/);
+ const version = await httpGet(f.port, "/__claw__/version", headers);
+ assert.equal(JSON.parse(version.body).version, 1);
+ t.mock.timers.tick(60 * 60 * 1000);
+ assert.equal((await httpGet(f.port, "/", headers)).status, 401);
+ } finally {
+ await f.close();
+ }
+});
+
+test("app shell: bare escape renders frame-denying apps at top level without forwarding the shell parameter", async () => {
+ let appRequestPath: string | undefined;
+ const f = await widgetFixture((req, res) => {
+ appRequestPath = req.url;
+ res.writeHead(200, {
+ "content-type": "text/html",
+ "x-frame-options": "DENY",
+ "content-security-policy": "frame-ancestors 'none'",
+ });
+ res.end("APP");
+ });
+ try {
+ const page = await httpGet(f.port, "/?__qm_no_shell=1&filter=recent", {
+ Host: HOST,
+ Cookie: `portal_session=${mintPortalSession("U1")}`,
+ "sec-fetch-dest": "document",
+ });
+ assert.equal(page.status, 200);
+ assert.equal(page.body, "APP");
+ assert.equal(appRequestPath, "/?filter=recent");
+ assert.equal(page.headers["x-frame-options"], "DENY");
+ assert.equal(page.headers["content-security-policy"], "frame-ancestors 'none'");
} finally {
await f.close();
}
diff --git a/test/deploy-path-serving.test.ts b/test/deploy-path-serving.test.ts
index e4b4af9c9..31e016d10 100644
--- a/test/deploy-path-serving.test.ts
+++ b/test/deploy-path-serving.test.ts
@@ -168,16 +168,3 @@ test("without a subdomain configuration /d/ document navigations proxy in place"
await f.close();
}
});
-
-test("owner-url without a subdomain configuration explains the /d/ path and the enabling env var", async () => {
- const f = await fixture({});
- try {
- const r = await httpGet(f.port, "/v1/deployments/mysite/[email protected]", {});
- assert.equal(r.status, 503);
- const { message } = JSON.parse(r.body) as { message: string };
- assert.match(message, /\/d\/mysite\//);
- assert.match(message, /DEPLOY_APPS_DOMAIN/);
- } finally {
- await f.close();
- }
-});
diff --git a/test/share-deployment.test.ts b/test/share-deployment.test.ts
index ac45bc26c..d94afead0 100644
--- a/test/share-deployment.test.ts
+++ b/test/share-deployment.test.ts
@@ -16,6 +16,7 @@ import {
archiveDeployment,
restoreDeployment,
getDeployment,
+ getDeploymentShares,
setDeploymentDisplayName,
} from "../src/api/routes/deployments.ts";
import type { ApiCtx } from "../src/api/routes/route.ts";
@@ -477,3 +478,23 @@ test("transferDeploymentOwner to the current home is a no-op", async () => {
assert.equal(after.ownerScopeId, scopeId("personal", "U1"));
assert.equal((await acl.list()).length, 0, "no self-grant sprayed by a no-op transfer");
});
+
+test("deployment permissions are visible only to the owner, including for managers", async () => {
+ const { app } = apiHarness();
+ await app.deploy({
+ ownerScopeId: scopeId("personal", "U1"),
+ createdBy: "U1",
+ entrypoint: "x",
+ files: [],
+ name: "permissions",
+ });
+ await callShare(app, cap("U1"), "permissions", { scope: "personal:U2", access: "manage" });
+ const owner = await callManage(getDeploymentShares, app, cap("U1"), "permissions", {});
+ assert.equal(owner.status, 200);
+ assert.deepEqual(owner.body.grantees, [{ scope: "personal:U2", permission: "write" }]);
+ assert.equal((await callManage(getDeploymentShares, app, cap("U2"), "permissions", {})).status, 403);
+ assert.equal((await callManage(getDeploymentShares, app, null, "permissions", {})).status, 403);
+ assert.equal((await callManage(getDeploymentShares, app, cap("U1"), "missing", {})).status, 404);
+ await callShare(app, cap("U1"), "permissions", { scope: "personal:U2", access: "none" });
+ assert.deepEqual((await callManage(getDeploymentShares, app, cap("U1"), "permissions", {})).body.grantees, []);
+});