From fb4da63818dc562b53b41430eb34bd1d48eb5cfb Mon Sep 17 00:00:00 2001 From: Dan Smolsky <78942835+Tarquinen@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:12:15 -0500 Subject: [PATCH] feat(core): send question, answer, error and permission details in push data (#66451) --- packages/core/src/push/sender.ts | 190 +++++++++++++++---- packages/core/src/push/watcher.ts | 138 +++++++++++--- packages/core/test/push-sender.test.ts | 91 ++++++++-- packages/core/test/push-watcher.test.ts | 183 ++++++++++++++++--- packages/server/test/push-routes.test.ts | 10 +- specs/v2/README.md | 1 + specs/v2/push.md | 221 +++++++++++++++++++++++ 7 files changed, 737 insertions(+), 97 deletions(-) create mode 100644 specs/v2/push.md diff --git a/packages/core/src/push/sender.ts b/packages/core/src/push/sender.ts index d15b3c5bf8e..e9bb3c707bc 100644 --- a/packages/core/src/push/sender.ts +++ b/packages/core/src/push/sender.ts @@ -9,15 +9,72 @@ import { KV } from "../kv.js" import { PushCrypto } from "./crypto.js" import { PushList } from "./list.js" +/** A reply sends `value`, or `label` when there is no value. */ +export interface Choice { + readonly label: string + readonly value?: string + readonly description?: string +} + +/** One field of a form, under the form's own key names. */ +export interface Field { + readonly key: string + readonly type: string + readonly title?: string + readonly description?: string + /** True when a typed answer is accepted. */ + readonly custom?: true + readonly options?: ReadonlyArray +} + +export interface Data { + readonly requestID?: string + readonly formID?: string + /** The session that asked, which replies name; it may be a subagent's. */ + readonly replySessionID?: string + readonly action?: string + readonly resources?: ReadonlyArray + /** How many resources the request has, when some were left out. */ + readonly resourceCount?: number + readonly save?: ReadonlyArray + readonly decisions?: ReadonlyArray + readonly message?: string + readonly source?: { readonly type: "tool"; readonly messageID: string; readonly id: string } + readonly kind?: string + readonly fieldCount?: number + /** A reply can be built from the message alone. Left out as soon as the message is too big. */ + readonly inlineReply?: true + /** The form's first field. */ + readonly fields?: ReadonlyArray + readonly outcome?: "succeeded" | "failed" + readonly messageID?: string + readonly idleMessageID?: string + readonly text?: string + readonly error?: { + readonly type: string + readonly message?: string + readonly status?: number + readonly retryAfterMs?: number + } + /** How many background jobs are still running under the session, by kind. */ + readonly background?: Readonly> + /** Something in `data` was cut or left out; the full version can be read by id. */ + readonly truncated?: true +} + export interface Notification { /** What a later `clear` names: the permission request, the form, or the session for a finished turn. */ readonly id: string - readonly type: "session.idle" | "question" | "permission" + readonly type: "turn" | "form" | "permission" + /** The top-level session, and the folder it works in. */ readonly sessionID: string + readonly directory: string + /** When the event happened, in ms since the epoch. */ + readonly time: number readonly title: string readonly body: string - readonly data: Record> - /** True when the notification needs the person, so phones at level `attention` get it. */ + readonly data: Data + /** True when the session waits on the person, so phones at level `attention` get it. */ readonly attention: boolean } @@ -25,14 +82,15 @@ export interface Interface { /** Sends to every phone that wants it, in the background. */ readonly send: (notification: Notification) => Effect.Effect /** Removes the notifications sent under these ids from the phones that got them, in the background. */ - readonly clear: (ids: ReadonlyArray) => Effect.Effect + readonly clear: (ids: ReadonlyArray, time: number) => Effect.Effect /** Removes every notification sent for this top-level session, for when the session is deleted. */ - readonly clearSession: (sessionID: string) => Effect.Effect + readonly clearSession: (sessionID: string, time: number) => Effect.Effect } export class Service extends Context.Service()("@opencode/PushSender") {} const maxMessageBytes = 2600 +const maxBodyChars = 200 const attempts = 3 // Which phones were sent a notification, so a clear goes only to them. const Sent = Schema.Struct({ sessionID: Schema.String, devices: Schema.Array(Schema.String) }) @@ -40,48 +98,112 @@ const decodeSent = Schema.decodeUnknownOption(Sent) const sentKey = (id: string) => `push:sent:${id}` const sentPrefix = "push:sent:" -/** Drops characters from the end of `text` until its JSON is at least `bytes` shorter, then adds "…". */ +/** + * Drops characters from the end of `text` until its JSON is at least `bytes` shorter, then adds "…". Undefined when + * nothing is left. + */ const shorten = (text: string, bytes: number) => { const chars = Array.from(text) let dropped = 0 while (chars.length > 0 && dropped < bytes + 3) { dropped += Buffer.byteLength(JSON.stringify(chars.pop()), "utf8") - 2 } + if (chars.length === 0) return undefined return chars.join("") + "…" } +type Over = (data: Data) => number +/** One cut, applied while the message is still too big. */ +type Step = (data: Data, over: Over) => Data + +/** Keeps resources in order while they fit. The first that doesn't is shortened if that fits, and the rest are dropped. */ +const cutResources: Step = (data, over) => { + const all = data.resources + if (!all) return data + const cut = (kept: ReadonlyArray): Data => ({ + ...data, + resources: kept, + ...(kept.length < all.length && { resourceCount: all.length }), + truncated: true, + }) + const kept: string[] = [] + for (const item of all) { + const bytes = over(cut([...kept, item])) + if (bytes > 0) { + const short = shorten(item, bytes) + return cut(short === undefined ? kept : [...kept, short]) + } + kept.push(item) + } + return cut(kept) +} + +/** A cut to the form's field. `change` returns undefined when it has nothing to cut. */ +const cutField = + (change: (field: Field, over: (field: Field) => number) => Field | undefined): Step => + (data, over) => { + const [field] = data.fields ?? [] + const cut = (field: Field): Data => ({ ...data, fields: [field], truncated: true }) + const next = field && change(field, (field) => over(cut(field))) + return next ? cut(next) : data + } + +// In the order of specs/v2/push.md: bulk goes before small facts. +const steps: ReadonlyArray = [ + (data) => (data.inlineReply ? { ...data, inlineReply: undefined, truncated: true } : data), + (data) => (data.text === undefined ? data : { ...data, text: undefined, truncated: true }), + (data, over) => { + if (data.error?.message === undefined) return data + const marked: Data = { ...data, truncated: true } + return { ...marked, error: { ...data.error, message: shorten(data.error.message, over(marked)) } } + }, + cutResources, + cutField((field) => + field.options?.some((option) => option.description !== undefined) + ? { ...field, options: field.options.map((option) => ({ label: option.label, value: option.value })) } + : undefined, + ), + cutField((field, over) => + field.description === undefined ? undefined : { ...field, description: shorten(field.description, over(field)) }, + ), +] + /** - * The JSON the phone decrypts, shortened so the box stays within the relay's limit. Only a question's body and a - * permission's `data.resources` can be long. Cut resources keep their order and come with `truncated: "true"`. + * The JSON the phone decrypts, cut so the box stays within the relay's limit. Anything cut or left out of `data` sets + * `truncated: true`. Ids, the title and the body are never cut. The format is described in specs/v2/push.md. */ export const message = (notification: Notification) => { - const make = (body: string, data = notification.data) => + const chars = Array.from(notification.body) + const body = chars.length > maxBodyChars ? chars.slice(0, maxBodyChars - 1).join("") + "…" : notification.body + const make = (data: Data, directory?: string) => JSON.stringify({ v: 1, - id: notification.id, type: notification.type, + id: notification.id, + time: notification.time, sessionID: notification.sessionID, + directory, + ...(notification.attention && { attention: true }), title: notification.title, body, data, }) - const over = (text: string) => Buffer.byteLength(text, "utf8") - maxMessageBytes - const whole = make(notification.body) - if (over(whole) <= 0) return whole - const resources = notification.data.resources - if (!Array.isArray(resources)) return make(shorten(notification.body, over(whole))) - const cut = (kept: ReadonlyArray) => - make(notification.body, { ...notification.data, resources: kept, truncated: "true" }) - const kept: string[] = [] - for (const resource of resources) { - const next = cut([...kept, resource]) - if (over(next) > 0) { - const short = cut([...kept, shorten(resource, over(next))]) - return over(short) > 0 ? cut(kept) : short - } - kept.push(resource) - } - return cut(kept) + const over: Over = (data) => Buffer.byteLength(make(data, notification.directory), "utf8") - maxMessageBytes + const data = steps.reduce((data, step) => (over(data) > 0 ? step(data, over) : data), notification.data) + if (over(data) <= 0) return make(data, notification.directory) + return make({ + requestID: data.requestID, + formID: data.formID, + replySessionID: data.replySessionID, + kind: data.kind, + fieldCount: data.fieldCount, + decisions: data.decisions, + outcome: data.outcome, + messageID: data.messageID, + idleMessageID: data.idleMessageID, + background: data.background, + truncated: true, + }) } export const level = (device: PushList.Stored, sessions: Record, sessionID: string) => @@ -151,7 +273,7 @@ const layer = Layer.effect( ) }) - const clear = Effect.fn("PushSender.clear")(function* (ids: ReadonlyArray) { + const clear = Effect.fn("PushSender.clear")(function* (ids: ReadonlyArray, time: number) { const cleared: (typeof Sent.Type & { id: string })[] = [] for (const id of ids) { const sent = yield* getSent(id) @@ -164,16 +286,14 @@ const layer = Layer.effect( cleared.flatMap((item) => targets.devices .filter((device) => item.devices.includes(device.id)) - .map((device) => - push(device, JSON.stringify({ v: 1, id: item.id, type: "clear", sessionID: item.sessionID }), true), - ), + .map((device) => push(device, JSON.stringify({ v: 1, type: "clear", ids: [item.id], time }), true)), ), Effect.ignoreCause({ log: "Warn", message: "Failed to clear a push notification" }), { concurrency: "unbounded", discard: true }, ) }) - const clearSession = Effect.fn("PushSender.clearSession")(function* (sessionID: string) { + const clearSession = Effect.fn("PushSender.clearSession")(function* (sessionID: string, time: number) { const ids: string[] = [] let after: string | undefined while (true) { @@ -185,13 +305,13 @@ const layer = Layer.effect( if (!page.next) break after = page.next } - yield* clear(ids) + yield* clear(ids, time) }) return Service.of({ send: (notification) => deliver(notification).pipe(Effect.forkIn(scope), Effect.asVoid), - clear: (ids) => clear(ids).pipe(Effect.forkIn(scope), Effect.asVoid), - clearSession: (sessionID) => clearSession(sessionID).pipe(Effect.forkIn(scope), Effect.asVoid), + clear: (ids, time) => clear(ids, time).pipe(Effect.forkIn(scope), Effect.asVoid), + clearSession: (sessionID, time) => clearSession(sessionID, time).pipe(Effect.forkIn(scope), Effect.asVoid), }) }), ) diff --git a/packages/core/src/push/watcher.ts b/packages/core/src/push/watcher.ts index 459b40049e6..84c3512abb5 100644 --- a/packages/core/src/push/watcher.ts +++ b/packages/core/src/push/watcher.ts @@ -3,10 +3,14 @@ export * as PushWatcher from "./watcher.js" import { Effect, Layer, Option, Schema, Stream } from "effect" import { Form } from "@opencode/schema/form" import { Permission } from "@opencode/schema/permission" +import { SessionError } from "@opencode/schema/session-error" import { SessionEvent } from "@opencode/schema/session-event" +import { SessionMessage } from "@opencode/schema/session-message" import { makeGlobalNode } from "@opencode/util/effect/app-node" import { Bus } from "../bus.js" +import { Job } from "../job.js" import { Session } from "../session.js" +import { SessionBackground } from "../session/background.js" import { PushList } from "./list.js" import { PushSender } from "./sender.js" @@ -19,10 +23,14 @@ const bodies = { failed: "Failed", } +// The tool call a question form was asked from, as the question tool records it. +const Tool = Schema.Struct({ messageID: Schema.String, id: Schema.String }) + const layer = Layer.effectDiscard( Effect.gen(function* () { const bus = yield* Bus.Service const sessions = yield* Session.Service + const jobs = yield* Job.Service const list = yield* PushList.Service const sender = yield* PushSender.Service const stepped = new Set() @@ -36,41 +44,117 @@ const layer = Layer.effectDiscard( return session }) - const finished = Effect.fn("PushWatcher.finished")(function* (sessionID: Session.ID, outcome: keyof typeof bodies) { + const finished = Effect.fn("PushWatcher.finished")(function* ( + sessionID: Session.ID, + outcome: keyof typeof bodies, + ran: boolean, + time: number, + idleMessageID: SessionMessage.ID, + error?: SessionError.Error, + ) { if (!(yield* list.hasDevices())) return const session = yield* sessions.get(sessionID) if (session.parentID) return + // A running subagent's report starts another turn, so this one isn't the last. Running shells don't hold the + // push, or a session with a dev server running would never send one. + const running = yield* SessionBackground.outstanding( + jobs, + { get: (id) => sessions.get(id).pipe(Effect.option, Effect.map(Option.getOrUndefined)) }, + sessionID, + yield* sessions.active, + ) + if (outcome === "succeeded" && running.some((job) => job.kind === "subagent" && job.sessionID === sessionID)) + return + const background = running.reduce>( + (counts, job) => ({ ...counts, [job.kind]: (counts[job.kind] ?? 0) + 1 }), + {}, + ) + // The newest assistant message is the turn's last step, so only read it when this turn ran one. + const [last] = ran ? yield* sessions.messages({ sessionID, type: "assistant", order: "desc", limit: 1 }) : [] + const text = Array.from( + (last?.type === "assistant" ? last.content : []) + .flatMap((part) => (part.type === "text" ? [part.text] : [])) + .join("\n") + .trim(), + ) + .slice(-500) + .join("") yield* sender.send({ id: sessionID, - type: "session.idle", + type: "turn", sessionID, + directory: session.location.directory, + time, title: session.title || "OpenCode", body: bodies[outcome], - data: { outcome }, + data: { + outcome, + ...(last && { messageID: last.id }), + idleMessageID, + ...(text && { text }), + ...(error && { + error: { + type: error.type, + message: error.message || undefined, + status: error.status, + retryAfterMs: error.retryAfterMs, + }, + }), + ...(running.length > 0 && { background }), + }, attention: false, }) }) - const question = Effect.fn("PushWatcher.question")(function* (form: Form.Info) { - if (form.metadata?.kind !== "question") return + const question = Effect.fn("PushWatcher.question")(function* (form: Form.Info, time: number) { + const kind = form.metadata?.kind + if (kind !== "question") return const sessionID = Schema.decodeUnknownOption(Session.ID)(form.sessionID) if (Option.isNone(sessionID)) return if (!(yield* list.hasDevices())) return const session = yield* topLevel(sessionID.value) const field = form.fields[0] + const choices = field.type === "string" || field.type === "multiselect" ? field : undefined + const options = choices?.options ?? [] + const tool = Schema.decodeUnknownOption(Tool)(form.metadata?.tool) yield* sender.send({ id: form.id, - type: "question", + type: "form", sessionID: session.id, + directory: session.location.directory, + time, title: session.title || "OpenCode", body: field.description || field.title || form.title, // The top-level session is the one to open and the one bells apply to; the form belongs to this one. - data: { formID: form.id, sessionID: sessionID.value }, + data: { + formID: form.id, + replySessionID: sessionID.value, + kind, + fieldCount: form.fields.length, + ...(choices && form.fields.length === 1 && { inlineReply: true }), + ...(Option.isSome(tool) && { source: { type: "tool", ...tool.value } }), + fields: [ + { + key: field.key, + type: field.type, + ...(field.title && { title: field.title }), + ...(field.description && { description: field.description }), + ...(choices?.custom && { custom: true }), + ...(options.length > 0 && { + options: options.map((option) => ({ + label: option.label, + ...(option.value !== option.label && { value: option.value }), + ...(option.description && { description: option.description }), + })), + }), + }, + ], + }, attention: true, }) }) - const permission = Effect.fn("PushWatcher.permission")(function* (request: Permission.Request) { + const permission = Effect.fn("PushWatcher.permission")(function* (request: Permission.Request, time: number) { if (!(yield* list.hasDevices())) return const session = yield* topLevel(request.sessionID) asking.set(request.sessionID, (asking.get(request.sessionID) ?? new Set()).add(request.id)) @@ -78,14 +162,20 @@ const layer = Layer.effectDiscard( id: request.id, type: "permission", sessionID: session.id, + directory: session.location.directory, + time, title: session.title || "OpenCode", body: `Needs permission: ${request.action}`, // A reply has to name the session that asked, which may be a subagent's. data: { requestID: request.id, - sessionID: request.sessionID, + replySessionID: request.sessionID, action: request.action, resources: request.resources, + ...(request.save?.length && { save: request.save }), + decisions: request.save?.length ? ["once", "always", "reject"] : ["once", "reject"], + message: request.message, + source: request.source, }, attention: true, }) @@ -93,7 +183,10 @@ const layer = Layer.effectDiscard( yield* bus.subscribe([Form.Event.Created, Permission.Event.Asked]).pipe( Stream.runForEach((event) => { - const notify = event.type === "form.created" ? question(event.data.form) : permission(event.data) + const notify = + event.type === "form.created" + ? question(event.data.form, event.created) + : permission(event.data, event.created) return notify.pipe(Effect.ignoreCause({ log: "Warn", message: "Failed to notify phones" })) }), Effect.forkScoped({ startImmediately: true }), @@ -113,23 +206,23 @@ const layer = Layer.effectDiscard( ]) .pipe( Stream.runForEach((event) => { - if (event.type === "session.archived") return sender.clearSession(event.data.sessionID) + if (event.type === "session.archived") return sender.clearSession(event.data.sessionID, event.created) if (event.type === "session.deleted") { stepped.delete(event.data.sessionID) asking.delete(event.data.sessionID) - return sender.clearSession(event.data.sessionID) + return sender.clearSession(event.data.sessionID, event.created) } if (event.type === "permission.replied") { asking.get(event.data.sessionID)?.delete(event.data.requestID) - return sender.clear([event.data.requestID]) + return sender.clear([event.data.requestID], event.created) } if (event.type === "session.viewed") { if (event.created - event.data.idle < viewedAfter) return Effect.void - return sender.clear([event.data.sessionID]) + return sender.clear([event.data.sessionID], event.created) } - if (event.type !== "session.inbox.enqueued") return sender.clear([event.data.id]) + if (event.type !== "session.inbox.enqueued") return sender.clear([event.data.id], event.created) if (event.data.item.type !== "user") return Effect.void - return sender.clear([event.data.sessionID]) + return sender.clear([event.data.sessionID], event.created) }), Effect.forkScoped({ startImmediately: true }), ) @@ -152,13 +245,16 @@ const layer = Layer.effectDiscard( const ran = stepped.delete(sessionID) const unanswered = Array.from(asking.get(sessionID) ?? []) asking.delete(sessionID) - if (event.type === "session.execution.interrupted") return sender.clear(unanswered) - if (event.type === "session.execution.succeeded" && !ran) return sender.clear(unanswered) + if (event.type === "session.execution.interrupted") return sender.clear(unanswered, event.created) + if (event.type === "session.execution.succeeded" && !ran) return sender.clear(unanswered, event.created) const outcome = event.type === "session.execution.succeeded" ? "succeeded" : "failed" + const error = event.type === "session.execution.failed" ? event.data.error : undefined return sender - .clear(unanswered) + .clear(unanswered, event.created) .pipe( - Effect.andThen(finished(sessionID, outcome)), + Effect.andThen( + finished(sessionID, outcome, ran, event.created, SessionMessage.ID.fromEvent(event.id), error), + ), Effect.ignoreCause({ log: "Warn", message: "Failed to notify phones" }), ) }), @@ -170,5 +266,5 @@ const layer = Layer.effectDiscard( export const node = makeGlobalNode({ name: "push-watcher", layer, - deps: [Bus.node, PushList.node, PushSender.node, Session.node], + deps: [Bus.node, Job.node, PushList.node, PushSender.node, Session.node], }) diff --git a/packages/core/test/push-sender.test.ts b/packages/core/test/push-sender.test.ts index 225838840c4..cf45eb48d3b 100644 --- a/packages/core/test/push-sender.test.ts +++ b/packages/core/test/push-sender.test.ts @@ -45,8 +45,10 @@ const sessionID = Session.ID.make("ses_push_sender") const finished: PushSender.Notification = { id: sessionID, - type: "session.idle", + type: "turn", sessionID, + directory: "/home/me/shop", + time: 1_000, title: "Fix the login bug", body: "Finished", data: { outcome: "succeeded" }, @@ -55,8 +57,10 @@ const finished: PushSender.Notification = { const question: PushSender.Notification = { id: "frm_1", - type: "question", + type: "form", sessionID, + directory: "/home/me/shop", + time: 1_000, title: "Fix the login bug", body: "Which database?", data: { formID: "frm_1" }, @@ -149,9 +153,11 @@ describe("PushSender", () => { expect(delivered!.silent).toBeUndefined() expect(open(ok, delivered!.box)).toEqual({ v: 1, + type: "turn", id: sessionID, - type: "session.idle", + time: 1_000, sessionID, + directory: "/home/me/shop", title: "Fix the login bug", body: "Finished", data: { outcome: "succeeded" }, @@ -192,55 +198,112 @@ describe("PushSender", () => { const ok = yield* phone(ids.ok, "ok") yield* phone(ids.quiet, "quiet", { default: "attention" }) - yield* sender.clear([sessionID]) + yield* sender.clear([sessionID], 2_000) yield* drain expect(calls).toEqual([]) yield* sender.send(finished) yield* advance(() => calls.length === 1) - yield* sender.clear([sessionID, "frm_unknown"]) + yield* sender.clear([sessionID, "frm_unknown"], 2_000) yield* advance(() => calls.length === 2) - yield* sender.clear([sessionID]) + yield* sender.clear([sessionID], 2_000) yield* drain expect(calls.map((call) => [call.path.split("/").pop(), call.silent])).toEqual([ ["ok", undefined], ["ok", true], ]) - expect(open(ok, calls[1]!.box)).toEqual({ v: 1, id: sessionID, type: "clear", sessionID }) + expect(open(ok, calls[1]!.box)).toEqual({ v: 1, type: "clear", ids: [sessionID], time: 2_000 }) }), ) - it.effect("shortens a long body or resource list so the box fits the relay", () => + it.effect("cuts bulk before small facts so the box fits the relay", () => Effect.sync(() => { for (const body of ["é".repeat(5_000), "漢".repeat(1_500), "\n".repeat(3_000)]) { const text = PushSender.message({ ...question, body }) expect(Buffer.byteLength(text, "utf8")).toBeLessThanOrEqual(2600) - expect(Buffer.byteLength(text, "utf8")).toBeGreaterThan(2580) - expect(JSON.parse(text).body.endsWith("…")).toBe(true) + expect(JSON.parse(text).body).toBe(body.slice(0, 199) + "…") + } + const data = { + requestID: "per_1", + replySessionID: sessionID, + action: "shell", + resources: ["git push", "x".repeat(5_000), "ls"], + save: ["git push *"], + decisions: ["once", "always", "reject"], } - const data = { requestID: "per_1", sessionID, action: "shell", resources: ["git push", "x".repeat(5_000), "ls"] } const text = PushSender.message({ ...question, type: "permission", body: "Needs permission: shell", data }) expect(Buffer.byteLength(text, "utf8")).toBeLessThanOrEqual(2600) expect(Buffer.byteLength(text, "utf8")).toBeGreaterThan(2580) expect(JSON.parse(text).data).toEqual({ ...data, resources: ["git push", expect.stringMatching(/^x+…$/)], - truncated: "true", + resourceCount: 3, + truncated: true, }) const many = PushSender.message({ ...question, type: "permission", - data: { ...data, resources: Array.from({ length: 3000 }, (_, i) => "cmd" + i) }, + data: { ...data, resources: Array.from({ length: 300 }, (_, i) => "mkdir -p src/dir" + i) }, }) expect(Buffer.byteLength(many, "utf8")).toBeLessThanOrEqual(2600) expect(JSON.parse(many).data.resources).not.toContain("…") + expect(JSON.parse(many).data.resourceCount).toBe(300) + const options = [{ label: "A" }, { label: "abcd", value: "b" }, { label: "Z".repeat(100) }] + const described = options.map((option) => ({ ...option, description: "An option" })) + const field = { key: "q0", type: "string", description: "b".repeat(3_000), options: described } + const cut = PushSender.message({ ...question, data: { formID: "frm_1", inlineReply: true, fields: [field] } }) + expect(Buffer.byteLength(cut, "utf8")).toBeLessThanOrEqual(2600) + expect(JSON.parse(cut).data).toEqual({ + formID: "frm_1", + fields: [{ key: "q0", type: "string", description: expect.stringMatching(/^b+…$/), options }], + truncated: true, + }) + // More options than fit: only the ids and small facts go out, and the app fetches the form. + const paths = Array.from({ length: 100 }, (_, i) => ({ label: "src/components/feature-" + i + "/index.tsx" })) + const most = PushSender.message({ + ...question, + data: { + formID: "frm_1", + replySessionID: sessionID, + kind: "question", + fieldCount: 1, + inlineReply: true, + fields: [{ key: "q0", type: "string", options: paths }], + }, + }) + expect(JSON.parse(most)).toEqual({ + v: 1, + type: "form", + id: question.id, + time: 1_000, + sessionID, + attention: true, + title: question.title, + body: question.body, + data: { formID: "frm_1", replySessionID: sessionID, kind: "question", fieldCount: 1, truncated: true }, + }) + const error = { type: "provider.rate-limit", message: "e".repeat(3_000), status: 429, retryAfterMs: 30_000 } + const failed = PushSender.message({ + ...finished, + body: "Failed", + data: { outcome: "failed", text: "a".repeat(500), error }, + }) + expect(Buffer.byteLength(failed, "utf8")).toBeLessThanOrEqual(2600) + expect(JSON.parse(failed).data).toEqual({ + outcome: "failed", + error: { ...error, message: expect.stringMatching(/^e+…$/) }, + truncated: true, + }) expect(PushSender.message(question)).toBe( JSON.stringify({ v: 1, + type: "form", id: question.id, - type: "question", + time: 1_000, sessionID, + directory: question.directory, + attention: true, title: question.title, body: question.body, data: question.data, diff --git a/packages/core/test/push-watcher.test.ts b/packages/core/test/push-watcher.test.ts index 9baa3f9622c..45ef43ff324 100644 --- a/packages/core/test/push-watcher.test.ts +++ b/packages/core/test/push-watcher.test.ts @@ -3,6 +3,8 @@ import { createECDH, createDecipheriv, hkdfSync } from "node:crypto" import { DateTime, Effect, Layer } from "effect" import { Agent } from "@opencode/core/agent" import { Bus } from "@opencode/core/bus" +import { Job } from "@opencode/core/job" +import type { Recovery } from "@opencode/core/job/recovery" import { KV } from "@opencode/core/kv" import { Location } from "@opencode/core/location" import { Model } from "@opencode/core/model" @@ -27,6 +29,8 @@ import { waitUntil } from "./lib/eventually" let boxes: string[] = [] let silent: unknown[] = [] +let active = new Set() +let background: Recovery[] = [] const relay = async (input: Request | string | URL, init?: RequestInit) => { const text = input instanceof Request ? await input.text() : String(init?.body) @@ -39,6 +43,7 @@ const relay = async (input: Request | string | URL, init?: RequestInit) => { const parentID = Session.ID.make("ses_push_parent") const childID = Session.ID.make("ses_push_child") const grandchildID = Session.ID.make("ses_push_grandchild") +const messageID = SessionMessage.ID.create() const session = (id: Session.ID, title: string, parent?: Session.ID) => Session.Info.make({ @@ -65,6 +70,21 @@ const it = testEffect( Session.node.replace( Layer.mock(Session.Service, { get: (id) => Effect.succeed(sessions.get(id)!), + active: Effect.sync(() => active), + messages: () => + Effect.succeed([ + SessionMessage.Assistant.make({ + id: messageID, + type: "assistant", + agent: Agent.ID.make("build"), + model: Model.Ref.make({ id: Model.ID.make("model"), providerID: Provider.ID.make("provider") }), + content: [ + { type: "reasoning", text: "Check the session code", time: { created: DateTime.makeUnsafe(0) } }, + { type: "text", text: "Fixed the login bug." }, + ], + time: { created: DateTime.makeUnsafe(0) }, + }), + ]), revert: { stage: () => Effect.die(new Error("unused")), clear: () => Effect.die(new Error("unused")), @@ -72,6 +92,12 @@ const it = testEffect( }, }), ), + Job.node.replace( + Layer.mock(Job.Service, { + get: () => Effect.succeed(undefined), + runningBackground: Effect.sync(() => background), + }), + ), ], }), ) @@ -118,6 +144,8 @@ const step = (sessionID: Session.ID) => beforeEach(() => { boxes = [] silent = [] + active = new Set() + background = [] }) describe("PushWatcher", () => { @@ -133,37 +161,79 @@ describe("PushWatcher", () => { yield* bus.publish(SessionEvent.Execution.Interrupted, { sessionID: parentID, reason: "user" }) yield* bus.publish(SessionEvent.Execution.Succeeded, { sessionID: parentID }) yield* step(parentID) - yield* bus.publish(SessionEvent.Execution.Succeeded, { sessionID: parentID }) + const succeeded = yield* bus.publish(SessionEvent.Execution.Succeeded, { sessionID: parentID }) yield* waitUntil(Effect.sync(() => boxes.length === 1)) - yield* bus.publish(SessionEvent.Execution.Failed, { + const failed = yield* bus.publish(SessionEvent.Execution.Failed, { sessionID: parentID, - error: { type: "unknown", message: "x" }, + error: { type: "provider.rate-limit", message: "x", status: 429, retryAfterMs: 30_000 }, }) yield* waitUntil(Effect.sync(() => boxes.length === 2)) expect(boxes.map((box) => open(key, box))).toEqual([ { v: 1, + type: "turn", id: parentID, - type: "session.idle", + time: succeeded.created, sessionID: parentID, + directory: "/tmp/push", title: "Fix the login bug", body: "Finished", - data: { outcome: "succeeded" }, + data: { + outcome: "succeeded", + messageID, + idleMessageID: SessionMessage.ID.fromEvent(succeeded.id), + text: "Fixed the login bug.", + }, }, { v: 1, + type: "turn", id: parentID, - type: "session.idle", + time: failed.created, sessionID: parentID, + directory: "/tmp/push", title: "Fix the login bug", body: "Failed", - data: { outcome: "failed" }, + data: { + outcome: "failed", + idleMessageID: SessionMessage.ID.fromEvent(failed.id), + error: { type: "provider.rate-limit", message: "x", status: 429, retryAfterMs: 30_000 }, + }, }, ]) }), ) + it.live("holds a finished turn while a subagent runs, and counts the background work still running", () => + Effect.gen(function* () { + const bus = yield* Bus.Service + const key = yield* phone() + + active = new Set([parentID, childID]) + yield* step(parentID) + yield* bus.publish(SessionEvent.Execution.Succeeded, { sessionID: parentID }) + yield* step(parentID) + yield* bus.publish(SessionEvent.Execution.Failed, { + sessionID: parentID, + error: { type: "unknown", message: "x" }, + }) + yield* waitUntil(Effect.sync(() => boxes.length === 1)) + + // A grandchild reports to the child, and a shell may never end, so neither holds the push. + active = new Set([parentID, grandchildID]) + background = [{ kind: "shell", sessionID: parentID, shellID: "sh_1", command: "bun dev" }] + yield* step(parentID) + yield* bus.publish(SessionEvent.Execution.Succeeded, { sessionID: parentID }) + yield* waitUntil(Effect.sync(() => boxes.length === 2)) + + expect(boxes.map((box) => open(key, box).data)).toMatchObject([ + { outcome: "failed", background: { subagent: 1 } }, + { outcome: "succeeded", background: { shell: 1, subagent: 1 } }, + ]) + }), + ) + it.live("asks for questions and permissions, also from subagents, under the top-level session", () => Effect.gen(function* () { const bus = yield* Bus.Service @@ -172,40 +242,90 @@ describe("PushWatcher", () => { id: Form.ID.make(id), sessionID, title: "Questions", - metadata: { kind }, - fields: [{ key: "q0", title: "Database", description: "Which database?", type: "string" }], + metadata: { kind, tool: { messageID: "msg_1", id: "call_1" } }, + fields: [ + { + key: "q0", + title: "Database", + description: "Which database?", + type: "string", + options: [ + { value: "Postgres", label: "Postgres", description: "The production database" }, + { value: "sqlite", label: "SQLite" }, + ], + custom: true, + }, + { key: "q1", title: "Seed", type: "boolean" }, + ], }) yield* bus.publish(Form.Event.Created, { form: form("frm_other", childID, "elicitation") }) yield* bus.publish(Form.Event.Created, { form: form("frm_global", "global", "question") }) - yield* bus.publish(Form.Event.Created, { form: form("frm_1", grandchildID, "question") }) + const created = yield* bus.publish(Form.Event.Created, { form: form("frm_1", grandchildID, "question") }) yield* waitUntil(Effect.sync(() => boxes.length === 1)) - yield* bus.publish(Permission.Event.Asked, { + const asked = yield* bus.publish(Permission.Event.Asked, { id: Permission.ID.make("per_1"), sessionID: childID, action: "bash", resources: ["git push"], + save: ["git push *"], + source: { type: "tool", messageID: "msg_2", id: "call_2" }, + message: "Pushes to main", }) yield* waitUntil(Effect.sync(() => boxes.length === 2)) expect(boxes.map((box) => open(key, box))).toEqual([ { v: 1, + type: "form", id: "frm_1", - type: "question", + time: created.created, sessionID: parentID, + directory: "/tmp/push", + attention: true, title: "Fix the login bug", body: "Which database?", - data: { formID: "frm_1", sessionID: grandchildID }, + data: { + formID: "frm_1", + replySessionID: grandchildID, + kind: "question", + fieldCount: 2, + source: { type: "tool", messageID: "msg_1", id: "call_1" }, + fields: [ + { + key: "q0", + type: "string", + title: "Database", + description: "Which database?", + custom: true, + options: [ + { label: "Postgres", description: "The production database" }, + { label: "SQLite", value: "sqlite" }, + ], + }, + ], + }, }, { v: 1, - id: "per_1", type: "permission", + id: "per_1", + time: asked.created, sessionID: parentID, + directory: "/tmp/push", + attention: true, title: "Fix the login bug", body: "Needs permission: bash", - data: { requestID: "per_1", sessionID: childID, action: "bash", resources: ["git push"] }, + data: { + requestID: "per_1", + replySessionID: childID, + action: "bash", + resources: ["git push"], + save: ["git push *"], + decisions: ["once", "always", "reject"], + message: "Pushes to main", + source: { type: "tool", messageID: "msg_2", id: "call_2" }, + }, }, ]) }), @@ -239,7 +359,9 @@ describe("PushWatcher", () => { yield* ask("per_1") yield* waitUntil(Effect.sync(() => boxes.length === 1)) - yield* bus.publish(Permission.Event.Replied, { + // Nothing to save, so "always" isn't offered. + expect(open(key, boxes[0]!).data.decisions).toEqual(["once", "reject"]) + const replied = yield* bus.publish(Permission.Event.Replied, { sessionID: childID, requestID: Permission.ID.make("per_1"), reply: "once", @@ -252,24 +374,33 @@ describe("PushWatcher", () => { sessionID: childID, title: "Questions", metadata: { kind: "question" }, - fields: [{ key: "q0", title: "Database", type: "string" }], + fields: [{ key: "q0", title: "Database", type: "string", custom: true }], }, }) yield* waitUntil(Effect.sync(() => boxes.length === 3)) - yield* bus.publish(Form.Event.Cancelled, { id: Form.ID.make("frm_1"), sessionID: childID }) + // A form with one field can be answered from the notification. + expect(open(key, boxes[2]!).data).toEqual({ + formID: "frm_1", + replySessionID: childID, + kind: "question", + fieldCount: 1, + inlineReply: true, + fields: [{ key: "q0", type: "string", title: "Database", custom: true }], + }) + const cancelled = yield* bus.publish(Form.Event.Cancelled, { id: Form.ID.make("frm_1"), sessionID: childID }) yield* waitUntil(Effect.sync(() => boxes.length === 4)) // An interrupted request gets no reply. yield* ask("per_2") yield* waitUntil(Effect.sync(() => boxes.length === 5)) - yield* bus.publish(SessionEvent.Execution.Interrupted, { sessionID: childID, reason: "user" }) + const interrupted = yield* bus.publish(SessionEvent.Execution.Interrupted, { sessionID: childID, reason: "user" }) yield* waitUntil(Effect.sync(() => boxes.length === 6)) yield* step(parentID) yield* bus.publish(SessionEvent.Execution.Succeeded, { sessionID: parentID }) yield* waitUntil(Effect.sync(() => boxes.length === 7)) yield* prompt("synthetic") - yield* prompt("user") + const prompted = yield* prompt("user") yield* waitUntil(Effect.sync(() => boxes.length === 8)) // Archiving or deleting the session removes whatever is still showing for it. @@ -284,17 +415,17 @@ describe("PushWatcher", () => { expect( cleared() .slice(-2) - .map((item) => item.id) + .map((item) => item.ids[0]) .sort(), ).toEqual([parentID, "per_3"].sort()) } expect(silent.slice(0, 8)).toEqual([undefined, true, undefined, true, undefined, true, undefined, true]) expect(cleared().slice(0, 4)).toEqual([ - { v: 1, id: "per_1", type: "clear", sessionID: parentID }, - { v: 1, id: "frm_1", type: "clear", sessionID: parentID }, - { v: 1, id: "per_2", type: "clear", sessionID: parentID }, - { v: 1, id: parentID, type: "clear", sessionID: parentID }, + { v: 1, type: "clear", ids: ["per_1"], time: replied.created }, + { v: 1, type: "clear", ids: ["frm_1"], time: cancelled.created }, + { v: 1, type: "clear", ids: ["per_2"], time: interrupted.created }, + { v: 1, type: "clear", ids: [parentID], time: prompted.created }, ]) }), ) @@ -347,7 +478,7 @@ describe("PushWatcher", () => { boxes .slice(3) .map((box) => open(key, box)) - .map((item) => [item.type, item.id]), + .map((item) => [item.type, item.id ?? item.ids[0]]), ).toEqual([ ["permission", "per_2"], ["clear", "per_2"], diff --git a/packages/server/test/push-routes.test.ts b/packages/server/test/push-routes.test.ts index 9b9d866d93a..95eb2151f0c 100644 --- a/packages/server/test/push-routes.test.ts +++ b/packages/server/test/push-routes.test.ts @@ -37,8 +37,16 @@ const start = Effect.fnUntraced(function* () { }) }) +// A later app may send keys this server doesn't know, such as the format versions it reads. const register = (publicKey: string, callbackURL = `${relay}/v2/notify/sealed`) => - JSON.stringify({ callbackURL, expiresAt: Date.now() + 86_400_000, publicKey, platform: "android", name: "Pixel" }) + JSON.stringify({ + callbackURL, + expiresAt: Date.now() + 86_400_000, + publicKey, + platform: "android", + name: "Pixel", + formats: [1], + }) const phoneKey = () => { const phone = createECDH("prime256v1") diff --git a/specs/v2/README.md b/specs/v2/README.md index 437de9bc0c1..564a9490bf5 100644 --- a/specs/v2/README.md +++ b/specs/v2/README.md @@ -23,6 +23,7 @@ Generated clients follow the assembled public `HttpApi`. GitHub issues own activ | ----------------------- | --------------------------------------------------------------------------------------- | | [Session](./session.md) | Explain prompt admission, execution, instructions, compaction, and recovery boundaries. | | [Tools](./tools.md) | Explain tool construction, registration, execution, and outcome laws. | +| [Push](./push.md) | Describe the push notification message a phone client receives and how it replies. | ## Decision Records diff --git a/specs/v2/push.md b/specs/v2/push.md new file mode 100644 index 00000000000..297d56f1490 --- /dev/null +++ b/specs/v2/push.md @@ -0,0 +1,221 @@ +# Push Notification Format + +Status: **Current contract.** Core builds these messages in `packages/core/src/push/watcher.ts` and `sender.ts`. This document is for anyone writing a phone client. + +## The Message + +A phone registers with `PUT /api/experimental/push/device/:deviceID`. The server then sends each notification through the relay as an encrypted box. Inside the box is one JSON object, the message. The relay never sees it. + +Every message has `v` and `type`. A message that shows a notification has this envelope: + +| Key | Sent | Meaning | +| ----------- | ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | +| `v` | always | Format version, `1`. | +| `type` | always | `permission`, `form` or `turn`. A `clear` has [its own shape](#clear). | +| `id` | always | The notification's name. A later message with the same `id` replaces it, and a `clear` removes it. | +| `time` | always | When the event happened, in ms since the epoch. | +| `sessionID` | when it is about a session | The top-level session: the one to open on tap, and the one bells apply to. | +| `directory` | when it is about a session | The folder that session works in. | +| `attention` | when it asks the person for something | `true`: the notification waits for an answer, as a permission or a form does. Phones whose level is `attention` get only these. | +| `title` | always | A plain title to fall back on. Today the session's title, or "OpenCode". | +| `body` | always | Plain text to fall back on, at most 200 Unicode code points and never empty. | +| `data` | always | Facts for the app to build its own text from, different for each type. | + +`id` is opaque and unique only within one server, so a phone paired with several servers keeps each server's notifications and clears apart. Today it is a permission, form or session id, but an app only compares it with other `id`s; the ids to reply with and open are in `sessionID` and `data`. + +`title` and `body` are always a usable notification on their own. An app shows them when it doesn't understand a message's `type` or `v`. The server's own phrases are English; text it copies, such as a form's question or a provider's error, is in whatever language it was written. A message without `body`, as a `clear` is, is never shown. + +## Permission + +```json +{ + "v": 1, + "type": "permission", + "id": "per_1", + "time": 1795644290720, + "sessionID": "ses_parent", + "directory": "/home/me/shop", + "attention": true, + "title": "Fix the login bug", + "body": "Needs permission: shell", + "data": { + "requestID": "per_1", + "replySessionID": "ses_child", + "action": "shell", + "resources": ["git add .", "git push origin main"], + "save": ["git add *", "git push *"], + "decisions": ["once", "always", "reject"], + "source": { "type": "tool", "messageID": "msg_1", "id": "call_1" } + } +} +``` + +| Key | Sent | Meaning | +| ---------------- | -------------------------------- | -------------------------------------------------------------------------------------------------------------- | +| `requestID` | always | The request to reply to. | +| `replySessionID` | always | The session that asked, which may be a subagent's. | +| `action` | always | `shell`, `edit`, `read`, `webfetch`, `websearch`, `external_directory`, `skill`, an MCP tool, or another name. | +| `resources` | always | What is asked for: commands, paths, a URL, a query or folders. `["*"]` means anything. | +| `resourceCount` | when `resources` were left out | How many resources the request has. | +| `save` | when the request has any | The patterns "Allow always" would store. | +| `decisions` | always | The replies to offer: `once` and `reject`, and `always` when the request has patterns to save. | +| `message` | when the request has one | A note sent with the request. | +| `source` | when a tool call asked | The call: `type` `"tool"`, the `messageID` of its assistant message, and the call's `id`. | +| `truncated` | when something in `data` was cut | `true`. See [Size](#size). | + +A request's `metadata`, such as the diff of an edit, is never in the message. An app fetches the request to show it. + +## Form + +```json +{ + "v": 1, + "type": "form", + "id": "frm_1", + "time": 1795644290720, + "sessionID": "ses_parent", + "directory": "/home/me/shop", + "attention": true, + "title": "Fix the login bug", + "body": "Which database should the cache use?", + "data": { + "formID": "frm_1", + "replySessionID": "ses_child", + "kind": "question", + "fieldCount": 1, + "inlineReply": true, + "source": { "type": "tool", "messageID": "msg_1", "id": "call_1" }, + "fields": [ + { + "key": "q0", + "type": "string", + "title": "Database", + "description": "Which database should the cache use?", + "custom": true, + "options": [ + { "label": "Postgres", "description": "Best for production" }, + { "label": "SQLite", "value": "sqlite" } + ] + } + ] + } +} +``` + +A form is something the session asks the person to fill in. Today only forms whose `metadata.kind` is `"question"`, as the question tool's are, send a push. `fields` holds the form's first field; the others are only counted. An app reads `fields` as a list, since later servers may send more of them. + +A field uses the same names as the form the server returns from `GET`, and carries only these keys: + +| Key | Sent | Meaning | +| ---------------------- | -------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ | +| `formID` | always | The form to reply to. | +| `replySessionID` | always | The session that owns the form, which may be a subagent's. | +| `kind` | when the form has one | What the form is for. `"question"` is the question tool's. | +| `fieldCount` | always | How many fields the form has. | +| `inlineReply` | when a reply can be built from this message alone | `true`. See [Replying](#replying-from-a-notification). | +| `source` | when a tool call asked | The call: `type` `"tool"`, the `messageID` of its assistant message, its `id`. | +| `fields[].key` | always | The field's key, used in the reply. | +| `fields[].type` | always | `string`, `multiselect`, `number`, `integer`, `boolean` or `external`. | +| `fields[].title` | when it has one | Its short header. | +| `fields[].description` | when it has one | The question itself. | +| `fields[].custom` | when a typed answer is accepted | `true`. Without it, only the listed options are accepted. | +| `fields[].options` | for `string` and `multiselect` fields with options | All of them, in order. `label` always; `value` only when it differs from the label; `description` when it has one. | +| `truncated` | when something in `data` was cut | `true`. See [Size](#size). | + +## Finished and Failed + +```json +{ + "v": 1, + "type": "turn", + "id": "ses_parent", + "time": 1795644290720, + "sessionID": "ses_parent", + "directory": "/home/me/shop", + "title": "Fix the login bug", + "body": "Failed", + "data": { + "outcome": "failed", + "messageID": "msg_9", + "idleMessageID": "msg_10", + "text": "Running the tests now.", + "error": { "type": "provider.rate-limit", "message": "Rate limit exceeded", "status": 429, "retryAfterMs": 30000 } + } +} +``` + +Sent for top-level sessions only: when a turn that ran a model step succeeds (`body` "Finished"), and when a turn fails (`body` "Failed"). + +A finished turn sends nothing while one of the session's own subagents is still running, because the subagent's report starts another turn. Other background work doesn't hold the message, since a command such as a dev server may never end; `background` says what is still running. A failed turn is always sent. + +| Key | Sent | Meaning | +| -------------------- | ------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `outcome` | always | `succeeded` or `failed`. | +| `messageID` | when the turn ran a model step | The turn's final assistant message, where its answer is. | +| `idleMessageID` | always | The message that records how the turn ended. A failed turn's full error is on it. | +| `text` | when the turn wrote any | An excerpt of that message's text that the server picks, in Markdown. For display only: it can start mid-word or inside a Markdown block. Never reasoning or tool output. | +| `error.type` | on failure | The error's kind, such as `provider.rate-limit`, `provider.auth`, `tool.execution` or `aborted`. | +| `error.message` | on failure, when not empty | The error's message. | +| `error.status` | on failure, when there is one | The HTTP status the provider answered with. | +| `error.retryAfterMs` | on failure, when there is one | How long the provider asked to wait before trying again, in ms, counted from when it answered, shortly before `time`. | +| `background` | when background work is still running | How many background jobs are still running under the session and its subagents, by kind: `shell`, `subagent`, `codemode`, `image` or `video`. Each one starts another turn when it ends. | +| `truncated` | when something in `data` was cut | `true`. See [Size](#size). | + +## Clear + +```json +{ "v": 1, "type": "clear", "ids": ["per_1", "per_2"], "time": 1795644290725 } +``` + +Sent silently, only to the phones that got the notifications. It removes the notifications sent under `ids`. `time` is when the event that caused it happened. `ids` is a list so that one clear can name several; today the server sends one clear for each. + +A permission clears when it is answered on any client or its turn ends, a form when it is answered or cancelled, and a finished turn on a new prompt or a later view of the session. Archiving or deleting a session clears all of its notifications. + +## Order + +Pushes can arrive late, out of order or not at all. + +- A message replaces the notification shown under the same `id`, unless that one has a later `time`. +- A clear removes a notification only when the notification's `time` is not later than the clear's. +- A phone remembers a clear for at least an hour. A notification that arrives after it with the same `id` and a `time` that is not later is never shown. +- A reply to something already settled answers 404 or 409. The app then removes the notification. +- When the app opens, it asks the server what is still waiting instead of trusting the notifications on screen. + +## Replying From a Notification + +Replies name `replySessionID`, not the top-level `sessionID`. An app offers an action only when this message gives it everything the action needs; otherwise it opens the session. + +- Permission: offer the `decisions` the message lists, and no others. `POST /api/session/:replySessionID/permission/:requestID/reply` with `{ "decision": "once" | "always" | "reject", "message"?: string }`. A `message` with `reject` goes back to the agent as feedback. `always` stores the `save` patterns for the project and also allows other waiting requests they now cover. `reject` also rejects the session's other waiting requests from the same assistant message. Don't approve a request whose `truncated` is `true` without fetching the full version first. +- Form: reply only when `inlineReply` is `true`, `fields` holds all `fieldCount` fields, and the app knows the `type` of each. `POST /api/session/:replySessionID/form/:formID/reply` with `{ "answer": { "": value } }`. For `string` the value is a string; for `multiselect`, a list of strings. For an option, send its `value`, or its `label` when there is no `value`. Send typed text only when `custom` is `true`. The server checks the answer and answers 400 when it doesn't accept it; the app then opens the session. To dismiss a form without answering, `DELETE /api/session/:replySessionID/form/:formID`, which needs only the ids. + +The server sends `inlineReply` when the form has one field, a `string` or `multiselect`, and nothing in `data` was cut. A reply settles the whole form. + +## Size + +A message is at most 2,600 bytes, so its box fits the relay's limit. When it is bigger, the server cuts it in this order until it fits: + +1. `inlineReply` is left out. +2. `text` is left out. +3. `error.message` is cut from its end. +4. `resources` are kept in order while they fit; the next one is shortened, or left out if even that won't fit, and the rest are left out. +5. Option `description`s are left out. +6. A field's `description` is cut from its end. +7. `data` keeps only its ids (`requestID`, `formID`, `replySessionID`, `messageID`, `idleMessageID`), `kind`, `fieldCount`, `decisions`, `outcome`, `background` and `truncated`, and `directory` is left out. This is the one step that leaves out keys the tables above call always sent. + +Anything shortened ends in "…". A value is never sent as a bare "…": it is left out instead. When anything in `data` is cut or left out, `data.truncated` is `true`; otherwise it isn't sent. The server's choice of excerpt for `text` doesn't set it. Ids, `time`, `title` and `body` are never cut. + +The full version can be fetched by id: + +- `GET /api/session/:replySessionID/permission/:requestID` (while the request is waiting) +- `GET /api/session/:replySessionID/form/:formID` +- `GET /api/session/:sessionID/message/:messageID` for a turn's answer +- `GET /api/session/:sessionID/message/:idleMessageID` for how a turn ended, with a failed turn's full error + +## Changing the Format + +- Only add keys. Never rename, remove or change the meaning or type of one. +- Clients treat every key except `v` and `type` as optional, and ignore keys they don't know. +- For an unknown `type` or `v`, a client shows `title` and `body` and opens the session on tap, or the app when there is no `sessionID`. It offers no actions. Without `body`, it does nothing. +- For an unknown value, such as a new `kind`, field `type`, decision, `outcome` or `error.type`, a client shows what it understands and leaves out what it doesn't. +- `title` and `body` always stay a usable notification on their own. +- Bump `v` only as a last resort. Registration ignores keys it doesn't know, so a later app can tell the server which versions it reads; an app that doesn't say reads only `1`.