diff --git a/FORK.md b/FORK.md index 7f034a036e783..93a1b6de2f8f7 100644 --- a/FORK.md +++ b/FORK.md @@ -446,7 +446,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 ``, the last child of its `SidebarProvider` (one import, one line; upstream dropped `MainAppLocationTracker`, beside which it sat, at v0.1.3): 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 and appends J5's `HIGHLIGHTS_PALETTE_ITEMS` to case 71's `actionItems.push(...)`. `apps/web/src/onboarding/firstRun.ts`: `completeOnboarding`, 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 the `SidebarProvider`'s children, 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 › About "Mobile app" row (in General until v0.1.3) (`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 `settingsForThisPlatform` in `settingsSearch.ts`, upstream's filter of the settings a platform has, leaves out 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 builds `admittedHandlers`, 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 wrapped entries spread over upstream's handlers). Upstream serves its handlers as two groups, so its `splitHandlers` and `otherHandlers` `Pick`s are typed from `admittedHandlers`, and J5's checks run before the split. 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. Upstream's Stop is the `thread.stop` command since the 2026-10-24 advance, with a row like `run.interrupt`'s, so a Collaborator on the thread can press it. 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. +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 builds `admittedHandlers`, upstream's handlers with `orchestration.dispatchCommand` and `orchestration.launchThread` each wrapped by one J5 call around upstream's own, `j5Commands.dispatchCommand(command, upstream's handler)` and `j5Commands.launchThread(input, upstream's handler)` (one import of `OrchestrationV2ThreadLaunchInput`, one of the admission, the line that builds it, and the wrapped entries spread over upstream's handlers). Upstream serves its handlers as two groups, so its `splitHandlers` and `otherHandlers` `Pick`s are typed from `admittedHandlers`, and J5's checks run before the split. 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. Upstream's Stop is the `thread.stop` command since the 2026-10-24 advance, with a row like `run.interrupt`'s, so a Collaborator on the thread can press it. 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. A new message's record is written as it is admitted, which holds its id, and is released if upstream refuses it and stored no message under that id. `launchThread` does the same for a launch's first message through `SharedConversation.launch`, around upstream's launch. `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, four looks a second apart (`cliPairing.ts`, J5's own bound since upstream's `pair` stopped waiting for a starting server at the 2026-10-24 advance; register D21, retired). 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, and its IPv6 Tailscale case gives its runtime record an owner id, since its fake `ps` would otherwise make the record read as a live pre-lock server. The edit is the imports, the flag spread, the scope flag and the one call in each file: 2 files, about 60 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`). Upstream split the timeline into several files at the 2026-10-24 advance, and the edits moved with the code. In `apps/web/src/components/chat/MessagesTimeline.tsx`, `ConversationTimeline` destructures the `timelineEntries` prop 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 left off the minimap by `isSharedNote` in case 24's J5-owned classifier, `apps/web/src/j5/a2a/minimapMessages.ts`), and a message whose author has not been answered for yet is shown as typed here or held back for the moment. In `apps/web/src/components/chat/TimelineUserMessageRow.tsx`, `UserTimelineRow` reads `const sharedAuthor = useSharedMessageAuthor(ctx.threadRef, row.message)` after `userMessage`; the row is `items-start` instead of `items-end` for another person's message, the author slot before the intent marker draws `SharedMessageAuthorLine` (above the reader's own message it says only who edited it) through case 7's `J5MessageAuthorLine`, which shares the slot, and `MessageAuthorHeading` reads `sharedAuthor?.name` first, 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 `apps/web/src/components/chat/TimelineWorkEntryRow.tsx`, `` 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/chat/chatViewSend.ts`, where upstream moved the rewind out of `ChatView.tsx`: one import, and `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. Upstream's `MessagesTimeline.browser.test.tsx` and `QueuedRunsControl.browser.test.tsx` mock the shared-conversation hooks as pass-throughs, because the queries those hooks make would otherwise be answered by the tests' own mocks. `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/CommandAdmission.test.ts b/apps/server/src/j5/sharing/CommandAdmission.test.ts index 917becb988ea7..7730ea43d0a97 100644 --- a/apps/server/src/j5/sharing/CommandAdmission.test.ts +++ b/apps/server/src/j5/sharing/CommandAdmission.test.ts @@ -153,10 +153,15 @@ it.layer(conversationLayer)("CommandAdmission", (it) => { ]); const admission = yield* makeCommandAdmission(() => Effect.void, projectOnly); const launch = (projectId: string) => - admission.admitLaunch({ projectId } as unknown as OrchestrationV2ThreadLaunchInput).pipe( - Effect.as("admitted"), - Effect.orElseSucceed(() => "refused"), - ); + admission + .launchThread( + { projectId } as unknown as OrchestrationV2ThreadLaunchInput, + Effect.succeed, + ) + .pipe( + Effect.as("admitted"), + Effect.orElseSucceed(() => "refused"), + ); assert.strictEqual(yield* launch(PROJECT), "admitted"); assert.strictEqual(yield* launch(OTHER_PROJECT), "refused"); }), diff --git a/apps/server/src/j5/sharing/CommandAdmission.ts b/apps/server/src/j5/sharing/CommandAdmission.ts index 044c0247803d2..593d1bfd28c57 100644 --- a/apps/server/src/j5/sharing/CommandAdmission.ts +++ b/apps/server/src/j5/sharing/CommandAdmission.ts @@ -145,9 +145,11 @@ export interface CommandAdmission { command: OrchestrationV2Command, dispatch: (command: OrchestrationV2Command) => Effect.Effect, ) => Effect.Effect; - readonly admitLaunch: ( + /** A person's launch of a thread, admitted and then handed to upstream's launch (FORK.md case 78). */ + readonly launchThread: ( input: OrchestrationV2ThreadLaunchInput, - ) => Effect.Effect; + launch: (input: OrchestrationV2ThreadLaunchInput) => Effect.Effect, + ) => Effect.Effect; /** * A person's save of a scheduled task, with who scheduled it recorded: whoever creates it, and * whoever changes its prompt (`scheduledRuns`). `ws.ts` wraps upstream's upsert with this @@ -294,16 +296,19 @@ export const makeCommandAdmission = Effect.fn("j5.sharing.commandAdmission.makeC Effect.withSpan("j5.sharing.commandAdmission.dispatchCommand"), ); - const admitLaunch: CommandAdmission["admitLaunch"] = Effect.fn( - "j5.sharing.commandAdmission.admitLaunch", - )(function* (input) { + const launchThread: CommandAdmission["launchThread"] = Effect.fn( + "j5.sharing.commandAdmission.launchThread", + )(function* ( + input: OrchestrationV2ThreadLaunchInput, + launch: (input: OrchestrationV2ThreadLaunchInput) => Effect.Effect, + ) { // Launching into a thread that exists writes to it; otherwise it starts one in a project. const scope: CommandScope = input.reuseExistingThread === true && input.threadId !== undefined ? { kind: "thread", threadId: input.threadId } : { kind: "project", projectId: input.projectId }; yield* requireLevel(scope, "collaborator"); - return yield* conversation.admitLaunch(person, input); + return yield* conversation.launch(person, input, launch); }); const upsertScheduledTask: CommandAdmission["upsertScheduledTask"] = (input, upsert) => { @@ -342,6 +347,6 @@ export const makeCommandAdmission = Effect.fn("j5.sharing.commandAdmission.makeC }); }; - return { dispatchCommand, admitLaunch, upsertScheduledTask }; + return { dispatchCommand, launchThread, upsertScheduledTask }; }, ); diff --git a/apps/server/src/j5/sharing/SharedConversation.integration.test.ts b/apps/server/src/j5/sharing/SharedConversation.integration.test.ts index e32ff4daa3fac..f3eb623fd686d 100644 --- a/apps/server/src/j5/sharing/SharedConversation.integration.test.ts +++ b/apps/server/src/j5/sharing/SharedConversation.integration.test.ts @@ -7,7 +7,9 @@ import { type OrchestrationV2Command, type OrchestrationV2ThreadLaunchInput, ProviderDriverKind, + ProjectId, ProviderSessionId, + RunId, RuntimeRequestId, ThreadId, } from "@t3tools/contracts"; @@ -259,16 +261,21 @@ it.effect( attachments: [], }, } as const satisfies OrchestrationV2ThreadLaunchInput; - const admitted = yield* conversation.admitLaunch(owner, launch); - yield* launches.launch({ - ...launch, - initialMessage: { ...launch.initialMessage, text: admitted.initialMessage!.text }, - createdBy: "user", - creationSource: "web", - }); + yield* conversation.launch(owner, launch, (admitted) => + launches.launch({ + ...launch, + initialMessage: { ...launch.initialMessage, text: admitted.initialMessage!.text }, + createdBy: "user", + creationSource: "web", + }), + ); const first = yield* storedText(on, launch.initialMessage.messageId); assert.include(first, "Who can write: Jackson (owner), Priya (collaborator)."); assert.isTrue(first?.endsWith("\n[Message from Jackson (owner)]\n\nLet us review the plan.")); + const recorded = (yield* conversation.threadAuthors(owner, on)).authors.find( + (author) => author.messageId === launch.initialMessage.messageId, + )!; + assert.strictEqual(first, `${recorded.storedPrefix}Let us review the plan.`); // Her `/compact` goes on as typed, so upstream takes it for the command it is (AC5). const compact = message("/compact", on); @@ -562,3 +569,208 @@ it.effect("a person's approval feedback, written by upstream, is recorded as the assert.deepStrictEqual(yield* named(priya.personId), [[written.id, "Priya", true]]); }).pipe(Effect.provide(Layer.provideMerge(ProjectionStore.layer, layerFor(harness)))); }); + +/** The author record J5 keeps for a message, or none. */ +const authorRecord = (messageId: string) => + SqlClient.SqlClient.use( + (sql) => sql<{ readonly display_name: string | null; readonly stored_prefix: string }>` + SELECT display_name, stored_prefix FROM j5_a2a_message_author + WHERE message_id = ${messageId} + `, + ).pipe(Effect.map((rows) => rows[0] ?? null)); + +it.effect( + "a new message upstream refuses leaves no author record, and its retry is recorded", + () => { + const harness = makeHarness(); + const on = ThreadId.make("thread:shared-refused-message"); + return Effect.gen(function* () { + const people = yield* PersonAccess.PersonAccess; + const threads = yield* ThreadManagementService; + yield* threads.dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("command:refused-message: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", + }); + + // Upstream refuses to continue a run the thread never had, so nothing is stored. + const typed = "Pick up where you left off."; + const refused = { + ...message(typed, on), + manualContinuationOfRunId: RunId.make("run:never-ran"), + } satisfies OrchestrationV2Command; + const refusal = yield* send(priya.personId, refused).pipe(Effect.flip); + assert.strictEqual(refusal._tag, "OrchestratorDispatchError"); + assert.isUndefined(yield* storedText(on, refused.messageId)); + assert.isNull(yield* authorRecord(refused.messageId)); + + // She is renamed, then sends it again under the same id: it is recorded as now sent. + yield* people.setName({ personId: priya.personId, displayName: "Priya Shah" }); + const retried = { ...message(typed, on), messageId: refused.messageId }; + yield* send(priya.personId, retried); + const record = (yield* authorRecord(refused.messageId))!; + assert.strictEqual(record.display_name, "Priya Shah"); + assert.include(record.stored_prefix, "[Message from Priya Shah (collaborator)]"); + assert.strictEqual( + yield* storedText(on, refused.messageId), + `${record.stored_prefix}${typed}`, + ); + }).pipe(Effect.provide(layerFor(harness))); + }, +); + +it.effect( + "a message's id is held from admission, and its record kept once upstream stored it", + () => { + const harness = makeHarness(); + const on = ThreadId.make("thread:shared-held-id"); + 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:held-id: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" }); + + // Sam sends under her id while hers is still on its way to upstream: his is refused. + const hers = message("Ship Friday.", on); + const samsRefusal = yield* conversation.dispatch(priya, hers, (admitted) => + send(sam, { ...message("Ship Monday.", on), messageId: hers.messageId }).pipe( + Effect.flip, + Effect.tap(() => threads.dispatch(admitted)), + ), + ); + assert.strictEqual(samsRefusal.message, "This message was already sent."); + const record = (yield* authorRecord(hers.messageId))!; + assert.strictEqual(record.display_name, "Priya"); + assert.strictEqual( + yield* storedText(on, hers.messageId), + `${record.stored_prefix}Ship Friday.`, + ); + + // Upstream stores her next message, then the request fails: the message keeps its record. + const late = message("Keep the migration step.", on); + yield* conversation + .dispatch(priya, late, (admitted) => + threads.dispatch(admitted).pipe(Effect.andThen(Effect.fail("lost after commit"))), + ) + .pipe(Effect.flip); + const kept = (yield* authorRecord(late.messageId))!; + assert.strictEqual(kept.display_name, "Priya"); + assert.strictEqual( + yield* storedText(on, late.messageId), + `${kept.stored_prefix}Keep the migration step.`, + ); + + // Her client retries a send still on its way to upstream, and the retry fails first: it + // releases nothing, so the first attempt's record stands once upstream takes it. + const pending = message("Ship it.", on); + yield* conversation.dispatch(priya, pending, (admitted) => + conversation + .dispatch(priya, pending, () => Effect.fail("retry refused")) + .pipe(Effect.flip, Effect.andThen(threads.dispatch(admitted))), + ); + const survived = (yield* authorRecord(pending.messageId))!; + assert.strictEqual(survived.display_name, "Priya"); + assert.strictEqual( + yield* storedText(on, pending.messageId), + `${survived.stored_prefix}Ship it.`, + ); + }).pipe(Effect.provide(layerFor(harness))); + }, +); + +it.effect("a launch upstream refuses leaves no author record for its first message", () => { + const harness = makeHarness(); + const on = ThreadId.make("thread:shared-refused-launch"); + const gone = ProjectId.make("project:gone"); + return Effect.gen(function* () { + const people = yield* PersonAccess.PersonAccess; + const conversation = yield* SharedConversation.SharedConversation; + const launches = yield* ThreadLaunch.ThreadLaunchService; + const owner = (yield* people.firstOwner).personId; + yield* people.setName({ personId: owner, displayName: "Jackson" }); + const priya = yield* people.createPerson({ displayName: "Priya" }); + for (const scoped of [projectId, gone]) { + yield* people.setLevel({ + personId: priya.personId, + scope: { kind: "project", projectId: scoped }, + level: "collaborator", + }); + } + const launch = (into: ProjectId, commandId: string) => { + const input = { + commandId: CommandId.make(commandId), + threadId: on, + projectId: into, + title: "Review the plan", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + workspaceStrategy: { type: "root" }, + initialMessage: { + messageId: MessageId.make("message:refused-launch"), + text: "Let us review the plan.", + attachments: [], + }, + } as const satisfies OrchestrationV2ThreadLaunchInput; + return conversation.launch(owner, input, (admitted) => + launches.launch({ + ...input, + initialMessage: { ...input.initialMessage, text: admitted.initialMessage!.text }, + createdBy: "user", + creationSource: "web", + }), + ); + }; + + // Upstream refuses a launch into a project it does not have. + const refusal = yield* launch(gone, "command:refused-launch").pipe(Effect.flip); + assert.strictEqual(refusal._tag, "ThreadLaunchError"); + assert.isNull(yield* authorRecord("message:refused-launch")); + + yield* people.setName({ personId: owner, displayName: "Jackson Miller" }); + yield* launch(projectId, "command:accepted-launch"); + const record = (yield* authorRecord("message:refused-launch"))!; + assert.include(record.stored_prefix, "[Message from Jackson Miller (owner)]"); + assert.strictEqual( + yield* storedText(on, "message:refused-launch"), + `${record.stored_prefix}Let us review the plan.`, + ); + }).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 f0688887c79ec..39d02c5e28735 100644 --- a/apps/server/src/j5/sharing/SharedConversation.test.ts +++ b/apps/server/src/j5/sharing/SharedConversation.test.ts @@ -647,7 +647,7 @@ it.effect("a thread started in a project already shared is shared from its first attachments: [], }, } as unknown as OrchestrationV2ThreadLaunchInput; - const admitted = yield* conversation.admitLaunch(owner, launch); + const admitted = yield* conversation.launch(owner, launch, Effect.succeed); const text = admitted.initialMessage!.text; assert.include(text, "Who can write: Jackson (owner), Priya (collaborator)."); // A new thread has no messages from before. @@ -659,7 +659,7 @@ it.effect("a thread started in a project already shared is shared from its first threadId: "thread:alone", projectId: ProjectId.make("project:other"), } as OrchestrationV2ThreadLaunchInput; - assert.strictEqual(yield* conversation.admitLaunch(owner, elsewhere), elsewhere); + assert.strictEqual(yield* conversation.launch(owner, elsewhere, Effect.succeed), elsewhere); }).pipe(Effect.provide(conversationLayer)), ); @@ -1185,11 +1185,15 @@ it.effect( { scope: { kind: "project", projectId: PROJECT }, level: "collaborator" }, ]); const conversation = yield* SharedConversation; - yield* conversation.admitLaunch(owner, { - commandId: CommandId.make("command:empty-launch"), - threadId: "thread:empty-launch" as ThreadId, - projectId: PROJECT, - } as unknown as OrchestrationV2ThreadLaunchInput); + yield* conversation.launch( + owner, + { + commandId: CommandId.make("command:empty-launch"), + threadId: "thread:empty-launch" as ThreadId, + projectId: PROJECT, + } as unknown as OrchestrationV2ThreadLaunchInput, + Effect.succeed, + ); yield* conversation.dispatch( owner, { diff --git a/apps/server/src/j5/sharing/SharedConversation.ts b/apps/server/src/j5/sharing/SharedConversation.ts index 050dbfa4e1376..7458a740f0d50 100644 --- a/apps/server/src/j5/sharing/SharedConversation.ts +++ b/apps/server/src/j5/sharing/SharedConversation.ts @@ -137,15 +137,20 @@ const MESSAGE_WRITTEN_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; +/** + * A command or launch as it goes on to upstream, what is written once upstream takes it, and + * what is undone if upstream refuses it. + */ +interface Admitted { + readonly command: C; readonly accepted: Effect.Effect; + readonly refused: Effect.Effect; } -const admitted = (command: OrchestrationV2Command): Admitted => ({ +const admitted = (command: C): Admitted => ({ command, accepted: Effect.void, + refused: Effect.void, }); export interface SharedConversationShape { @@ -161,15 +166,16 @@ export interface SharedConversationShape { 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 - * `dispatch` takes in a message. A thread born under a scope that is already shared is a shared - * conversation from its first message. + * A client's request to start a thread, handed to upstream's launch. 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 `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: ( + readonly launch: ( personId: ParticipantId | null, input: OrchestrationV2ThreadLaunchInput, - ) => Effect.Effect; + launch: (input: OrchestrationV2ThreadLaunchInput) => Effect.Effect, + ) => Effect.Effect; /** Who sent each message and answered each prompt in a thread, for anyone who reads it. */ readonly threadAuthors: ( viewer: ParticipantId | null, @@ -250,8 +256,9 @@ const make = Effect.gen(function* () { )`; /** - * A person's message taken in on a shared thread: recorded under its author, and returned as - * the agent will read it. A command goes on as typed (AC5). + * A person's message taken in on a shared thread: recorded under its author, which reserves its + * id, and returned as the agent will read it. A command goes on as typed (AC5). If upstream + * refuses it, the record is released, unless upstream stored a message under the id after all. */ const stampMessage = Effect.fn("j5.sharing.sharedConversation.stampMessage")(function* ( threadId: ThreadId, @@ -260,14 +267,32 @@ const make = Effect.gen(function* () { author: Author, launchingIn: ProjectId | null, ) { + // An attempt releases only the record it wrote: an overlapping retry's holds the earlier one's. + const releaseIf = (reserved: boolean) => + reserved + ? sql` + DELETE FROM j5_a2a_message_author + WHERE thread_id = ${threadId} AND message_id = ${messageId} + AND person_id = ${author.personId} + AND NOT EXISTS ( + SELECT 1 FROM orchestration_v2_projection_messages WHERE message_id = ${messageId} + ) + `.pipe(Effect.andThen(touch(threadId)), Effect.asVoid) + : Effect.void; if (beginsWithSlash(text)) { - yield* recordAuthor(threadId, messageId, author, { note: null, told: null }, ""); - return text; + const reserved = yield* recordAuthor( + threadId, + messageId, + author, + { note: null, told: null }, + "", + ); + return { text, release: releaseIf(reserved) }; } const carried = yield* announce(threadId, launchingIn); const prefix = prefixOf(carried.note, authorLine(author)); - yield* recordAuthor(threadId, messageId, author, carried, prefix); - return `${prefix}${text}`; + const reserved = yield* recordAuthor(threadId, messageId, author, carried, prefix); + return { text: `${prefix}${text}`, release: releaseIf(reserved) }; }); /** The message a queued run would deliver, by upstream's own record of the run. */ @@ -379,7 +404,7 @@ const make = Effect.gen(function* () { told_json = excluded.told_json, edited_by = excluded.edited_by `.pipe(Effect.andThen(touch(command.threadId)), Effect.asVoid); - return { command: { ...command, text }, accepted: record }; + return { ...admitted({ ...command, text }), accepted: record }; }); /** @@ -485,14 +510,14 @@ const make = Effect.gen(function* () { if (!(yield* shared.isShared(command.threadId))) return admitted(command); const author = yield* authorOn(personId, command.threadId); if (author === null) return admitted(command); - const text = yield* stampMessage( + const stamp = yield* stampMessage( command.threadId, command.messageId, command.text, author, null, ); - return admitted({ ...command, text }); + return { ...admitted({ ...command, text: stamp.text }), refused: stamp.release }; } case "queued-run.edit": { if (!(yield* shared.isShared(command.threadId))) return admitted(command); @@ -524,6 +549,11 @@ const make = Effect.gen(function* () { // 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 }); + // A record left behind holds its old prefix and note for a retry under the same id. + const notReleased = (cause: unknown) => + Effect.logError("J5 shared conversation could not release a refused message's record", { + cause, + }); const dispatch: SharedConversationShape["dispatch"] = Effect.fn( "j5.sharing.sharedConversation.dispatch", @@ -549,7 +579,9 @@ const make = Effect.gen(function* () { const marked = stamped.type === "runtime-request.respond" && stamped.answers !== undefined; yield* recordAnswer(personId, stamped, marked); } - const result = yield* dispatchUpstream(stamped); + const result = yield* dispatchUpstream(stamped).pipe( + Effect.onError(() => stamp.refused.pipe(Effect.catch(notReleased))), + ); yield* stamp.accepted.pipe(Effect.catch(notRecorded)); if ( stamped.type === "runtime-request.respond" && @@ -560,9 +592,10 @@ const make = Effect.gen(function* () { return result; }); - const admitLaunch: SharedConversationShape["admitLaunch"] = Effect.fn( - "j5.sharing.sharedConversation.admitLaunch", - )(function* (personId, input) { + const admitLaunch = Effect.fn("j5.sharing.sharedConversation.admitLaunch")(function* ( + personId: ParticipantId | null, + input: OrchestrationV2ThreadLaunchInput, + ) { const first = input.initialMessage; if (first !== undefined && carriesPlatformRecord(first.context)) { return yield* refused("A message cannot carry a record of the platform's own."); @@ -576,27 +609,43 @@ const make = Effect.gen(function* () { if (input.threadId !== undefined) { yield* shared.isShared(input.threadId, launchingIn).pipe(Effect.catch(failClosed)); } - return input; + return admitted(input); } if (input.threadId === undefined) { // No thread is named, so the message cannot be recorded under one; on a project more // than one person writes to, that is a launch J5 cannot take in. const writers = yield* shared.projectWriters(input.projectId).pipe(Effect.catch(failClosed)); - if (writers.length < 2) return input; + if (writers.length < 2) return admitted(input); return yield* refused("A thread in a shared project is started with its id."); } const threadId = input.threadId; return yield* Effect.gen(function* () { - if (!(yield* shared.isShared(threadId, launchingIn))) return input; + if (!(yield* shared.isShared(threadId, launchingIn))) return admitted(input); const author = yield* authorOn(personId, threadId, launchingIn); - if (author === null) return input; + if (author === null) return admitted(input); const messageId = first.messageId ?? MessageId.make(`message:j5:launch:${NodeCrypto.randomUUID()}`); - const text = yield* stampMessage(threadId, messageId, first.text, author, launchingIn); - return { ...input, initialMessage: { ...first, messageId, text } }; + const stamp = yield* stampMessage(threadId, messageId, first.text, author, launchingIn); + return { + ...admitted({ ...input, initialMessage: { ...first, messageId, text: stamp.text } }), + refused: stamp.release, + }; }).pipe(Effect.catch(failClosed)); }); + const launch: SharedConversationShape["launch"] = Effect.fn( + "j5.sharing.sharedConversation.launch", + )(function* ( + personId: ParticipantId | null, + input: OrchestrationV2ThreadLaunchInput, + launchUpstream: (input: OrchestrationV2ThreadLaunchInput) => Effect.Effect, + ) { + const stamp = yield* admitLaunch(personId, input); + return yield* launchUpstream(stamp.command).pipe( + Effect.onError(() => stamp.refused.pipe(Effect.catch(notReleased))), + ); + }); + /** * A thread's messages, its own and those a fork shows, that no person is recorded for but a * person wrote: the first owner's, as search names them (`typedByFirstOwner`). Their own view @@ -871,7 +920,7 @@ const make = Effect.gen(function* () { return SharedConversation.of({ dispatch, - admitLaunch, + launch, threadAuthors, authorsChanges: (threadId) => Stream.unwrap( diff --git a/apps/server/src/j5/sharing/messageStamps.ts b/apps/server/src/j5/sharing/messageStamps.ts index c6afc87c5e96d..419f909328054 100644 --- a/apps/server/src/j5/sharing/messageStamps.ts +++ b/apps/server/src/j5/sharing/messageStamps.ts @@ -230,7 +230,7 @@ export const makeMessageStamps = Effect.fn("j5.sharing.sharedConversation.makeMe return yield* refused("This message was already sent."); } const createdAt = DateTime.formatIso(yield* DateTime.now); - yield* sql` + const inserted = yield* sql` INSERT INTO j5_a2a_message_author ( thread_id, message_id, person_id, display_name, level, note, told_json, stored_prefix, created_at @@ -239,8 +239,11 @@ export const makeMessageStamps = Effect.fn("j5.sharing.sharedConversation.makeMe ${carried.note}, ${carried.told}, ${storedPrefix}, ${createdAt} ) ON CONFLICT (thread_id, message_id) DO NOTHING + RETURNING message_id `; yield* touch(threadId); + // Whether this call wrote the record, rather than finding an earlier attempt's. + return inserted.length > 0; }); return { writerLabel, authorOn, announce, recordAuthor }; diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index f8fea3cca8483..fa1c5cce9e9ff 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -3330,9 +3330,7 @@ export const layerWsRpc = ( handlers[ORCHESTRATION_V2_WS_METHODS.dispatchCommand], ), [ORCHESTRATION_V2_WS_METHODS.launchThread]: (input: OrchestrationV2ThreadLaunchInput) => - j5Commands - .admitLaunch(input) - .pipe(Effect.flatMap(handlers[ORCHESTRATION_V2_WS_METHODS.launchThread])), + j5Commands.launchThread(input, handlers[ORCHESTRATION_V2_WS_METHODS.launchThread]), [WS_METHODS.scheduledTasksUpsert]: (input: ScheduledTaskUpsertInput) => j5Commands.upsertScheduledTask(input, handlers[WS_METHODS.scheduledTasksUpsert]), };