Skip to content

Commit c438a73

Browse files
committed
feat(es-app): integrate idempotent Front Desk brief jobs and handoff progress UI (dotfiles#238, anomalyco#245)
3 parents 73661c0 + 4df99db + 9335c77 commit c438a73

10 files changed

Lines changed: 193 additions & 18 deletions

‎packages/es-app/src/api.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
* dashboard server (:7777) via /es — both same-origin through vite. */
33
import type { Agent, GlobalSession, Message, Part, PermissionRequest, QuestionRequest, Session, SessionFailure, SessionRetryResult, SessionV1InputImage, Todo } from "@opencode-ai/sdk/v2"
44
import { httpError } from "./api-error"
5+
import type { PendingHandoff } from "./handoffs"
56

67
export type MessageWithParts = { info: Message; parts: Part[] }
78
/** Generated text attached to a human's own message; marked synthetic and with its producer. */
@@ -340,7 +341,7 @@ export type MailDelivery = {
340341
wake_observations?: readonly { outcome: "scheduled" | "coalesced"; observedAt: number }[]
341342
}
342343
export type MailTimeline = { editspace: string; lane: string; messages: MailMessage[] }
343-
export type Handoff = { lane: string; predecessor: string; successor: string }
344+
export type Handoff = { lane: string; predecessor: string; successor: string; reason?: string; kickoff?: "skipped"; context?: string }
344345
export type LaneProvenance = {
345346
delegations: { lane: string; parent: string; session: string | null; status: string }[]
346347
spawned: { lane: string; by: string }[]
@@ -475,8 +476,8 @@ export const es = {
475476
fetch(`/es/api/lane-provenance?es=${encodeURIComponent(name)}`).then(statusJson<LaneProvenance>),
476477
// The dashboard must create the handoff document, spawn the successor, and
477478
// transfer the lane owner as one server-side operation before returning.
478-
handoffs: (name: string): Promise<{ handoffs: Handoff[] }> =>
479-
fetch(`/es/api/handoffs?es=${encodeURIComponent(name)}`).then(statusJson<{ handoffs: Handoff[] }>),
479+
handoffs: (name: string): Promise<{ handoffs: Handoff[]; pending?: PendingHandoff[] }> =>
480+
fetch(`/es/api/handoffs?es=${encodeURIComponent(name)}`).then(statusJson<{ handoffs: Handoff[]; pending?: PendingHandoff[] }>),
480481
handoff: (name: string, lane: string, predecessor: string, task: string, handoff: string): Promise<Handoff | { lane: string; predecessor: string; status: "pending" }> =>
481482
fetch(`/es/api/handoffs?es=${encodeURIComponent(name)}`, {
482483
method: "POST",

‎packages/es-app/src/desk-briefs.tsx‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@ const waitFor = (ready: () => boolean) => new Promise<void>(resolve => {
1414
check()
1515
})
1616
const SETTING = "es-app:front-desk:auto-prepare"
17+
// The newest few open items first, then the backlog one at a time: no burst on first run.
18+
const FIRST = 5
1719
const MAX_RUNNING = 2
1820

1921
const create = () => {
@@ -57,8 +59,9 @@ const create = () => {
5759
createEffect(() => {
5860
if (!auto() || !loaded() || anchor.error() || attention.stale() || briefs.pending() || briefs.preparing()) return
5961
const running = briefs.jobs().filter(job => ["starting", "running"].includes(job.state.state)).length
60-
if (running >= MAX_RUNNING) return
61-
const next = items().find(item => !jobFor(item) && !attempted.has(`${item.key}\u0000${item.revision}`))
62+
if (running >= (attempted.size < FIRST ? MAX_RUNNING : 1)) return
63+
const next = items().filter(item => !jobFor(item) && !attempted.has(`${item.key}\u0000${item.revision}`))
64+
.sort((a, b) => (b.record?.created_at ?? 0) - (a.record?.created_at ?? 0))[0]
6265
if (!next) return
6366
attempted.add(`${next.key}\u0000${next.revision}`)
6467
void briefs.start(next)

‎packages/es-app/src/desk-session.ts‎

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,17 @@ const metaOf = (session: Session): BriefMeta | undefined => {
137137
/** Local read-only retrieval inside the anchor's project root. Every other tool, reads outside the
138138
* root and environment files are denied, so a brief never prompts for permission, runs commands,
139139
* reaches the network or writes anything. */
140+
/* Public shape other clients (native, phone) can read without es-app code:
141+
* - anchor: Core session ses_fdbrief_<sha256(editspace root)[:20 hex]> in that root (archived);
142+
* - job: its child session ses_fdjob_<sha256(JSON [anchor, source, revision, attempt])[:24 hex]>,
143+
* metadata.frontDesk = BriefMeta {kind:"brief", requestID, source: "attention:<editspace>:<record id>", revision, title, refs};
144+
* - result: the job's last completed assistant text is one JSON object matching BRIEF_SCHEMA (desk.ts),
145+
* valid only while the ledger record still has that revision. */
146+
const briefID = async (parent: string, source: string, revision: string, attempt: number) => {
147+
const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(JSON.stringify([parent, source, revision, attempt]))))
148+
return `ses_fdjob_${[...digest].map(byte => byte.toString(16).padStart(2, "0")).join("").slice(0, 24)}`
149+
}
150+
140151
export const BRIEF_PERMISSION = [
141152
{ permission: "*", pattern: "*", action: "deny" as const },
142153
...["read", "grep", "glob", "list"].map(permission => ({ permission, pattern: "*", action: "allow" as const })),
@@ -218,7 +229,8 @@ export const createBriefs = (desk: () => DeskPointer | undefined, current: (key:
218229
} catch (cause) {
219230
if (cause instanceof SessionCreateError && !cause.uncertain) {
220231
savePending(undefined)
221-
setError(`Brief not started: ${cause.message}`)
232+
// 409: another client (tab, native app) already created this job; adopt it, never prompt it again.
233+
if (!cause.message.includes("HTTP 409")) setError(`Brief not started: ${cause.message}`)
222234
}
223235
setInflight(undefined)
224236
return refresh()
@@ -255,7 +267,10 @@ export const createBriefs = (desk: () => DeskPointer | undefined, current: (key:
255267
if (desk()?.session !== target.session || pending() || inflight() || reusable(latest)) return
256268
const packet = briefPacket(latest, tail)
257269
const meta: BriefMeta = { kind: "brief", requestID: crypto.randomUUID(), source: latest.key, revision: latest.revision, title: latest.title, refs: packet.refs }
258-
const id = `ses_${descending()}`
270+
// Deterministic per (parent, source, revision, attempt): every client computes the same ID, so
271+
// Core's create reconciliation makes the first creator win and the rest adopt its job.
272+
const attempt = jobs().filter(job => job.meta.source === latest.key && job.meta.revision === latest.revision).length
273+
const id = await briefID(target.session, latest.key, latest.revision, attempt)
259274
const value: PendingCreate = {
260275
id, directory: target.directory, packet: packet.text, created: Date.now(),
261276
body: {

‎packages/es-app/src/handoffs.ts‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,13 @@
1-
export type Handoff = { lane: string; predecessor: string; successor: string }
1+
export type Handoff = { lane: string; predecessor: string; successor: string; reason?: string; kickoff?: "skipped"; context?: string }
2+
export type PendingHandoff = {
3+
lane: string
4+
predecessor: string
5+
successor?: string | null
6+
status: string
7+
request_id: string
8+
error?: string | null
9+
reason?: string
10+
}
211
export type LaneOwner = { lane: string; owner: string }
312

413
// A lane owner is the authoritative tip. Never infer succession from timestamps,
@@ -29,6 +38,11 @@ export const handoffNext = (sessionID: string, handoffs: Handoff[]) => {
2938
return next.length === 1 ? next[0] : undefined
3039
}
3140

41+
export const pendingHandoffFor = (sessionID: string, pending: PendingHandoff[]) => {
42+
const matches = pending.filter((item) => item.predecessor === sessionID || item.successor === sessionID)
43+
return matches.length === 1 ? matches[0] : undefined
44+
}
45+
3246
export const transferPins = (pins: string[], from: string, to: string, directory: string, targetDirectory = directory) => {
3347
const oldKey = JSON.stringify([directory, from])
3448
const newKey = JSON.stringify([targetDirectory, to])

‎packages/es-app/src/pages/session.tsx‎

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ import { usePulse } from "../pulse"
3737
import { MailRow } from "../components/mail-row"
3838
import { MailSubscriptions } from "../components/mail-subscriptions"
3939
import { mailCauses, mailLocation, mailRows, mailSourceID } from "../mail-timeline"
40-
import { handoffChain, handoffNext, successorFor } from "../handoffs"
40+
import { handoffChain, handoffNext, pendingHandoffFor, successorFor } from "../handoffs"
4141
import { ComposerImages } from "../components/composer-images"
4242
import { ActivityBriefView } from "../components/activity-brief"
4343
import { FindExcerpt, TranscriptFind } from "../components/transcript-find"
@@ -157,7 +157,8 @@ export function SessionView(props: { sessionID: string; directory: string; embed
157157
let inspecting = false
158158

159159
const { activity, sessionsError, editspaces, mailRevision, editspace, state, handoffs, handoffsError,
160-
laneOwners, lineage, lineageOwners, refetch, refetchHandoffs, transferPin } = useDashboard()
160+
laneOwners, lineage, lineageOwners, pendingHandoffs, refetch, refetchHandoffs, transferPin } = useDashboard()
161+
const pendingTransfer = () => pendingHandoffFor(sessionID, pendingHandoffs())
161162
const currentEditspace = () => editspace() ?? editspaces()?.default ?? state()?.editspace
162163
const ownedLane = () => laneOwners().find((lane) => lane.owner === sessionID)
163164
const predecessor = () => {
@@ -885,6 +886,7 @@ export function SessionView(props: { sessionID: string; directory: string; embed
885886
}
886887
}
887888
const recoveryTarget = () => {
889+
if (pendingTransfer()) return
888890
const tip = successor()
889891
if (tip) return tip.successor
890892
// A tagged rejection can supply a missing edge, but cannot override a
@@ -1503,6 +1505,17 @@ export function SessionView(props: { sessionID: string; directory: string; embed
15031505
<Show when={predecessor()}>{(edge) => <div class="banner handoff-history" aria-label="Previous session">
15041506
Previous session: <A href={sessionHref(edge().predecessor, activity.session(edge().predecessor)?.directory)}><bdi dir="auto">{activity.session(edge().predecessor)?.title ?? edge().predecessor}</bdi></A>
15051507
{" · "}<bdi dir="ltr">{edge().predecessor}</bdi>
1508+
<Show when={edge().reason}>{(reason) => <> · <bdi dir="auto">{reason()}</bdi></>}</Show>
1509+
<Show when={edge().kickoff === "skipped" && edge().context}>{(context) => <>
1510+
{" · "}Handoff brief not sent because this session was already in use: <bdi dir="ltr">{context()}</bdi>
1511+
</>}</Show>
1512+
</div>}</Show>
1513+
<Show when={pendingTransfer()}>{(transfer) => <div class="banner handoff-progress" role="status" aria-label="Handoff progress">
1514+
{transfer().error ? "Handoff paused. Your draft is saved." : transfer().successor === sessionID
1515+
? "Loading handoff context. This session is not ready yet."
1516+
: transfer().status === "submitting" ? "Starting the next session. Your draft is saved here."
1517+
: "Preparing the next session. Your draft is saved here."}
1518+
<Show when={transfer().reason}>{(reason) => <> <bdi dir="auto">{reason()}</bdi>.</>}</Show>
15061519
</div>}</Show>
15071520
<Show when={live.hasOlder()}>
15081521
<button class="transcript-older" disabled={live.loadingOlder()} onClick={loadEarlier}>
@@ -1572,7 +1585,9 @@ export function SessionView(props: { sessionID: string; directory: string; embed
15721585
<div dir="auto">{composer.state.admission?.payload.text}</div>
15731586
<button disabled={composer.state.inputLoading || !connected()} onClick={() => composer.refreshInputs()}>Check admission</button>
15741587
</div></Show>
1575-
<Show when={!composer.state.admission?.fence && recoveryTarget()} fallback={<p>Waiting for a confirmed successor or admission outcome. No message will be resent automatically.</p>}>{(next) =>
1588+
<Show when={!composer.state.admission?.fence && recoveryTarget()} fallback={<p>{pendingTransfer()
1589+
&& !composer.state.admission?.fence ? "Handoff is still preparing; your message has not been sent."
1590+
: "Waiting for a confirmed successor or admission outcome. No message will be resent automatically."}</p>}>{(next) =>
15761591
<A href={sessionHref(next(), activity.session(next())?.directory ?? directory)} aria-disabled={recovering()} onClick={(event) => {
15771592
event.preventDefault()
15781593
void followSuccessor(next())

‎packages/es-app/src/state.tsx‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ import { es, oc, type AttentionNotification } from "./api"
1616
import { createSessionActivity } from "./session-activity"
1717
import { createServerEvents } from "./event-source"
1818
import { resolveProjectName } from "./project-name"
19-
import { reconcilePins, transferPins, type Handoff } from "./handoffs"
19+
import { reconcilePins, transferPins, type Handoff, type PendingHandoff } from "./handoffs"
2020
import { pinSessionID } from "./session-pins"
2121
import { createCloudAgents } from "./cloud-agents"
2222
import { createSessionFailures } from "./session-failures"
@@ -53,6 +53,7 @@ type DashboardCtx = {
5353
editspaces: Resource<{ editspaces: { name: string; root: string }[]; default: string | null }>
5454
mailRevision: () => number
5555
handoffs: Resource<Handoff[]>
56+
pendingHandoffs: () => PendingHandoff[]
5657
handoffsError: () => string
5758
refetchHandoffs: () => void
5859
laneOwners: () => { lane: string; owner: string }[]
@@ -123,6 +124,7 @@ export function DashboardProvider(props: ParentProps) {
123124
},
124125
)
125126
const [handoffsError, setHandoffsError] = createSignal("")
127+
const [pendingHandoffs, setPendingHandoffs] = createSignal<Record<string, PendingHandoff[]>>({})
126128
const cloud = createCloudAgents({
127129
project: () => allProjects() ? undefined : editspace() ?? editspaces()?.default ?? undefined,
128130
defaultProject: () => editspace() ?? editspaces()?.default ?? undefined,
@@ -134,6 +136,7 @@ export function DashboardProvider(props: ParentProps) {
134136
if (!name) return []
135137
try {
136138
const result = await es.handoffs(name)
139+
setPendingHandoffs((previous) => ({ ...previous, [name]: result.pending ?? [] }))
137140
setHandoffsError("")
138141
return result.handoffs
139142
} catch (error) {
@@ -373,16 +376,17 @@ export function DashboardProvider(props: ParentProps) {
373376
async ({ names, selected }) => Promise.all(names.filter((name) => name !== selected).map(async (name) => {
374377
try {
375378
const [lineage, dashboard] = await Promise.all([es.handoffs(name), es.state(name)])
376-
if (dashboard.editspace !== name) return { edges: [], owners: [] }
379+
if (dashboard.editspace !== name) return { edges: [], owners: [], pending: [] }
377380
const scope = (lane: string) => JSON.stringify([name, lane])
378381
return {
379382
edges: lineage.handoffs.map((edge) => ({ ...edge, lane: scope(edge.lane) })),
383+
pending: (lineage.pending ?? []).map((item) => ({ ...item, lane: scope(item.lane) })),
380384
owners: (dashboard.threads ?? []).flatMap((thread: { lanes?: { lane: string; owner?: string }[] }) =>
381385
(thread.lanes ?? []).flatMap((lane) => lane.owner ? [{ lane: scope(lane.lane), owner: lane.owner }] : [])),
382386
}
383387
} catch {
384388
// Missing lineage in one editspace must not guess at its pinned owners.
385-
return { edges: [], owners: [] }
389+
return { edges: [], owners: [], pending: [] }
386390
}
387391
})),
388392
)
@@ -518,6 +522,10 @@ export function DashboardProvider(props: ParentProps) {
518522
editspaces,
519523
mailRevision,
520524
handoffs,
525+
pendingHandoffs: () => [
526+
...(pendingHandoffs()[currentEditspaceName()] ?? []).map((item) => ({ ...item, lane: JSON.stringify([currentEditspaceName(), item.lane]) })),
527+
...(otherLineages() ?? []).flatMap((item) => item.pending),
528+
],
521529
handoffsError,
522530
refetchHandoffs: () => { void refetchHandoffs() },
523531
laneOwners,

‎packages/es-app/test/composer-fixture.mjs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,7 @@ export const createFixture = async () => {
9898
wingman: undefined,
9999
wingmanTranscript: undefined,
100100
handoffs: undefined,
101+
pendingHandoffs: [],
101102
subscriptions: undefined,
102103
laneOwners: [],
103104
superseded: new Map(),
@@ -236,7 +237,7 @@ export const createFixture = async () => {
236237
if (url.pathname === "/api/lane-provenance" && request.method === "GET")
237238
return json(fixture.laneProvenance?.(url.searchParams.get("es")) ?? { delegations: [], spawned: [] })
238239
if (url.pathname === "/api/handoffs" && request.method === "GET")
239-
return json({ handoffs: fixture.handoffs ?? [] })
240+
return json({ handoffs: fixture.handoffs ?? [], pending: fixture.pendingHandoffs })
240241
if (url.pathname === "/api/subscriptions" && fixture.subscriptions) {
241242
const recipient = request.method === "GET" ? url.searchParams.get("recipient") : body?.recipient
242243
if (request.method === "PUT") fixture.subscriptions.set(recipient, [

0 commit comments

Comments
 (0)