From 32739384f56433ad27f339a598e00d812aee942b Mon Sep 17 00:00:00 2001 From: Jackson Miller Date: Mon, 26 Oct 2026 21:59:08 -0400 Subject: [PATCH 1/2] fix(j5): a refused edit to a queued message keeps its author record A person's edit of a queued message in a shared conversation wrote its new author record (edited by, stored prefix, note) while the command was admitted, before upstream dispatched it. When upstream refused the edit because the run had left the queue, the record named an editor and a prefix the stored message didn't carry. SharedConversation now wraps upstream's dispatch instead of only admitting the command: an edit's record is written after upstream takes it, and an edit upstream refuses writes nothing. Closes #738 Co-Authored-By: Claude Opus 5.5 --- FORK.md | 4 +- .../src/j5/sharing/CommandAdmission.test.ts | 10 +- .../server/src/j5/sharing/CommandAdmission.ts | 91 ++++++++--------- .../SharedConversation.integration.test.ts | 97 ++++++++++++++++++- .../src/j5/sharing/SharedConversation.test.ts | 33 ++++--- .../src/j5/sharing/SharedConversation.ts | 95 ++++++++++-------- .../src/j5/sharing/linkJoinShared.test.ts | 26 ++--- .../src/j5/sharing/scheduledRuns.test.ts | 18 ++-- 8 files changed, 247 insertions(+), 127 deletions(-) diff --git a/FORK.md b/FORK.md index bf8a5752f42a..ea44e77032bf 100644 --- a/FORK.md +++ b/FORK.md @@ -439,7 +439,7 @@ migrations after upstream migrations. 75. Highlights, a client's "What's new" ([#624](https://github.com/Jacksondr5/j5code/issues/624), register D35, Jackson's 2026-10-17 decision and design). The entries, the client filter and the rule for what is new are J5-owned `packages/client-runtime/src/j5/highlights.ts`, reached through the `./j5/highlights` export this case appends to upstream-owned `packages/client-runtime/package.json`; the web button, list, art, seen record and palette entry are J5-owned files under `apps/web/src/j5/highlights/`. Four upstream files are touched. `apps/web/src/components/sidebar/SidebarChrome.tsx`: `SidebarUtilityMenu`'s `SidebarMenu` gains the class `@container/utility`, which the button's container query reads to hide itself where the row is too narrow, and `` is mounted immediately before `` (one import, one line). The button's item carries `ms-auto` and cancels the update button's own `ms-auto` with `[&+li]:ms-0`, so the two sit together at the end of the row. `apps/web/src/components/AppSidebarLayout.tsx` mounts `` after upstream's `` (one import, one line): the palette sits outside the sidebar provider, and this helper leaves a utility page and opens a collapsed sidebar when the palette asks for the list. `apps/web/src/components/CommandPalette.tsx` gains one import, one hook call (`useHighlightsPaletteItems()`, beside case 71's) and appends its items to case 71's `actionItems.push(...)`. `apps/web/src/onboarding/firstRun.ts`: `useCompleteOnboarding`, which every path that finishes first run calls (the wizard, the gate's silent completion for a client on an existing workspace, and hosted mode), calls `markAllHighlightsSeen()` before it writes `onboardingCompletedAt` (one import, one call). A finished client with no record is then an existing one, and the order makes that hold whenever the highlights code first reads it. On a pin advance: if upstream moves the utility row, the update button or `MainAppLocationTracker`, re-apply the mounts where they went; if upstream adds another writer of `onboardingCompletedAt`, it needs the same call before it; if upstream's palette `actionItems` moves, re-apply the append as in case 71. 76. Prompt links open J5's apps and j5.codes (registers D19 and D25, Jackson's 2026-10-17 and 2026-10-24 decisions). Upstream's prompt links (`packages/shared/src/promptLinks.ts`) are `t3code://` deep links and `https://app.t3.codes` links to its hosted app, which upstream's "Copy prompt link" makes. J5 has no hosted app; its shareable links point at `https://j5.codes/new?…`, a static page on J5's marketing site (`apps/marketing/src/pages/new.astro`, J5-owned) that shows the prompt and the hidden-characters warning and offers the `j5code://` link, the download page, and the same path on the person's own server. `promptLinks.ts` carries four J5 edits: `APP_SCHEME` accepts only `j5code` and its suffixed development schemes; a J5 constant `J5_PROMPT_LINK_ORIGIN` (`https://j5.codes`) is the default origin of `buildNewThreadLink` and of `promptLinkAppPath`, in place of upstream's `DEFAULT_HOSTED_APP_URL`, so app.t3.codes links are T3 Code's and j5.codes links open in J5's apps; `promptLinkDeepLink`'s default scheme is J5's production scheme (`J5_BRANDING.desktop.productionScheme`); and its error text names J5 Code. "Copy prompt link" on web (`promptLinkFor` in `apps/web/src/components/promptLinks/copyPromptLink.ts`) drops upstream's `origin: configuredHostedAppUrl()`, so it takes the j5.codes default; mobile's copy is upstream's and takes the same default. The thread form, `j5.codes//?prompt=…`, reaches the page through a rewrite in `apps/marketing/vercel.ts`. Upstream's user docs (`docs/user/prompt-links.md`, `default-browser.md`) keep their wording (D25). Proofs: `packages/shared/src/promptLinks.test.ts` (j5.codes links round-trip; T3 Code's scheme and hosted links are not J5's), `apps/marketing/src/lib/promptLink.test.ts`, and `apps/desktop/src/app/DesktopClerk.test.ts`. On a pin advance, keep the scheme, the j5.codes defaults and the web copy call over upstream's changes. 77. No Mobile app row in Settings (Jackson's 2026-10-09 ruling for case 61, applied to the row that replaced it at the 2026-10-17 advance). Upstream's Settings › General "Mobile app" row (`apps/web/src/components/settings/MobileAppSettingsRow.tsx`) shows QR codes and links for T3 Code's App Store and Google Play apps. J5 has no app in the stores, so the file adds `J5_HAS_STORE_MOBILE_APP = false` and the row renders nothing, and `searchSettings` in `settingsSearch.ts` skips the item `mobile-app` (two lines), so search does not offer it. On a pin advance, keep the constant and the skip over upstream's changes. -78. A person's commands are held to what their level and scope allow ([#636](https://github.com/Jacksondr5/j5code/issues/636), register D33, People and access AC13 and AC14). `layerWsRpc` in `apps/server/src/ws.ts` builds J5-owned `makeCommandAdmission(j5CrewSeatArchiveGuard, currentSession)` (`apps/server/src/j5/sharing/CommandAdmission.ts`) once per socket, which reads whose the socket is once, and returns upstream's handlers with `orchestration.dispatchCommand` and `orchestration.launchThread` each wrapped by one J5 call ahead of upstream's own, `j5Commands.dispatchCommand(command, upstream's handler)` and `j5Commands.admitLaunch(input)` (one import of `OrchestrationV2ThreadLaunchInput`, one of the admission, the line that builds it, and the two wrapped entries spread over upstream's handlers). A third entry wraps `scheduledTasks.upsert` (with one import of `ScheduledTaskUpsertInput`): `j5Commands.upsertScheduledTask(input, upstream's upsert)` records who scheduled the task as a person saves it, for case 81. The Crew seat guard of case 37 moved from the dispatch pipe into the admission. It refuses archiving, unarchiving and deleting a thread to anyone who is not an Owner, for now, and runs the Crew seat guard for those who are. For a narrowed person it checks every command type against the scope of the thread or project it names (`NARROWED_COMMAND_SCOPES`): a Collaborator writes within their scope, starts a thread only in a project they reach, and forks or merges back only within such a project; a Viewer sends nothing. A command type without a row is refused to a narrowed person, and the table is keyed by upstream's command types, so a type upstream renames or removes fails to compile. Once admitted, a command goes through J5-owned `SharedConversation.admit` in the same call, which puts the author's line and any note on a person's message in a shared conversation and keeps who answers a prompt. `dispatchCommand` admits the command and then runs upstream's handler: a person's edit of a queued agent message is claimed under their name for J5's ledger before the handler runs, and the claim is released if upstream refuses the edit (#136). The admission reads that service from the socket's context, so the socket's layer is given the server's J5 services: one `Layer.provide(Layer.succeedContext(j5RpcServices))` beside the other server-lifetime services provided there. On a pin advance: if upstream adds a command type, decide its row; if upstream moves either handler, keep the wrap where it is built. +78. A person's commands are held to what their level and scope allow ([#636](https://github.com/Jacksondr5/j5code/issues/636), register D33, People and access AC13 and AC14). `layerWsRpc` in `apps/server/src/ws.ts` builds J5-owned `makeCommandAdmission(j5CrewSeatArchiveGuard, currentSession)` (`apps/server/src/j5/sharing/CommandAdmission.ts`) once per socket, which reads whose the socket is once, and returns upstream's handlers with `orchestration.dispatchCommand` and `orchestration.launchThread` each wrapped by one J5 call ahead of upstream's own, `j5Commands.dispatchCommand(command, upstream's handler)` and `j5Commands.admitLaunch(input)` (one import of `OrchestrationV2ThreadLaunchInput`, one of the admission, the line that builds it, and the two wrapped entries spread over upstream's handlers). A third entry wraps `scheduledTasks.upsert` (with one import of `ScheduledTaskUpsertInput`): `j5Commands.upsertScheduledTask(input, upstream's upsert)` records who scheduled the task as a person saves it, for case 81. The Crew seat guard of case 37 moved from the dispatch pipe into the admission. It refuses archiving, unarchiving and deleting a thread to anyone who is not an Owner, for now, and runs the Crew seat guard for those who are. For a narrowed person it checks every command type against the scope of the thread or project it names (`NARROWED_COMMAND_SCOPES`): a Collaborator writes within their scope, starts a thread only in a project they reach, and forks or merges back only within such a project; a Viewer sends nothing. A command type without a row is refused to a narrowed person, and the table is keyed by upstream's command types, so a type upstream renames or removes fails to compile. Once admitted, a command goes through J5-owned `SharedConversation.dispatch` in the same call, which puts the author's line and any note on a person's message in a shared conversation, keeps who answers a prompt, and records an edit of a queued message only once upstream takes it. `dispatchCommand` admits the command and then runs upstream's handler: a person's edit of a queued agent message is claimed under their name for J5's ledger before the handler runs, and the claim is released if upstream refuses the edit (#136). The admission reads that service from the socket's context, so the socket's layer is given the server's J5 services: one `Layer.provide(Layer.succeedContext(j5RpcServices))` beside the other server-lifetime services provided there. On a pin advance: if upstream adds a command type, decide its row; if upstream moves either handler, keep the wrap where it is built. 79. The `j5` CLI knows whose a session is, and names the person a pairing link is for ([#636](https://github.com/Jacksondr5/j5code/issues/636), register D36, People and access AC4). `apps/server/src/cli/auth.ts` builds upstream's `EnvironmentAuth.layerRuntime` through J5-owned `cliEnvironmentAuth` (`apps/server/src/j5/sharing/AccessGate.ts`; one import and one call), so `auth session revoke` cuts the session loose from its person before upstream revokes it, and the session can never renew. Both `pair` and `auth pairing create` spread J5-owned `personPairingFlags` (`--person`, `--level`, `--project`, `--thread`; `apps/server/src/j5/sharing/cliPairing.ts`) into their flags, and make their link through one call, `pairingLinkFromCli({ config, flags, scopes, ttl, label, withoutPerson })`, which takes upstream's own `--ttl` and `--label` (`pair`'s default label `j5 pair` included). It replaces the body of `mintPairingLink` in `pair.ts`, which no longer builds auth of its own, and the handler of `auth pairing create`, which resolves upstream's config itself rather than through `runWithEnvironmentAuth`. While a server holds the home's lock (`serverOwnership.ts`), the call asks it to make the link (J5's route `POST /api/j5/people/pair`, `CliPairingHttp.ts`) with a session it issues itself in upstream's `j5 project` way, holding only `access:write` and living two minutes, and revokes it afterwards; the route answers only that subject (`cli-issued-session`), so the running server writes the person, level and link, and an open People page hears of it ([#643](https://github.com/Jacksondr5/j5code/issues/643)). A server that holds the lock but has not yet said where it listens is waited for as `pair` waits for a starting one: `pair.ts` exports `runtimeFileActivation` (its own retry count and delay, and `RuntimeFileActivationDelay`), and both commands pass it in. A server that cannot be reached gets nothing written behind it; one whose answer is lost after it was asked is reported as unconfirmed. With no server, the call holds the lock itself and writes through `pairingLinkForPerson`, whose `mint` is upstream's own `createPairingLink` call with the permissions J5 passes it. Without `--person`, `pair` refuses, listing the people on the server, and `auth pairing create` makes upstream's own link with no person recorded, so the device that pairs with it is asked whose it is: upstream's desktop app runs that bare command over SSH (`packages/ssh/src/tunnel.ts`). With `--person`, the call makes the link for a person whose name matches, at their levels, or creates the person at `--level` and scope, and records whose the link is (`PairingIntents`) in the same transaction. Upstream's `--scope` becomes the device's ceiling when it is given at all, so both commands take it through J5's `pairingScopesFlag` in place of upstream's `authScopesFlag` (the same flag, which also says whether it was given; on a pin advance, carry over any change upstream makes to `cli/authScopes.ts`). A `--scope` that gives nothing within the person's level is refused. Each command prints what it did, `pair` on stdout and `auth pairing create --json` on stderr so its JSON stays whole. `cli/pair.test.ts`'s `pair` cases pass `--person` and compare an Owner's permissions as a set. The edit is the imports, the flag spread, the scope flag and the one call in each file, and the `runtimeFileActivation` export: 2 files, about 70 lines. On a pin advance, if upstream builds the CLI's auth anywhere else, build it through `cliEnvironmentAuth`, and if upstream adds a command that makes a pairing link, give it the flags and the call. 80. A shared conversation shows each person's message as they typed it ([#636](https://github.com/Jacksondr5/j5code/issues/636), register D33, Shared conversations AC9 to AC11 and AC16). The server stores a person's message with the platform's lines at its start (a note, the author's line), names exactly that text as the message's `storedPrefix`, and records who answered each prompt (`j5.sharedConversation.listThreadAuthors`, read again on `subscribeThreadAuthorsChanges`); everything that reads them is J5-owned under `apps/web/src/j5/sharing/` (`sharedTimeline.ts`). `apps/web/src/components/chat/MessagesTimeline.tsx` carries 17 added and 3 changed lines: two J5 imports (eight lines as formatted), two comments, and the calls below (the size Jackson is shown for this new shape, provisionally approved by the orchestrator on 2026-10-18). In `ConversationTimeline` the `timelineEntries` prop is destructured as `timelineEntriesAsBuilt` and `const timelineEntries = useSharedConversationEntries(citationThreadRef, timelineEntriesAsBuilt)` follows `citationThreadRef`: each message is shown without the prefix, a note it carried becomes a notice entry before it (drawn through case 7's `renderThreadA2ADelivery`), and a message whose author has not been answered for yet is shown as typed here or held back for the moment. In `UserTimelineRow`, `const sharedAuthor = useSharedMessageAuthor(ctx.threadRef, row.message)` after `userMessage`; the row's `items-end` becomes `items-start` for another person's message, J5's `` goes before the intent marker (above the reader's own message it says only who edited it), and `MessageAuthorHeading` reads `sharedAuthor?.name ?? "You"`, so another person's message is upstream's own bubble, with its attachments and chips, on the left with their initials and name and no level. In `WorkEntryLogRow`, `` after the answer preview says who answered a settled prompt. The rows read the record of the thread they are in and ask nothing; only the entries hook opens the read and its change feed, so two timelines never mix. The entries hook also shows an answer to the agent's question without the server's mark (`PromptAnswer.storedPrefix`). `apps/web/src/components/ChatView.tsx` (6 added, 2 changed): one import, and in the rewind action `const typedText = sharedMessageTypedText(input.routeThreadRef, message)` before the rewind, which `recallableComposerPrompt` reads in place of `message.text`, so a rewound message comes back as typed. `apps/web/src/components/chat/QueuedRunsControl.tsx` (case 24 already edits it; one import and one call as formatted over seven lines): `const queued = useSharedQueuedRuns(props.environmentId, props.threadId, workflow?.queuedRuns ?? [])` in place of upstream's `workflow?.queuedRuns ?? []`, so the queue's rows, the edit-latest key and each row's Edit read and load a queued message as its author typed it. `apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx` (3 changed): the dismiss control of a dismissible question honours the card's `disabled` like its other controls (`disabled={isResponding || disabled}` and `if (!disabled)` before each `onDismiss`), so a Viewer sees it disabled; this is a fix upstream may take (#276). On a pin advance: if upstream stops building the timeline from `timelineEntries`, call the hook where the entries are built; if upstream builds the queue's rows from anything but `queuedRuns`, strip them there; if upstream reshapes the user row, keep the author line and the left alignment, or another person's message reads as the viewer's own; if upstream moves the prompt's answer preview, keep the answered-by line beside it; if upstream changes what a rewind restores, keep the typed text. @@ -469,7 +469,7 @@ migrations after upstream migrations. - Message search, the sidebar's and the command palette's: `apps/server/src/orchestration-v2/ThreadSearch.ts` imports J5-owned `typedMessageMatchesSql` and `typedMessageTextSql` (`apps/server/src/j5/sharing/typedMessageText.ts`). The candidate query keeps upstream's `LIKE` first and adds one condition after it: a row whose stored text begins with its recorded prefix must also match without it. The `ranked` step carries `message_id`, and the final select's `matchText` is the typed text, so the snippet shows the person's words and a word only in the note or the author line finds nothing. Both ask once a query whether any message carries a prefix (an uncorrelated `EXISTS`), so a server with no shared conversation reads nothing more per message; otherwise the condition reads the author record by its primary key, and the text is taken off only the rows returned. Every user match still reads "You:" (`ThreadSearchMatch.tsx`): naming the author would need a field on upstream's search contract, so it is left. - Generated thread title: `orchestration-v2/runtimeLayer.ts` provides J5-owned `titleSource.layer` (`apps/server/src/j5/sharing/titleSource.ts`) to `layerThreadTitleRegenerationProvided` alone (one import and one `Layer.provide`, as case 81 does). It decorates `ThreadManagementService.getThreadRecords` so each message the title generator reads, for a first title and a regeneration, has its prefix taken off, in one read of the thread's recorded prefixes. - - Fork: no upstream edit. A fork shows its source's messages through upstream's `buildVisibleTurnItems`, not as copies, so J5's `listThreadAuthors` (`SharedConversation.threadAuthors`) also returns the author records of the messages a fork shows, walking `forkedFrom` (type `run`) up its sources and keeping each source's messages through the forked-at run's ordinal, as upstream does. A fork's reader need not reach its source, so an inherited record is told only where the stored text the fork shows begins with its prefix, and so restates what the reader already receives: not at all for a slash command, whose prefix is empty, or for a record an edit wrote that upstream then refused. A record that is told is told in full when `PersonAccess.participantVisible` lets the reader know its writer, otherwise with only its prefix (no name, edited-by or note). Case 80's timeline hook then draws them as in the shared thread, with Copy message and rewind reading the typed text. + - Fork: no upstream edit. A fork shows its source's messages through upstream's `buildVisibleTurnItems`, not as copies, so J5's `listThreadAuthors` (`SharedConversation.threadAuthors`) also returns the author records of the messages a fork shows, walking `forkedFrom` (type `run`) up its sources and keeping each source's messages through the forked-at run's ordinal, as upstream does. A fork's reader need not reach its source, so an inherited record is told only where the stored text the fork shows begins with its prefix, and so restates what the reader already receives: not at all for a slash command, whose prefix is empty. A record that is told is told in full when `PersonAccess.participantVisible` lets the reader know its writer, otherwise with only its prefix (no name, edited-by or note). Case 80's timeline hook then draws them as in the shared thread, with Copy message and rewind reading the typed text. - Up-arrow recall: `apps/web/src/components/chat/ChatComposer.tsx` imports J5-owned `sharedPromptHistoryMessages` (`apps/web/src/j5/sharing/sharedTimeline.ts`) and passes the thread's messages through it where `navigatePromptHistory` builds its entries, on the key press (`null` for a draft). Each person's message is recalled as case 80's timeline hook last showed that message object: as typed, as stored when no one is recorded, and not at all while the timeline holds it back for its author or has not drawn it, since a recalled draft is not cleaned again. Recall is still upstream's: it offers the last user message in the thread, whoever sent it. `typedText` moved to `packages/contracts/src/j5/sharedConversation.ts` so the server and the web strip the same way. Mobile is not covered ([#609](https://github.com/Jacksondr5/j5code/issues/609)). Proof: `j5/sharing/typedMessageText.test.ts` (search, with and without a message that carries a prefix), `j5/sharing/titleSource.test.ts` (title), `j5/sharing/SharedConversation.test.ts`, "a fork names who wrote the messages it shows, and none after its fork point" and "a fork tells its reader only what they could know of who wrote before it" and "a fork tells an inherited record only where the stored text it shows begins with it", and `apps/web/src/j5/sharing/sharedTimeline.logic.test.ts`, "up-arrow recall in a shared conversation". On a pin advance: if upstream reshapes the search query, keep the typed text in both the snippet and the match, with no per-message read on a server without a prefix; if the title generator stops reading messages through `ThreadManagementService.getThreadRecords`, strip where it reads them; if upstream changes how a fork inherits messages (`forkedFrom`, run ordinals), change the lineage read with it; if upstream renames `navigatePromptHistory` or `buildComposerPromptHistoryEntries`, move the call with it. diff --git a/apps/server/src/j5/sharing/CommandAdmission.test.ts b/apps/server/src/j5/sharing/CommandAdmission.test.ts index 88b57f25e375..ec8f196ce966 100644 --- a/apps/server/src/j5/sharing/CommandAdmission.test.ts +++ b/apps/server/src/j5/sharing/CommandAdmission.test.ts @@ -21,10 +21,12 @@ const admitted = Effect.fn("test.admitted")(function* ( sent: OrchestrationV2Command, ) { const admission = yield* makeCommandAdmission(() => Effect.void, session as never); - return yield* admission.admit(sent).pipe( - Effect.as("admitted"), - Effect.catch((error) => Effect.succeed(`refused: ${error.message}`)), - ); + return yield* admission + .dispatchCommand(sent, () => Effect.void) + .pipe( + Effect.as("admitted"), + Effect.catch((error) => Effect.succeed(`refused: ${error.message}`)), + ); }); const deviceOf = Effect.fn("test.deviceOf")(function* ( diff --git a/apps/server/src/j5/sharing/CommandAdmission.ts b/apps/server/src/j5/sharing/CommandAdmission.ts index 6c241dd3ea56..583ec552405e 100644 --- a/apps/server/src/j5/sharing/CommandAdmission.ts +++ b/apps/server/src/j5/sharing/CommandAdmission.ts @@ -145,12 +145,6 @@ const OWNERS_ONLY = "Only an Owner of this server archives or deletes a thread, for now. Ask an Owner to do it."; export interface CommandAdmission { - readonly admit: ( - command: OrchestrationV2Command, - ) => Effect.Effect< - OrchestrationV2Command, - EnvironmentAuthorizationError | OrchestrationV2DispatchCommandError - >; /** * A person's command, admitted and then handed to upstream's `dispatch`. `ws.ts` wraps upstream's * dispatch with this (FORK.md case 78). @@ -228,43 +222,38 @@ export const makeCommandAdmission = ( if (!levelReaches(held, level)) return yield* refused(NOT_SHARED); }).pipe(Effect.catchTags({ PersonAccessStorageError: refuseUnreadable })); - const checked: CommandAdmission["admit"] = Effect.fn("j5.sharing.commandAdmission.checked")( - function* (command) { - if (OWNER_ONLY_COMMANDS.has(command.type)) { - const owner = - reach.kind === "service" || - (reach.kind === "person" && levelReaches(reach.serverLevel, "owner")); - if (!owner) return yield* refused(OWNERS_ONLY); - yield* crewSeatArchiveGuard(command).pipe( - Effect.mapError( - (cause) => - new OrchestrationV2DispatchCommandError({ - commandId: command.commandId, - commandType: command.type, - message: cause.message, - detail: cause.message, - cause, - }), - ), - ); - return command; - } - if (isWide(reach)) return command; - const scopeOf = NARROWED_COMMAND_SCOPES[command.type] as - | ((command: OrchestrationV2Command) => CommandScope) - | undefined; - if (scopeOf === undefined) return yield* refused(NOT_SHARED); - yield* requireLevel(scopeOf(command), "collaborator"); + const checked = Effect.fn("j5.sharing.commandAdmission.checked")(function* ( + command: OrchestrationV2Command, + ) { + if (OWNER_ONLY_COMMANDS.has(command.type)) { + const owner = + reach.kind === "service" || + (reach.kind === "person" && levelReaches(reach.serverLevel, "owner")); + if (!owner) return yield* refused(OWNERS_ONLY); + yield* crewSeatArchiveGuard(command).pipe( + Effect.mapError( + (cause) => + new OrchestrationV2DispatchCommandError({ + commandId: command.commandId, + commandType: command.type, + message: cause.message, + detail: cause.message, + cause, + }), + ), + ); return command; - }, - ); + } + if (isWide(reach)) return command; + const scopeOf = NARROWED_COMMAND_SCOPES[command.type] as + | ((command: OrchestrationV2Command) => CommandScope) + | undefined; + if (scopeOf === undefined) return yield* refused(NOT_SHARED); + yield* requireLevel(scopeOf(command), "collaborator"); + return command; + }); const person = reachPersonId(reach); - const admit: CommandAdmission["admit"] = (command) => - checked(command).pipe( - Effect.flatMap((admitted) => conversation.admit(person, admitted)), - Effect.withSpan("j5.sharing.commandAdmission.admit"), - ); // A person's edit of a queued agent message is recorded in the ledger under their name // (`queuedEdits.ts`). A failure to claim it names no one and does not stop the edit. @@ -287,13 +276,19 @@ export const makeCommandAdmission = ( ), ); const dispatchCommand: CommandAdmission["dispatchCommand"] = (command, dispatch) => - Effect.gen(function* () { - const admitted = yield* admit(command); - const claimed = yield* claimEdit(admitted); - return yield* dispatch(admitted).pipe( - Effect.tapError(() => (claimed ? releaseEdit(admitted) : Effect.void)), - ); - }); + checked(command).pipe( + Effect.flatMap((admitted) => + conversation.dispatch(person, admitted, (stamped) => + Effect.gen(function* () { + const claimed = yield* claimEdit(stamped); + return yield* dispatch(stamped).pipe( + Effect.tapError(() => (claimed ? releaseEdit(stamped) : Effect.void)), + ); + }), + ), + ), + Effect.withSpan("j5.sharing.commandAdmission.dispatchCommand"), + ); const admitLaunch: CommandAdmission["admitLaunch"] = Effect.fn( "j5.sharing.commandAdmission.admitLaunch", @@ -343,5 +338,5 @@ export const makeCommandAdmission = ( }); }; - return { admit, dispatchCommand, admitLaunch, upsertScheduledTask }; + return { dispatchCommand, admitLaunch, upsertScheduledTask }; }); diff --git a/apps/server/src/j5/sharing/SharedConversation.integration.test.ts b/apps/server/src/j5/sharing/SharedConversation.integration.test.ts index 9f62dfa2bf3b..4e5fd003882f 100644 --- a/apps/server/src/j5/sharing/SharedConversation.integration.test.ts +++ b/apps/server/src/j5/sharing/SharedConversation.integration.test.ts @@ -66,9 +66,10 @@ const send = Effect.fn("test.send")(function* ( command: OrchestrationV2Command, ) { const conversation = yield* SharedConversation.SharedConversation; - const admitted = yield* conversation.admit(personId, command); - yield* (yield* ThreadManagementService).dispatch(admitted); - return admitted; + const threads = yield* ThreadManagementService; + return yield* conversation.dispatch(personId, command, (admitted) => + threads.dispatch(admitted).pipe(Effect.as(admitted)), + ); }); const runs = (on: ThreadId) => @@ -272,3 +273,93 @@ it.effect( }).pipe(Effect.provide(layerFor(harness))); }, ); + +it.effect("an edit upstream refuses leaves its message's record as it was", () => { + const harness = makeHarness(); + const on = ThreadId.make("thread:shared-refused-edit"); + return Effect.gen(function* () { + const people = yield* PersonAccess.PersonAccess; + const conversation = yield* SharedConversation.SharedConversation; + const threads = yield* ThreadManagementService; + yield* threads.dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("command:refused-edit:create"), + threadId: on, + projectId, + title: "Shared", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + }); + const owner = (yield* people.firstOwner).personId; + yield* people.setName({ personId: owner, displayName: "Jackson" }); + const priya = yield* people.createPerson({ displayName: "Priya" }); + yield* people.setLevel({ + personId: priya.personId, + scope: { kind: "thread", threadId: on }, + level: "collaborator", + }); + // The first run stays active with no provider, so both of hers queue behind it. + yield* send(owner, message("Let us review the plan.", on)); + const refusedMessage = message("Keep the migration step.", on); + const acceptedMessage = message("Ship Friday.", on); + yield* send(priya.personId, refusedMessage); + yield* send(priya.personId, acceptedMessage); + const recordOf = (messageId: string) => + conversation + .threadAuthors(owner, on) + .pipe( + Effect.map((authors) => authors.authors.find((entry) => entry.messageId === messageId)!), + ); + const runOf = (messageId: string) => + threads + .getThreadProjection(on) + .pipe( + Effect.map( + (projection) => projection.runs.find((run) => run.userMessageId === messageId)!.id, + ), + ); + const before = yield* recordOf(refusedMessage.messageId); + const beforeText = yield* storedText(on, refusedMessage.messageId); + + // Its run leaves the queue before the owner's edit lands, so upstream refuses the edit. + yield* threads.dispatch({ + type: "queued-run.cancel", + commandId: CommandId.make("command:refused-edit:cancel"), + threadId: on, + runId: yield* runOf(refusedMessage.messageId), + }); + const refusal = yield* send(owner, { + type: "queued-run.edit", + commandId: CommandId.make("command:refused-edit:edit"), + threadId: on, + runId: yield* runOf(refusedMessage.messageId), + text: "Drop the migration step.", + }).pipe(Effect.flip); + assert.strictEqual(refusal._tag, "OrchestratorCommandRejectedError"); + assert.strictEqual(yield* storedText(on, refusedMessage.messageId), beforeText); + const after = yield* recordOf(refusedMessage.messageId); + assert.isNull(after.editedBy); + assert.strictEqual(after.storedPrefix, before.storedPrefix); + assert.deepStrictEqual(after, before); + + // An edit upstream takes is recorded. + yield* send(owner, { + type: "queued-run.edit", + commandId: CommandId.make("command:accepted-edit:edit"), + threadId: on, + runId: yield* runOf(acceptedMessage.messageId), + text: "Ship Monday.", + }); + const accepted = yield* recordOf(acceptedMessage.messageId); + assert.strictEqual(accepted.editedBy, "Jackson"); + assert.strictEqual( + yield* storedText(on, acceptedMessage.messageId), + `${accepted.storedPrefix}Ship Monday.`, + ); + }).pipe(Effect.provide(layerFor(harness))); +}); diff --git a/apps/server/src/j5/sharing/SharedConversation.test.ts b/apps/server/src/j5/sharing/SharedConversation.test.ts index 107e5d4cb74d..5b502cafb015 100644 --- a/apps/server/src/j5/sharing/SharedConversation.test.ts +++ b/apps/server/src/j5/sharing/SharedConversation.test.ts @@ -77,7 +77,7 @@ const send = Effect.fn("test.send")(function* ( command: OrchestrationV2Command, run: "completed" | "queued" | null = "completed", ) { - const admitted = yield* (yield* SharedConversation).admit(personId, command); + const admitted = yield* (yield* SharedConversation).dispatch(personId, command, Effect.succeed); if (admitted.type === "message.dispatch") { yield* taken(admitted.threadId, admitted.messageId, run, admitted.text); } @@ -157,7 +157,10 @@ it.effect("a thread only one person can write to is untouched and records nothin // A Viewer does not make a thread shared: they cannot write to it. yield* personWith("Sam", onThread(alone, "viewer")); const command = message(alone, "Run the tests."); - assert.strictEqual(yield* (yield* SharedConversation).admit(owner, command), command); + assert.strictEqual( + yield* (yield* SharedConversation).dispatch(owner, command, Effect.succeed), + command, + ); assert.deepStrictEqual(yield* authors(alone), { shared: false, authors: [], answers: [] }); }).pipe(Effect.provide(conversationLayer)), ); @@ -405,7 +408,7 @@ it.effect( const command = message(source, "/goal ship the migration"); yield* say(priya, command, "queued"); yield* edit(command.messageId, "/goal ship it"); - // Edited after its run started, so upstream refuses the edit and the stored text is Priya's. + // Recorded as Alice's edit while the stored text stays Priya's: a record its text doesn't carry. const refused = message(source, "Keep the migration step."); yield* say(priya, refused, "queued"); yield* edit(refused.messageId, "Drop the migration step."); @@ -542,7 +545,7 @@ it.effect("only the platform sends a context record of its own kind (AC8)", () = const forged = message(threadId, "Hi.", { context: { version: 1, records: [{ kind: "j5-shared-note", version: 1 }] }, }); - const outcome = yield* (yield* SharedConversation).admit(owner, forged).pipe( + const outcome = yield* (yield* SharedConversation).dispatch(owner, forged, Effect.succeed).pipe( Effect.flip, Effect.map((error) => error.message), ); @@ -659,7 +662,7 @@ it.effect("a message id is its sender's own: someone else's is refused, and thei // The owner sends with her message's id, or with one from before the thread was shared. for (const messageId of [hers.messageId, "message:before-sharing"]) { const refusal = yield* conversation - .admit(owner, message(threadId, "Do not ship it.", { messageId })) + .dispatch(owner, message(threadId, "Do not ship it.", { messageId }), Effect.succeed) .pipe(Effect.flip); assert.strictEqual(refusal.message, "This message was already sent."); } @@ -668,7 +671,7 @@ it.effect("a message id is its sender's own: someone else's is refused, and thei `; assert.deepStrictEqual(recorded, [{ person_id: priya, message_id: hers.messageId }]); // Her own retry of the same send goes on. - const retried = yield* conversation.admit(priya, hers); + const retried = yield* conversation.dispatch(priya, hers, Effect.succeed); assert.strictEqual(retried.type, "message.dispatch"); }).pipe(Effect.provide(conversationLayer)), ); @@ -774,12 +777,16 @@ it.effect( threadId: "thread:empty-launch" as ThreadId, projectId: PROJECT, } as unknown as OrchestrationV2ThreadLaunchInput); - yield* conversation.admit(owner, { - type: "thread.create", - commandId: CommandId.make("command:create"), - threadId: "thread:created" as ThreadId, - projectId: PROJECT, - } as unknown as OrchestrationV2Command); + yield* conversation.dispatch( + owner, + { + type: "thread.create", + commandId: CommandId.make("command:create"), + threadId: "thread:created" as ThreadId, + projectId: PROJECT, + } as unknown as OrchestrationV2Command, + Effect.succeed, + ); const recorded = yield* sql<{ readonly thread_id: string }>` SELECT thread_id FROM j5_a2a_shared_thread WHERE thread_id IN ('thread:empty-launch', 'thread:created') @@ -850,7 +857,7 @@ it.effect("a note steered into a running turn has not told the agent, so the nex // The first shared message is steered into that turn: upstream records it against the // running run, which has started, while the provider may refuse the steer every time. const steered = message(threadId, "Stop and check the tests."); - const admitted = yield* (yield* SharedConversation).admit(owner, steered); + const admitted = yield* (yield* SharedConversation).dispatch(owner, steered, Effect.succeed); assert.isTrue(hasNote((admitted as { readonly text: string }).text)); yield* sql` INSERT INTO orchestration_v2_projection_messages ( diff --git a/apps/server/src/j5/sharing/SharedConversation.ts b/apps/server/src/j5/sharing/SharedConversation.ts index 041c70f739ad..ecf5babcdcec 100644 --- a/apps/server/src/j5/sharing/SharedConversation.ts +++ b/apps/server/src/j5/sharing/SharedConversation.ts @@ -126,23 +126,35 @@ export const PROMPT_SETTLED_EVENT = const QUEUED = "queued" satisfies OrchestrationV2Run["status"]; +/** A command as it goes on to upstream, and what is written once upstream takes it. */ +interface Admitted { + readonly command: OrchestrationV2Command; + readonly accepted: Effect.Effect; +} + +const admitted = (command: OrchestrationV2Command): Admitted => ({ + command, + accepted: Effect.void, +}); + export interface SharedConversationShape { /** - * A client's command as it goes on to upstream, after `CommandAdmission` has checked that its - * sender may send it. `personId` is the person on the connection; `null` for a service session, - * whose commands are not a person's. A message for a shared conversation gains its author's line - * and any note due; an edit of one keeps its author's; an answer to a question carries who gave - * it. Who is answering a prompt is written down. A command carrying a context record of the - * platform's own kind is refused (AC8). + * A client's command taken in and handed to upstream's `dispatch`, after `CommandAdmission` has + * checked that its sender may send it. `personId` is the person on the connection; `null` for a + * service session, whose commands are not a person's. A message for a shared conversation gains + * its author's line and any note due; an edit of one keeps its author's; an answer to a question + * carries who gave it. Who is answering a prompt is written down. A command carrying a context + * record of the platform's own kind is refused (AC8). */ - readonly admit: ( + readonly dispatch: ( personId: ParticipantId | null, command: OrchestrationV2Command, - ) => Effect.Effect; + dispatch: (command: OrchestrationV2Command) => Effect.Effect, + ) => Effect.Effect; /** * A client's request to start a thread, as it goes on to upstream. A new thread's first message * does not come as a command: upstream's launch sends it itself, so it is taken in here as - * `admit` takes in a message. A thread born under a scope that is already shared is a shared + * `dispatch` takes in a message. A thread born under a scope that is already shared is a shared * conversation from its first message. */ readonly admitLaunch: ( @@ -315,7 +327,8 @@ const make = Effect.gen(function* () { * typed and carries nothing; edited out of one, it is stamped as a new message would be. A * message no person is recorded for is stamped too, so an edit never reaches the agent with no * line: under the first owner when they typed it before the thread was shared, else as the - * editor's own words. + * editor's own words. The record is written only once upstream takes the edit: upstream refuses + * one whose run has started, and the message then keeps the record its stored text carries. */ const stampEdit = Effect.fn("j5.sharing.sharedConversation.stampEdit")(function* ( command: Extract, @@ -323,7 +336,7 @@ const make = Effect.gen(function* () { ) { const messageId = yield* queuedMessageId(command.threadId, command.runId); // Not a queued run of this thread: upstream refuses the edit. - if (messageId === null) return command; + if (messageId === null) return admitted(command); const recorded = yield* messageAuthor(command.threadId, messageId); const original = recorded !== null @@ -359,7 +372,7 @@ const make = Effect.gen(function* () { recorded !== null && (yield* isScheduledRun(messageId)) ? scheduledLine : authorLine; const prefix = beginsWithSlash(typed) ? "" : prefixOf(carried.note, line(author, editedBy)); const createdAt = DateTime.formatIso(yield* DateTime.now); - yield* sql` + const record = sql` INSERT INTO j5_a2a_message_author ( thread_id, message_id, person_id, display_name, level, edited_by, note, told_json, stored_prefix, created_at @@ -373,9 +386,8 @@ const make = Effect.gen(function* () { note = excluded.note, told_json = excluded.told_json, edited_by = excluded.edited_by - `; - yield* touch(command.threadId); - return { ...command, text: `${prefix}${typed}` }; + `.pipe(Effect.andThen(touch(command.threadId)), Effect.asVoid); + return { command: { ...command, text: `${prefix}${typed}` }, accepted: record }; }); /** @@ -433,12 +445,12 @@ const make = Effect.gen(function* () { case "thread.create": { // A thread started under a scope already shared is shared from its start (AC6). yield* shared.isShared(command.threadId, command.projectId); - return command; + return admitted(command); } case "message.dispatch": { - if (!(yield* shared.isShared(command.threadId))) return command; + if (!(yield* shared.isShared(command.threadId))) return admitted(command); const author = yield* authorOn(personId, command.threadId); - if (author === null) return command; + if (author === null) return admitted(command); const text = yield* stampMessage( command.threadId, command.messageId, @@ -446,24 +458,24 @@ const make = Effect.gen(function* () { author, null, ); - return { ...command, text }; + return admitted({ ...command, text }); } case "queued-run.edit": { - if (!(yield* shared.isShared(command.threadId))) return command; + if (!(yield* shared.isShared(command.threadId))) return admitted(command); const editor = yield* authorOn(personId, command.threadId); - return editor === null ? command : yield* stampEdit(command, editor); + return editor === null ? admitted(command) : yield* stampEdit(command, editor); } case "runtime-request.respond": { // An answer in words says whose it is, as a message does; an approval carries no words. - if (command.answers === undefined) return command; - if (!(yield* shared.isShared(command.threadId))) return command; + if (command.answers === undefined) return admitted(command); + if (!(yield* shared.isShared(command.threadId))) return admitted(command); const author = yield* authorOn(personId, command.threadId); - return author === null - ? command - : { ...command, answers: answersFrom(command.answers, author) }; + return admitted( + author === null ? command : { ...command, answers: answersFrom(command.answers, author) }, + ); } default: - return command; + return admitted(command); } }); @@ -475,7 +487,11 @@ const make = Effect.gen(function* () { cause, }).pipe(Effect.andThen(Effect.fail(notAdmitted))); - const admit: SharedConversationShape["admit"] = (personId, command) => + // Upstream has already taken the edit, so a failure to record it is logged and does not undo it. + const notRecorded = (cause: unknown) => + Effect.logError("J5 shared conversation could not record a queued message's edit", { cause }); + + const dispatch: SharedConversationShape["dispatch"] = (personId, command, dispatchUpstream) => Effect.gen(function* () { if ( (command.type === "message.dispatch" || command.type === "queued-run.edit") && @@ -483,18 +499,20 @@ const make = Effect.gen(function* () { ) { return yield* refused("A message cannot carry a record of the platform's own."); } - if (personId === null) return command; - const admitted = yield* stampCommand(personId, command).pipe(Effect.catch(failClosed)); + if (personId === null) return yield* dispatchUpstream(command); + const stamp = yield* stampCommand(personId, command).pipe(Effect.catch(failClosed)); + const stamped = stamp.command; if ( - admitted.type === "runtime-request.respond" || - admitted.type === "thread.user-input.dismiss" + stamped.type === "runtime-request.respond" || + stamped.type === "thread.user-input.dismiss" ) { // An answer in words had its mark put on it above; a decision or a dismissal has none. - const marked = - admitted.type === "runtime-request.respond" && admitted.answers !== undefined; - yield* recordAnswer(personId, admitted, marked); + const marked = stamped.type === "runtime-request.respond" && stamped.answers !== undefined; + yield* recordAnswer(personId, stamped, marked); } - return admitted; + const result = yield* dispatchUpstream(stamped); + yield* stamp.accepted.pipe(Effect.catch(notRecorded)); + return result; }); const admitLaunch: SharedConversationShape["admitLaunch"] = (personId, input) => @@ -547,8 +565,7 @@ const make = Effect.gen(function* () { // (#612). Only the messages a fork shows are read, so nothing after its fork point is named. // A fork's reader need not reach the thread it was forked from, so for a reader an inherited // record is read only where the stored text the fork shows begins with its prefix: then it - // restates what they already receive. A command carries no prefix, and a record an edit wrote that - // upstream then refused names an editor the stored text does not. + // restates what they already receive. A command carries no prefix. const authors = yield* sql< AuthorRow & { readonly created_at: string; readonly inherited: 0 | 1 } >` @@ -756,7 +773,7 @@ const make = Effect.gen(function* () { ); return SharedConversation.of({ - admit, + dispatch, admitLaunch, threadAuthors, authorsChanges: (threadId) => diff --git a/apps/server/src/j5/sharing/linkJoinShared.test.ts b/apps/server/src/j5/sharing/linkJoinShared.test.ts index eb79e42a33e8..fa8cf2e1d197 100644 --- a/apps/server/src/j5/sharing/linkJoinShared.test.ts +++ b/apps/server/src/j5/sharing/linkJoinShared.test.ts @@ -42,17 +42,21 @@ it.effect("a person brought in as a Collaborator on a thread makes it shared as const priya = (yield* people.listPeople).find( (record) => record.person.displayName === "Priya", )!.person.personId; - const admitted = (yield* (yield* SharedConversation).admit(priya, { - type: "message.dispatch", - commandId: CommandId.make("command:first"), - threadId, - messageId: MessageId.make("message:first"), - text: "Hello.", - attachments: [], - createdBy: "user", - creationSource: "web", - dispatchMode: { type: "start_immediately" }, - } as unknown as OrchestrationV2Command)) as { readonly text: string }; + const admitted = (yield* (yield* SharedConversation).dispatch( + priya, + { + type: "message.dispatch", + commandId: CommandId.make("command:first"), + threadId, + messageId: MessageId.make("message:first"), + text: "Hello.", + attachments: [], + createdBy: "user", + creationSource: "web", + dispatchMode: { type: "start_immediately" }, + } as unknown as OrchestrationV2Command, + Effect.succeed, + )) as { readonly text: string }; assert.include(admitted.text, "Who can write: Jackson (owner), Priya (collaborator)."); assert.isTrue(admitted.text.endsWith("[Message from Priya (collaborator)]\n\nHello.")); }).pipe(Effect.provide(linksLayer.pipe(Layer.provideMerge(conversationLayer)))), diff --git a/apps/server/src/j5/sharing/scheduledRuns.test.ts b/apps/server/src/j5/sharing/scheduledRuns.test.ts index 01929c8e2058..0f87d1bd54ed 100644 --- a/apps/server/src/j5/sharing/scheduledRuns.test.ts +++ b/apps/server/src/j5/sharing/scheduledRuns.test.ts @@ -331,13 +331,17 @@ it.effect("someone else's edit of a queued run keeps it scheduled and says who e ${JSON.stringify({ createdBy: "user", creationSource: "web", scheduledTaskId: TASK })} ) `; - const edited = yield* (yield* SharedConversation).admit(owner, { - type: "queued-run.edit", - commandId: CommandId.make("command:edit"), - threadId, - runId: RunId.make(`run:${messageId}`), - text: "Check CI only.", - } as unknown as OrchestrationV2Command); + const edited = yield* (yield* SharedConversation).dispatch( + owner, + { + type: "queued-run.edit", + commandId: CommandId.make("command:edit"), + threadId, + runId: RunId.make(`run:${messageId}`), + text: "Check CI only.", + } as unknown as OrchestrationV2Command, + Effect.succeed, + ); assert.strictEqual( afterNote((edited as { readonly text: string }).text), "[Scheduled by Priya (collaborator), edited by Jackson (owner)]\n\nCheck CI only.", From 2bb3283646b6f9052d98d6170d2cb30754e446b3 Mon Sep 17 00:00:00 2001 From: Jackson Miller Date: Mon, 26 Oct 2026 22:07:40 -0400 Subject: [PATCH 2/2] fix(j5): an edit's record is written only while the stored text is its own Upstream serializes dispatch but releases its lock before J5 writes an accepted edit's record, so a later edit can commit and be recorded in between; and a retried command replays its receipt without changing the text. Either way the deferred write named an editor the stored text didn't carry. The write is now an INSERT ... SELECT conditioned, in the same statement, on the message's stored text being exactly the text this edit produced; otherwise it writes nothing. Co-Authored-By: Claude Opus 5.5 --- FORK.md | 2 +- .../SharedConversation.integration.test.ts | 93 +++++++++++++++++++ .../src/j5/sharing/SharedConversation.test.ts | 39 +++++--- .../src/j5/sharing/SharedConversation.ts | 18 ++-- 4 files changed, 133 insertions(+), 19 deletions(-) diff --git a/FORK.md b/FORK.md index ea44e77032bf..59581f7a44f4 100644 --- a/FORK.md +++ b/FORK.md @@ -439,7 +439,7 @@ migrations after upstream migrations. 75. Highlights, a client's "What's new" ([#624](https://github.com/Jacksondr5/j5code/issues/624), register D35, Jackson's 2026-10-17 decision and design). The entries, the client filter and the rule for what is new are J5-owned `packages/client-runtime/src/j5/highlights.ts`, reached through the `./j5/highlights` export this case appends to upstream-owned `packages/client-runtime/package.json`; the web button, list, art, seen record and palette entry are J5-owned files under `apps/web/src/j5/highlights/`. Four upstream files are touched. `apps/web/src/components/sidebar/SidebarChrome.tsx`: `SidebarUtilityMenu`'s `SidebarMenu` gains the class `@container/utility`, which the button's container query reads to hide itself where the row is too narrow, and `` is mounted immediately before `` (one import, one line). The button's item carries `ms-auto` and cancels the update button's own `ms-auto` with `[&+li]:ms-0`, so the two sit together at the end of the row. `apps/web/src/components/AppSidebarLayout.tsx` mounts `` after upstream's `` (one import, one line): the palette sits outside the sidebar provider, and this helper leaves a utility page and opens a collapsed sidebar when the palette asks for the list. `apps/web/src/components/CommandPalette.tsx` gains one import, one hook call (`useHighlightsPaletteItems()`, beside case 71's) and appends its items to case 71's `actionItems.push(...)`. `apps/web/src/onboarding/firstRun.ts`: `useCompleteOnboarding`, which every path that finishes first run calls (the wizard, the gate's silent completion for a client on an existing workspace, and hosted mode), calls `markAllHighlightsSeen()` before it writes `onboardingCompletedAt` (one import, one call). A finished client with no record is then an existing one, and the order makes that hold whenever the highlights code first reads it. On a pin advance: if upstream moves the utility row, the update button or `MainAppLocationTracker`, re-apply the mounts where they went; if upstream adds another writer of `onboardingCompletedAt`, it needs the same call before it; if upstream's palette `actionItems` moves, re-apply the append as in case 71. 76. Prompt links open J5's apps and j5.codes (registers D19 and D25, Jackson's 2026-10-17 and 2026-10-24 decisions). Upstream's prompt links (`packages/shared/src/promptLinks.ts`) are `t3code://` deep links and `https://app.t3.codes` links to its hosted app, which upstream's "Copy prompt link" makes. J5 has no hosted app; its shareable links point at `https://j5.codes/new?…`, a static page on J5's marketing site (`apps/marketing/src/pages/new.astro`, J5-owned) that shows the prompt and the hidden-characters warning and offers the `j5code://` link, the download page, and the same path on the person's own server. `promptLinks.ts` carries four J5 edits: `APP_SCHEME` accepts only `j5code` and its suffixed development schemes; a J5 constant `J5_PROMPT_LINK_ORIGIN` (`https://j5.codes`) is the default origin of `buildNewThreadLink` and of `promptLinkAppPath`, in place of upstream's `DEFAULT_HOSTED_APP_URL`, so app.t3.codes links are T3 Code's and j5.codes links open in J5's apps; `promptLinkDeepLink`'s default scheme is J5's production scheme (`J5_BRANDING.desktop.productionScheme`); and its error text names J5 Code. "Copy prompt link" on web (`promptLinkFor` in `apps/web/src/components/promptLinks/copyPromptLink.ts`) drops upstream's `origin: configuredHostedAppUrl()`, so it takes the j5.codes default; mobile's copy is upstream's and takes the same default. The thread form, `j5.codes//?prompt=…`, reaches the page through a rewrite in `apps/marketing/vercel.ts`. Upstream's user docs (`docs/user/prompt-links.md`, `default-browser.md`) keep their wording (D25). Proofs: `packages/shared/src/promptLinks.test.ts` (j5.codes links round-trip; T3 Code's scheme and hosted links are not J5's), `apps/marketing/src/lib/promptLink.test.ts`, and `apps/desktop/src/app/DesktopClerk.test.ts`. On a pin advance, keep the scheme, the j5.codes defaults and the web copy call over upstream's changes. 77. No Mobile app row in Settings (Jackson's 2026-10-09 ruling for case 61, applied to the row that replaced it at the 2026-10-17 advance). Upstream's Settings › General "Mobile app" row (`apps/web/src/components/settings/MobileAppSettingsRow.tsx`) shows QR codes and links for T3 Code's App Store and Google Play apps. J5 has no app in the stores, so the file adds `J5_HAS_STORE_MOBILE_APP = false` and the row renders nothing, and `searchSettings` in `settingsSearch.ts` skips the item `mobile-app` (two lines), so search does not offer it. On a pin advance, keep the constant and the skip over upstream's changes. -78. A person's commands are held to what their level and scope allow ([#636](https://github.com/Jacksondr5/j5code/issues/636), register D33, People and access AC13 and AC14). `layerWsRpc` in `apps/server/src/ws.ts` builds J5-owned `makeCommandAdmission(j5CrewSeatArchiveGuard, currentSession)` (`apps/server/src/j5/sharing/CommandAdmission.ts`) once per socket, which reads whose the socket is once, and returns upstream's handlers with `orchestration.dispatchCommand` and `orchestration.launchThread` each wrapped by one J5 call ahead of upstream's own, `j5Commands.dispatchCommand(command, upstream's handler)` and `j5Commands.admitLaunch(input)` (one import of `OrchestrationV2ThreadLaunchInput`, one of the admission, the line that builds it, and the two wrapped entries spread over upstream's handlers). A third entry wraps `scheduledTasks.upsert` (with one import of `ScheduledTaskUpsertInput`): `j5Commands.upsertScheduledTask(input, upstream's upsert)` records who scheduled the task as a person saves it, for case 81. The Crew seat guard of case 37 moved from the dispatch pipe into the admission. It refuses archiving, unarchiving and deleting a thread to anyone who is not an Owner, for now, and runs the Crew seat guard for those who are. For a narrowed person it checks every command type against the scope of the thread or project it names (`NARROWED_COMMAND_SCOPES`): a Collaborator writes within their scope, starts a thread only in a project they reach, and forks or merges back only within such a project; a Viewer sends nothing. A command type without a row is refused to a narrowed person, and the table is keyed by upstream's command types, so a type upstream renames or removes fails to compile. Once admitted, a command goes through J5-owned `SharedConversation.dispatch` in the same call, which puts the author's line and any note on a person's message in a shared conversation, keeps who answers a prompt, and records an edit of a queued message only once upstream takes it. `dispatchCommand` admits the command and then runs upstream's handler: a person's edit of a queued agent message is claimed under their name for J5's ledger before the handler runs, and the claim is released if upstream refuses the edit (#136). The admission reads that service from the socket's context, so the socket's layer is given the server's J5 services: one `Layer.provide(Layer.succeedContext(j5RpcServices))` beside the other server-lifetime services provided there. On a pin advance: if upstream adds a command type, decide its row; if upstream moves either handler, keep the wrap where it is built. +78. A person's commands are held to what their level and scope allow ([#636](https://github.com/Jacksondr5/j5code/issues/636), register D33, People and access AC13 and AC14). `layerWsRpc` in `apps/server/src/ws.ts` builds J5-owned `makeCommandAdmission(j5CrewSeatArchiveGuard, currentSession)` (`apps/server/src/j5/sharing/CommandAdmission.ts`) once per socket, which reads whose the socket is once, and returns upstream's handlers with `orchestration.dispatchCommand` and `orchestration.launchThread` each wrapped by one J5 call ahead of upstream's own, `j5Commands.dispatchCommand(command, upstream's handler)` and `j5Commands.admitLaunch(input)` (one import of `OrchestrationV2ThreadLaunchInput`, one of the admission, the line that builds it, and the two wrapped entries spread over upstream's handlers). A third entry wraps `scheduledTasks.upsert` (with one import of `ScheduledTaskUpsertInput`): `j5Commands.upsertScheduledTask(input, upstream's upsert)` records who scheduled the task as a person saves it, for case 81. The Crew seat guard of case 37 moved from the dispatch pipe into the admission. It refuses archiving, unarchiving and deleting a thread to anyone who is not an Owner, for now, and runs the Crew seat guard for those who are. For a narrowed person it checks every command type against the scope of the thread or project it names (`NARROWED_COMMAND_SCOPES`): a Collaborator writes within their scope, starts a thread only in a project they reach, and forks or merges back only within such a project; a Viewer sends nothing. A command type without a row is refused to a narrowed person, and the table is keyed by upstream's command types, so a type upstream renames or removes fails to compile. Once admitted, a command goes through J5-owned `SharedConversation.dispatch` in the same call, which puts the author's line and any note on a person's message in a shared conversation, keeps who answers a prompt, and records an edit of a queued message only once upstream takes it, and only while the message's stored text is still the edit's own. `dispatchCommand` admits the command and then runs upstream's handler: a person's edit of a queued agent message is claimed under their name for J5's ledger before the handler runs, and the claim is released if upstream refuses the edit (#136). The admission reads that service from the socket's context, so the socket's layer is given the server's J5 services: one `Layer.provide(Layer.succeedContext(j5RpcServices))` beside the other server-lifetime services provided there. On a pin advance: if upstream adds a command type, decide its row; if upstream moves either handler, keep the wrap where it is built. 79. The `j5` CLI knows whose a session is, and names the person a pairing link is for ([#636](https://github.com/Jacksondr5/j5code/issues/636), register D36, People and access AC4). `apps/server/src/cli/auth.ts` builds upstream's `EnvironmentAuth.layerRuntime` through J5-owned `cliEnvironmentAuth` (`apps/server/src/j5/sharing/AccessGate.ts`; one import and one call), so `auth session revoke` cuts the session loose from its person before upstream revokes it, and the session can never renew. Both `pair` and `auth pairing create` spread J5-owned `personPairingFlags` (`--person`, `--level`, `--project`, `--thread`; `apps/server/src/j5/sharing/cliPairing.ts`) into their flags, and make their link through one call, `pairingLinkFromCli({ config, flags, scopes, ttl, label, withoutPerson })`, which takes upstream's own `--ttl` and `--label` (`pair`'s default label `j5 pair` included). It replaces the body of `mintPairingLink` in `pair.ts`, which no longer builds auth of its own, and the handler of `auth pairing create`, which resolves upstream's config itself rather than through `runWithEnvironmentAuth`. While a server holds the home's lock (`serverOwnership.ts`), the call asks it to make the link (J5's route `POST /api/j5/people/pair`, `CliPairingHttp.ts`) with a session it issues itself in upstream's `j5 project` way, holding only `access:write` and living two minutes, and revokes it afterwards; the route answers only that subject (`cli-issued-session`), so the running server writes the person, level and link, and an open People page hears of it ([#643](https://github.com/Jacksondr5/j5code/issues/643)). A server that holds the lock but has not yet said where it listens is waited for as `pair` waits for a starting one: `pair.ts` exports `runtimeFileActivation` (its own retry count and delay, and `RuntimeFileActivationDelay`), and both commands pass it in. A server that cannot be reached gets nothing written behind it; one whose answer is lost after it was asked is reported as unconfirmed. With no server, the call holds the lock itself and writes through `pairingLinkForPerson`, whose `mint` is upstream's own `createPairingLink` call with the permissions J5 passes it. Without `--person`, `pair` refuses, listing the people on the server, and `auth pairing create` makes upstream's own link with no person recorded, so the device that pairs with it is asked whose it is: upstream's desktop app runs that bare command over SSH (`packages/ssh/src/tunnel.ts`). With `--person`, the call makes the link for a person whose name matches, at their levels, or creates the person at `--level` and scope, and records whose the link is (`PairingIntents`) in the same transaction. Upstream's `--scope` becomes the device's ceiling when it is given at all, so both commands take it through J5's `pairingScopesFlag` in place of upstream's `authScopesFlag` (the same flag, which also says whether it was given; on a pin advance, carry over any change upstream makes to `cli/authScopes.ts`). A `--scope` that gives nothing within the person's level is refused. Each command prints what it did, `pair` on stdout and `auth pairing create --json` on stderr so its JSON stays whole. `cli/pair.test.ts`'s `pair` cases pass `--person` and compare an Owner's permissions as a set. The edit is the imports, the flag spread, the scope flag and the one call in each file, and the `runtimeFileActivation` export: 2 files, about 70 lines. On a pin advance, if upstream builds the CLI's auth anywhere else, build it through `cliEnvironmentAuth`, and if upstream adds a command that makes a pairing link, give it the flags and the call. 80. A shared conversation shows each person's message as they typed it ([#636](https://github.com/Jacksondr5/j5code/issues/636), register D33, Shared conversations AC9 to AC11 and AC16). The server stores a person's message with the platform's lines at its start (a note, the author's line), names exactly that text as the message's `storedPrefix`, and records who answered each prompt (`j5.sharedConversation.listThreadAuthors`, read again on `subscribeThreadAuthorsChanges`); everything that reads them is J5-owned under `apps/web/src/j5/sharing/` (`sharedTimeline.ts`). `apps/web/src/components/chat/MessagesTimeline.tsx` carries 17 added and 3 changed lines: two J5 imports (eight lines as formatted), two comments, and the calls below (the size Jackson is shown for this new shape, provisionally approved by the orchestrator on 2026-10-18). In `ConversationTimeline` the `timelineEntries` prop is destructured as `timelineEntriesAsBuilt` and `const timelineEntries = useSharedConversationEntries(citationThreadRef, timelineEntriesAsBuilt)` follows `citationThreadRef`: each message is shown without the prefix, a note it carried becomes a notice entry before it (drawn through case 7's `renderThreadA2ADelivery`), and a message whose author has not been answered for yet is shown as typed here or held back for the moment. In `UserTimelineRow`, `const sharedAuthor = useSharedMessageAuthor(ctx.threadRef, row.message)` after `userMessage`; the row's `items-end` becomes `items-start` for another person's message, J5's `` goes before the intent marker (above the reader's own message it says only who edited it), and `MessageAuthorHeading` reads `sharedAuthor?.name ?? "You"`, so another person's message is upstream's own bubble, with its attachments and chips, on the left with their initials and name and no level. In `WorkEntryLogRow`, `` after the answer preview says who answered a settled prompt. The rows read the record of the thread they are in and ask nothing; only the entries hook opens the read and its change feed, so two timelines never mix. The entries hook also shows an answer to the agent's question without the server's mark (`PromptAnswer.storedPrefix`). `apps/web/src/components/ChatView.tsx` (6 added, 2 changed): one import, and in the rewind action `const typedText = sharedMessageTypedText(input.routeThreadRef, message)` before the rewind, which `recallableComposerPrompt` reads in place of `message.text`, so a rewound message comes back as typed. `apps/web/src/components/chat/QueuedRunsControl.tsx` (case 24 already edits it; one import and one call as formatted over seven lines): `const queued = useSharedQueuedRuns(props.environmentId, props.threadId, workflow?.queuedRuns ?? [])` in place of upstream's `workflow?.queuedRuns ?? []`, so the queue's rows, the edit-latest key and each row's Edit read and load a queued message as its author typed it. `apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx` (3 changed): the dismiss control of a dismissible question honours the card's `disabled` like its other controls (`disabled={isResponding || disabled}` and `if (!disabled)` before each `onDismiss`), so a Viewer sees it disabled; this is a fix upstream may take (#276). On a pin advance: if upstream stops building the timeline from `timelineEntries`, call the hook where the entries are built; if upstream builds the queue's rows from anything but `queuedRuns`, strip them there; if upstream reshapes the user row, keep the author line and the left alignment, or another person's message reads as the viewer's own; if upstream moves the prompt's answer preview, keep the answered-by line beside it; if upstream changes what a rewind restores, keep the typed text. diff --git a/apps/server/src/j5/sharing/SharedConversation.integration.test.ts b/apps/server/src/j5/sharing/SharedConversation.integration.test.ts index 4e5fd003882f..0649b9f1c541 100644 --- a/apps/server/src/j5/sharing/SharedConversation.integration.test.ts +++ b/apps/server/src/j5/sharing/SharedConversation.integration.test.ts @@ -363,3 +363,96 @@ it.effect("an edit upstream refuses leaves its message's record as it was", () = ); }).pipe(Effect.provide(layerFor(harness))); }); + +it.effect("an edit's record is written only while the stored text is the edit's own", () => { + const harness = makeHarness(); + const on = ThreadId.make("thread:shared-edit-race"); + return Effect.gen(function* () { + const people = yield* PersonAccess.PersonAccess; + const conversation = yield* SharedConversation.SharedConversation; + const threads = yield* ThreadManagementService; + yield* threads.dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("command:edit-race:create"), + threadId: on, + projectId, + title: "Shared", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + }); + const owner = (yield* people.firstOwner).personId; + yield* people.setName({ personId: owner, displayName: "Jackson" }); + const scope = { kind: "thread" as const, threadId: on }; + const priya = (yield* people.createPerson({ displayName: "Priya" })).personId; + const sam = (yield* people.createPerson({ displayName: "Sam" })).personId; + yield* people.setLevel({ personId: priya, scope, level: "collaborator" }); + yield* people.setLevel({ personId: sam, scope, level: "collaborator" }); + yield* send(owner, message("Let us review the plan.", on)); + const replayed = message("Ship Friday.", on); + const raced = message("Keep the migration step.", on); + yield* send(priya, replayed); + yield* send(priya, raced); + const runOf = (messageId: string) => + threads + .getThreadProjection(on) + .pipe( + Effect.map( + (projection) => projection.runs.find((run) => run.userMessageId === messageId)!.id, + ), + ); + const edit = (commandId: string, messageId: string, text: string) => + runOf(messageId).pipe( + Effect.map( + (runId) => + ({ + type: "queued-run.edit", + commandId: CommandId.make(commandId), + threadId: on, + runId, + text, + }) as const satisfies OrchestrationV2Command, + ), + ); + const recordOf = (messageId: string) => + conversation + .threadAuthors(owner, on) + .pipe( + Effect.map((authors) => authors.authors.find((entry) => entry.messageId === messageId)!), + ); + + // Jackson edits, Sam edits after him, and Jackson's client retries his command: upstream + // replays its receipt and leaves Sam's text, so the record stays Sam's. + const jacksons = yield* edit("command:edit-race:jackson", replayed.messageId, "Ship Monday."); + yield* send(owner, jacksons); + yield* send(sam, yield* edit("command:edit-race:sam", replayed.messageId, "Ship Tuesday.")); + const samsRecord = yield* recordOf(replayed.messageId); + assert.strictEqual(samsRecord.editedBy, "Sam"); + yield* send(owner, jacksons); + assert.deepStrictEqual(yield* recordOf(replayed.messageId), samsRecord); + assert.strictEqual( + yield* storedText(on, replayed.messageId), + `${samsRecord.storedPrefix}Ship Tuesday.`, + ); + + // Sam's edit is taken and recorded after Jackson's commits and before Jackson's is recorded: + // the record stays Sam's, which the stored text carries. + const samsEdit = yield* edit("command:edit-race:sam-2", raced.messageId, "Drop it."); + yield* conversation.dispatch( + owner, + yield* edit("command:edit-race:jackson-2", raced.messageId, "Keep it."), + (admitted) => + threads.dispatch(admitted).pipe(Effect.andThen(send(sam, samsEdit)), Effect.as(admitted)), + ); + const raceRecord = yield* recordOf(raced.messageId); + assert.strictEqual(raceRecord.editedBy, "Sam"); + assert.strictEqual( + yield* storedText(on, raced.messageId), + `${raceRecord.storedPrefix}Drop it.`, + ); + }).pipe(Effect.provide(layerFor(harness))); +}); diff --git a/apps/server/src/j5/sharing/SharedConversation.test.ts b/apps/server/src/j5/sharing/SharedConversation.test.ts index 5b502cafb015..50aafb522458 100644 --- a/apps/server/src/j5/sharing/SharedConversation.test.ts +++ b/apps/server/src/j5/sharing/SharedConversation.test.ts @@ -68,16 +68,32 @@ const message = (threadId: ThreadId, text: string, extra: Record [entry.messageId, entry.editedBy]), [ [command.messageId, "Alice"], - [refused.messageId, "Alice"], + [rewritten.messageId, null], [accepted.messageId, "Alice"], ], ); diff --git a/apps/server/src/j5/sharing/SharedConversation.ts b/apps/server/src/j5/sharing/SharedConversation.ts index ecf5babcdcec..11ebc40914ab 100644 --- a/apps/server/src/j5/sharing/SharedConversation.ts +++ b/apps/server/src/j5/sharing/SharedConversation.ts @@ -327,8 +327,10 @@ const make = Effect.gen(function* () { * typed and carries nothing; edited out of one, it is stamped as a new message would be. A * message no person is recorded for is stamped too, so an edit never reaches the agent with no * line: under the first owner when they typed it before the thread was shared, else as the - * editor's own words. The record is written only once upstream takes the edit: upstream refuses - * one whose run has started, and the message then keeps the record its stored text carries. + * editor's own words. The record is written only once upstream takes the edit, and only while the + * stored text is still the text this edit wrote: upstream refuses an edit whose run has started, + * replays a retried command's receipt without writing again, and may take another edit between + * this one's commit and its record. In each case the message keeps the record its text carries. */ const stampEdit = Effect.fn("j5.sharing.sharedConversation.stampEdit")(function* ( command: Extract, @@ -372,22 +374,26 @@ const make = Effect.gen(function* () { recorded !== null && (yield* isScheduledRun(messageId)) ? scheduledLine : authorLine; const prefix = beginsWithSlash(typed) ? "" : prefixOf(carried.note, line(author, editedBy)); const createdAt = DateTime.formatIso(yield* DateTime.now); + const text = `${prefix}${typed}`; + // Checked in the same statement as the write, so no edit can land between the check and it. const record = sql` INSERT INTO j5_a2a_message_author ( thread_id, message_id, person_id, display_name, level, edited_by, note, told_json, stored_prefix, created_at - ) VALUES ( - ${command.threadId}, ${messageId}, ${author.personId}, ${author.displayName}, + ) + SELECT ${command.threadId}, ${messageId}, ${author.personId}, ${author.displayName}, ${author.level}, ${editedBy === null ? null : editorName(editedBy)}, ${carried.note}, ${carried.told}, ${prefix}, ${createdAt} - ) + FROM orchestration_v2_projection_messages + WHERE message_id = ${messageId} AND thread_id = ${command.threadId} + AND json_extract(payload_json, '$.text') = ${text} ON CONFLICT (thread_id, message_id) DO UPDATE SET stored_prefix = excluded.stored_prefix, note = excluded.note, told_json = excluded.told_json, edited_by = excluded.edited_by `.pipe(Effect.andThen(touch(command.threadId)), Effect.asVoid); - return { command: { ...command, text: `${prefix}${typed}` }, accepted: record }; + return { command: { ...command, text }, accepted: record }; }); /**