TypeScript
fix(web,mobile): save pull request description checkbox changes (#30704)
shivam7384cf20da1a
diff --git a/apps/mobile/src/features/pull-requests/PullRequestDescription.tsx b/apps/mobile/src/features/pull-requests/PullRequestDescription.tsxindex 1403ee8e8d4..59d2709a4f9 100644--- a/apps/mobile/src/features/pull-requests/PullRequestDescription.tsx+++ b/apps/mobile/src/features/pull-requests/PullRequestDescription.tsx@@ -5,7 +5,7 @@ import {PullRequestMediaContext,} from "./PullRequestMedia";import { PullRequestSectionHeading } from "./PullRequestSectionHeading";-import { useContext, useMemo, useState, type ReactNode } from "react";+import { useContext, useMemo, useState, type ComponentProps, type ReactNode } from "react";import { Platform, Pressable, ScrollView, StyleSheet, View } from "react-native";import Svg, { Defs, LinearGradient, Rect, Stop } from "react-native-svg";import { pullRequestImageSource } from "./pullRequestMediaSource";@@ -26,6 +26,7 @@ export function PullRequestDescription(props: {readonly expanded: boolean;readonly onExpandedChange: (expanded: boolean) => void;readonly footer?: ReactNode;+ readonly onTaskListChange?: ComponentProps<typeof PullRequestMarkdown>["onTaskListChange"];}) {const { expanded, onExpandedChange } = props;const [bodyHeight, setBodyHeight] = useState(0);@@ -66,7 +67,10 @@ export function PullRequestDescription(props: {style={{ position: "absolute", top: 0, left: 0, right: 0 }}onLayout={(event) => setBodyHeight(event.nativeEvent.layout.height)}>- <PullRequestMarkdown markdown={props.markdown} />+ <PullRequestMarkdown+ markdown={props.markdown}+ onTaskListChange={props.onTaskListChange}+ /></View></View>{collapsed ? (diff --git a/apps/mobile/src/features/pull-requests/PullRequestMarkdown.tsx b/apps/mobile/src/features/pull-requests/PullRequestMarkdown.tsxindex e09963c2bf3..f08b5c48468 100644--- a/apps/mobile/src/features/pull-requests/PullRequestMarkdown.tsx+++ b/apps/mobile/src/features/pull-requests/PullRequestMarkdown.tsx@@ -1,4 +1,5 @@import { splitPullRequestBody } from "@t3tools/client-runtime/pull-request-markdown";+import { markdownTaskMarkerOffset } from "@t3tools/shared/markdownTaskList";import type { ReactNode } from "react";import { View } from "react-native";import { useProject } from "../../state/entities";@@ -30,6 +31,7 @@ import {} from "../../components/FilePreviewModal";import { ThreadMarkdownImageView } from "../threads/ThreadMarkdownImage";import type { MarkdownImageRenderer } from "../../native/SelectableMarkdownText";+import type { SelectableMarkdownTextProps } from "../../native/SelectableMarkdownText.types";const AutolinksContext = createContext<((text: string) => ReadonlyArray<ReferenceAutolink>) | null>(null,@@ -97,17 +99,46 @@ export function PullRequestMarkdown(props: {readonly markdown: string;readonly imageGroupMarkdown?: string;readonly lineBreaks?: boolean;+ /**+ * `markerOffset` is into `markdown`. Returning false, or a tap that can't be traced back to+ * the source, undoes the tick the renderer already drew.+ */+ readonly onTaskListChange?: (input: {+ readonly markerOffset: number;+ readonly checked: boolean;+ }) => boolean;}) {+ const { onTaskListChange } = props;const segments = useMemo(() => splitPullRequestBody(props.markdown), [props.markdown]);+ const [undoneTicks, setUndoneTicks] = useState(0);return (<View style={{ gap: 12 }}>{segments.map((segment) =>segment.kind === "markdown" ? (<PullRequestMarkdownContent- key={segment.id}+ key={`${segment.id}:${undoneTicks}`}markdown={segment.text}imageGroupMarkdown={props.imageGroupMarkdown ?? props.markdown}lineBreaks={props.lineBreaks}+ onTaskListItemPress={+ onTaskListChange+ ? (event) => {+ const offset = markdownTaskMarkerOffset(+ segment.text,+ event.index,+ event.text,+ event.checked,+ );+ const kept =+ offset !== null &&+ onTaskListChange({+ markerOffset: segment.sourceOffset + offset,+ checked: event.checked,+ });+ if (!kept) setUndoneTicks((count) => count + 1);+ }+ : undefined+ }/>) : (<PullRequestMedia key={segment.id} url={segment.url} kind={segment.media} />@@ -121,6 +152,7 @@ function PullRequestMarkdownContent(props: {readonly markdown: string;readonly imageGroupMarkdown?: string;readonly lineBreaks: boolean | undefined;+ readonly onTaskListItemPress?: SelectableMarkdownTextProps["onTaskListItemPress"];}) {const hostLineBreaks = useContext(LineBreaksContext);const autolinks = useContext(AutolinksContext);@@ -153,6 +185,7 @@ function PullRequestMarkdownContent(props: {onLinkPress={openLink}renderImage={renderImage}onImagePress={(href) => setPreview(pullRequestImageSource(href, mediaContext))}+ onTaskListItemPress={props.onTaskListItemPress}/><FilePreviewModal source={preview} onRequestClose={() => setPreview(null)} /></FilePreviewGallery>diff --git a/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsxindex 15f823185a6..522a5eaf9a7 100644--- a/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx+++ b/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx@@ -33,6 +33,7 @@ import { Button } from "../../components/ui/Button";import { usePullRequestReviewDraft } from "./usePullRequestReviewDraft";import { usePullRequestFilesViewed } from "./usePullRequestFilesViewed";import { usePullRequestPermissions } from "./usePullRequestPermissions";+import { usePullRequestDescription } from "./usePullRequestDescription";import { usePullRequestAction } from "./usePullRequestAction";import { annotatePullRequestDiff, reviewPosition } from "./pullRequestDiffComments";import { usePullRequestFileFilter } from "./usePullRequestFileFilter";@@ -293,6 +294,7 @@ function PullRequestLabels(props: {function PullRequestOverview(props: {readonly pr: PullRequestDetail;+ readonly description: ReturnType<typeof usePullRequestDescription>;readonly params: PullRequestParams;readonly stack: PullRequestStackState;readonly onDescriptionLayout: (y: number) => void;@@ -320,7 +322,8 @@ function PullRequestOverview(props: {onLayout={(event) => props.onDescriptionLayout(event.nativeEvent.layout.y)}><PullRequestDescription- markdown={pr.body}+ markdown={props.description.body}+ onTaskListChange={props.description.toggleTask}onCollapse={props.onDescriptionCollapse}expanded={props.descriptionExpanded}onExpandedChange={props.onDescriptionExpandedChange}@@ -416,6 +419,7 @@ export function PullRequestRouteScreen({ route }: StaticScreenProps<PullRequestPconst identity = pr ?? summary;const terminology = sourceControlClients.get(identity?.provider).changeRequest;const permissions = usePullRequestPermissions(params, pr);+ const description = usePullRequestDescription(params, pr, permissions.canEditChangeRequest);const action = usePullRequestAction(params, pr);const maintainerEdits = usePullRequestMaintainerEdits(params,@@ -524,6 +528,8 @@ export function PullRequestRouteScreen({ route }: StaticScreenProps<PullRequestP{accessibilityLabel: "Edit description",icon: "doc.text" as const,+ disabled: description.pending,+ subtitle: description.pending ? "Saving…" : undefined,overflowOnly: true,onPress: () =>navigation.navigate("PullRequestEdit", { ...params, field: "body" }),@@ -629,6 +635,8 @@ export function PullRequestRouteScreen({ route }: StaticScreenProps<PullRequestP{permissions.canEditChangeRequest ? (<Toolbar.MenuActionicon="doc.text"+ disabled={description.pending}+ subtitle={description.pending ? "Saving…" : undefined}onPress={() => navigation.navigate("PullRequestEdit", { ...params, field: "body" })}><Toolbar.Label>Edit description</Toolbar.Label>@@ -779,6 +787,7 @@ export function PullRequestRouteScreen({ route }: StaticScreenProps<PullRequestP{pr ? (<PullRequestOverviewpr={pr}+ description={description}params={params}stack={stack}descriptionExpanded={descriptionExpanded}diff --git a/apps/mobile/src/features/pull-requests/usePullRequestDescription.ts b/apps/mobile/src/features/pull-requests/usePullRequestDescription.tsnew file mode 100644index 00000000000..1496270d112--- /dev/null+++ b/apps/mobile/src/features/pull-requests/usePullRequestDescription.ts@@ -0,0 +1,65 @@+import { useAtomRefresh, useAtomValue } from "@effect/atom-react";+import {+ descriptionDraftInForce,+ settleDescriptionSave,+ startDescriptionSave,+ type DescriptionDraft,+} from "@t3tools/client-runtime/pull-request-editing";+import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";+import type { PullRequestDetail } from "@t3tools/contracts";+import { setMarkdownTaskChecked } from "@t3tools/shared/markdownTaskList";+import { AsyncResult } from "effect/reactivity";+import { useRef, useState } from "react";+import * as Dialog from "../../components/ui/Dialog";+import { composerPullRequests } from "../../state/pull-requests";+import { useAtomCommand } from "../../state/use-atom-command";+import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff";++/** The description with checkbox ticks shown before the host confirms them. */+export function usePullRequestDescription(+ params: PullRequestParams,+ pr: PullRequestDetail | null,+ canEdit: boolean,+) {+ const target = pullRequestTarget(params);+ const update = useAtomCommand(composerPullRequests.update, { reportFailure: false });+ const refreshDetail = useAtomRefresh(composerPullRequests.detail(target));+ const reading = useAtomValue(composerPullRequests.detailReadVersion(target));+ const savesRunning = useRef(0);+ const [draft, setDraft] = useState<DescriptionDraft | null>(null);+ const kept = descriptionDraftInForce(draft, pr?.url ?? "", reading);+ if (kept !== draft) setDraft(kept);+ const body = kept?.body ?? pr?.body ?? "";+ const save = async (detail: PullRequestDetail, next: string) => {+ setDraft((current) =>+ startDescriptionSave(current, { url: detail.url, observedAt: reading }, next),+ );+ savesRunning.current += 1;+ const response = await update({ ...target, input: { ...target.input, body: next } });+ savesRunning.current -= 1;+ const saved = !AsyncResult.isFailure(response);+ setDraft((current) => settleDescriptionSave(current, detail.url, saved));+ if (AsyncResult.isFailure(response)) {+ const cause = squashAtomCommandFailure(response);+ Dialog.alert(+ "Could not save the description",+ cause instanceof Error ? cause.message : "Try again.",+ );+ }+ if (savesRunning.current === 0) refreshDetail();+ };+ return {+ body,+ /** The edit screen starts from the host's copy, so it waits for a reading with the ticks. */+ pending: kept !== null,+ toggleTask:+ canEdit && pr !== null+ ? ({ markerOffset, checked }: { markerOffset: number; checked: boolean }) => {+ const next = setMarkdownTaskChecked(body, markerOffset, checked);+ if (next === body) return false;+ void save(pr, next);+ return true;+ }+ : undefined,+ };+}diff --git a/apps/mobile/src/native/EnrichedMarkdownText.tsx b/apps/mobile/src/native/EnrichedMarkdownText.tsxindex 6fa8c229a95..77670ab86e2 100644--- a/apps/mobile/src/native/EnrichedMarkdownText.tsx+++ b/apps/mobile/src/native/EnrichedMarkdownText.tsx@@ -337,7 +337,8 @@ export function MobileEnrichedMarkdownText(props: SelectableMarkdownTextProps) {admonitions: true,preserveWindowsPaths: true,}}- enableTaskListItemToggle={false}+ enableTaskListItemToggle={props.onTaskListItemPress !== undefined}+ onTaskListItemPress={props.onTaskListItemPress}enableCodeBlockWrapTogglespoilerOverlay="solid"onLinkPress={diff --git a/apps/mobile/src/native/SelectableMarkdownText.types.ts b/apps/mobile/src/native/SelectableMarkdownText.types.tsindex 68600701526..b25999ea42b 100644--- a/apps/mobile/src/native/SelectableMarkdownText.types.ts+++ b/apps/mobile/src/native/SelectableMarkdownText.types.ts@@ -76,6 +76,15 @@ export interface SelectableMarkdownTextProps {readonly fileEmbedLabel?: (href: string, standalone: boolean) => string | null;readonly resolveImageSource?: MarkdownImageSourceResolver;readonly onImagePress?: (href: string) => void;+ /**+ * Makes task checkboxes tappable. The renderer ticks the box itself; `index` counts checkboxes+ * in document order and `checked` is the new state.+ */+ readonly onTaskListItemPress?: (event: {+ readonly index: number;+ readonly checked: boolean;+ readonly text: string;+ }) => void;readonly marginTop?: number;readonly marginBottom?: number;readonly writingDirection?: "ltr" | "rtl";diff --git a/apps/web/src/components/ChatMarkdown.browser.test.tsx b/apps/web/src/components/ChatMarkdown.browser.test.tsxindex 9a56cdf8b36..91d0abd6e34 100644--- a/apps/web/src/components/ChatMarkdown.browser.test.tsx+++ b/apps/web/src/components/ChatMarkdown.browser.test.tsx@@ -9,7 +9,7 @@ import "../index.css";import { filesystemEnvironment } from "../state/filesystem";import { useRightPanelStore } from "../rightPanelStore";-import { setMarkdownTaskChecked } from "./files/filePreviewMode";+import { setMarkdownTaskChecked } from "@t3tools/shared/markdownTaskList";import { HostImageUrlContext } from "./chat/hostImageUrl";const { workspaceSearch, filesystemMetadata } = vi.hoisted(() => ({@@ -320,6 +320,9 @@ describe("ChatMarkdown streaming", () => {await act(async () => original.click());expect(editedText).toBe("- [ ] A longer first task\n- [x] Second");await vi.waitFor(() => expect(checkboxes()[1]!.checked).toBe(true));+ await rerender(message("- [ ] A longer first task\n- [ ] Second"));+ expect(checkboxes()[1]).toBe(original);+ expect(checkboxes()[1]!.checked).toBe(false);});});diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsxindex dd37be3b4b6..3ab3148bf39 100644--- a/apps/web/src/components/ChatMarkdown.tsx+++ b/apps/web/src/components/ChatMarkdown.tsx@@ -6,6 +6,7 @@ import {extractMarkdownLinkHrefs,inlineCodeFilePathCandidate,} from "@t3tools/shared/markdownLinks";+import { taskListMarkerOffset } from "@t3tools/shared/markdownTaskList";import { isHostPath, resolveWorkspaceFilePath } from "@t3tools/shared/path";import { usePullRequestLinking } from "~/hooks/usePullRequestLinking";import {@@ -321,17 +322,6 @@ function CodexArtifactTemplateCard(props: {const WINDOWS_DRIVE_PATH_REGEX = /^[A-Za-z]:[\\/]/;-function findTaskListMarkerOffset(markdown: string, listItemStart: number): number | null {- const firstLineEnd = markdown.indexOf("\n", listItemStart);- const firstLine = markdown.slice(- listItemStart,- firstLineEnd === -1 ? markdown.length : firstLineEnd,- );- const match = firstLine.match(/^(?:\s*(?:[-+*]|\d+[.)])\s+)(\[[ xX]\])/);- if (!match?.[1]) return null;- return listItemStart + firstLine.indexOf(match[1]);-}-function orderedListGutterStyle(itemCount: number,start: unknown,@@ -1035,7 +1025,7 @@ const CHAT_MARKDOWN_COMPONENTS = {<input{...props}type={type}- checked={checked}+ checked={type === "checkbox" ? checked === true : checked}disabled={_disabled}readOnly={type === "checkbox"}/>@@ -1047,11 +1037,11 @@ const CHAT_MARKDOWN_COMPONENTS = {type="checkbox"name="markdown-task"aria-label="Toggle task"- checked={checked}+ checked={checked === true}onChange={(event) => {const listItemStart = Number(event.currentTarget.closest("li")?.dataset.listItemOffset);if (!Number.isSafeInteger(listItemStart)) return;- const markerOffset = findTaskListMarkerOffset(text, listItemStart);+ const markerOffset = taskListMarkerOffset(text, listItemStart);if (markerOffset === null) return;onTaskListChange({ markerOffset, checked: event.currentTarget.checked });}}diff --git a/apps/web/src/components/files/FilePreviewPanel.test.ts b/apps/web/src/components/files/FilePreviewPanel.test.tsindex ddc77e5748f..18f725c3ba6 100644--- a/apps/web/src/components/files/FilePreviewPanel.test.ts+++ b/apps/web/src/components/files/FilePreviewPanel.test.ts@@ -10,7 +10,6 @@ import {filePreviewReadErrorMessage,isMarkdownPreviewFile,resolveFilePreviewPath,- setMarkdownTaskChecked,shouldShowFileExplorer,workspaceAssetResource,} from "./filePreviewMode";@@ -76,21 +75,6 @@ describe("isMarkdownPreviewFile", () => {});});-describe("setMarkdownTaskChecked", () => {- const markdown = "- [ ] First\n- [x] Second\n";-- it("checks and unchecks the task marker at the supplied offset", () => {- expect(setMarkdownTaskChecked(markdown, 2, true)).toBe("- [x] First\n- [x] Second\n");- expect(setMarkdownTaskChecked(markdown, 14, false)).toBe("- [ ] First\n- [ ] Second\n");- expect(setMarkdownTaskChecked("1. [X] Ordered\n", 3, false)).toBe("1. [ ] Ordered\n");- });-- it("leaves the document unchanged for a stale or invalid marker offset", () => {- expect(setMarkdownTaskChecked(markdown, 0, true)).toBe(markdown);- expect(setMarkdownTaskChecked(markdown, 200, true)).toBe(markdown);- });-});-describe("resolveFilePreviewPath", () => {it.each([["/repo/project", null],diff --git a/apps/web/src/components/files/FilePreviewPanel.tsx b/apps/web/src/components/files/FilePreviewPanel.tsxindex b88d92fc4ed..9674bcfdebd 100644--- a/apps/web/src/components/files/FilePreviewPanel.tsx+++ b/apps/web/src/components/files/FilePreviewPanel.tsx@@ -114,10 +114,10 @@ import {filePreviewReadErrorMessage,isMarkdownPreviewFile,resolveFilePreviewPath,- setMarkdownTaskChecked,shouldShowFileExplorer,workspaceAssetResource,} from "./filePreviewMode";+import { setMarkdownTaskChecked } from "@t3tools/shared/markdownTaskList";import { changeFileSaveSession, useFileSaveSession } from "./fileSaveSessions";import { revisionedQuery } from "~/state/revisionedQuery";import {diff --git a/apps/web/src/components/files/filePreviewMode.ts b/apps/web/src/components/files/filePreviewMode.tsindex 3777fad423f..4fca2af1c18 100644--- a/apps/web/src/components/files/filePreviewMode.ts+++ b/apps/web/src/components/files/filePreviewMode.ts@@ -40,23 +40,6 @@ export function shouldShowFileExplorer(input: {return input.explorerOpen || input.relativePath === null;}-export function setMarkdownTaskChecked(- markdown: string,- markerOffset: number,- checked: boolean,-): string {- if (- markerOffset < 0 ||- markdown[markerOffset] !== "[" ||- !/[ xX]/.test(markdown[markerOffset + 1] ?? "") ||- markdown[markerOffset + 2] !== "]"- ) {- return markdown;- }-- return `${markdown.slice(0, markerOffset + 1)}${checked ? "x" : " "}${markdown.slice(markerOffset + 2)}`;-}-/*** The server only signs `workspace-file` assets below the workspace root, so a* file opened from outside it, such as an absolute link in the thread, goesdiff --git a/apps/web/src/components/pullRequest/PullRequestMarkdown.tsx b/apps/web/src/components/pullRequest/PullRequestMarkdown.tsxindex 566d34910d4..68d354f1758 100644--- a/apps/web/src/components/pullRequest/PullRequestMarkdown.tsx+++ b/apps/web/src/components/pullRequest/PullRequestMarkdown.tsx@@ -60,6 +60,7 @@ export function PullRequestMarkdown({threadRef,lineBreaks,className,+ onTaskListChange,}: {text: string;cwd: string;@@ -67,6 +68,8 @@ export function PullRequestMarkdown({threadRef?: ScopedThreadRef | null;lineBreaks?: boolean;className?: string;+ /** `markerOffset` is into `text`. Checkboxes stay read-only without it. */+ onTaskListChange?: ((input: { markerOffset: number; checked: boolean }) => void) | undefined;}) {const segments = splitPullRequestBody(text);const context = useContext(PullRequestMarkdownContext);@@ -92,6 +95,15 @@ export function PullRequestMarkdown({{...(context ? { extraRemarkPlugins: context.remarkPlugins } : {})}lineBreaks={lineBreaks ?? context?.lineBreaks ?? false}sourceControlMedia+ onTaskListChange={+ onTaskListChange && segment.kind === "markdown"+ ? ({ markerOffset, checked }) =>+ onTaskListChange({+ markerOffset: segment.sourceOffset + markerOffset,+ checked,+ })+ : undefined+ }/>);}diff --git a/apps/web/src/components/pullRequest/PullRequestSummaryTab.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestSummaryTab.browser.test.tsxindex ba8cb353e8d..98db15d1429 100644--- a/apps/web/src/components/pullRequest/PullRequestSummaryTab.browser.test.tsx+++ b/apps/web/src/components/pullRequest/PullRequestSummaryTab.browser.test.tsx@@ -3,10 +3,39 @@ import { EnvironmentId, ProjectId, type PullRequestDetailView } from "@t3tools/cimport { expect, it, vi } from "vite-plus/test";import { userEvent } from "vite-plus/test/browser";+const state = vi.hoisted(() => ({ update: vi.fn(), canUpdate: true }));+vi.mock(import("~/state/use-atom-command"), async (original) => ({...(await original()),- useAtomCommand: (() => vi.fn()) as never,+ useAtomCommand: (() => state.update) as never,+}));+vi.mock(import("~/state/session"), async (original) => ({+ ...(await original()),+ readEnvironmentScope: () => true,+ useEnvironmentScope: () => true,}));+vi.mock(import("~/state/pullRequests"), async (original) => {+ const actual = await original();+ const { Atom } = await import("effect/reactivity");+ const allowed = Atom.make(true);+ const denied = Atom.make(false);+ return {+ ...actual,+ pullRequestEnvironment: {+ ...actual.pullRequestEnvironment,+ update: {+ ...actual.pullRequestEnvironment.update,+ permissionAtom: () => (state.canUpdate ? allowed : denied),+ },+ },+ };+});++function setup() {+ state.update.mockReset();+ state.update.mockResolvedValue({ _tag: "Success", value: undefined });+ state.canUpdate = true;+}import { act, render as renderUi } from "../../../test/render";import { PullRequestSummaryTab } from "./PullRequestSummaryTab";@@ -95,7 +124,9 @@ async function render(value = detail) {});}-it("keeps an unsaved description when collapsed and reopened", async () => {+it("keeps an unsaved description when collapsed and reopened, and after a failed save", async () => {+ setup();+ state.update.mockResolvedValue({ _tag: "Failure", cause: new Error("offline") });await using screen = await render();await act(async () =>screen.container.querySelector<HTMLButtonElement>('[aria-label="Edit description"]')!.click(),@@ -107,4 +138,50 @@ it("keeps an unsaved description when collapsed and reopened", async () => {expect(screen.expanded("Description")).toBe("false");await screen.click("Description");expect(screen.container.querySelector("textarea")!.value).toBe("Unsaved description");++ await userEvent.click(screen.getByRole("button", { name: "Save" }));+ expect(state.update).toHaveBeenCalledTimes(1);+ await expect.element(screen.getByRole("button", { name: "Save" })).toBeEnabled();+ expect(screen.container.querySelector("textarea")!.value).toBe("Unsaved description");+});++it("ticks a description checkbox placed after an attachment and edits from the ticked body", async () => {+ setup();+ let finishSave = (_result: unknown) => {};+ state.update.mockReturnValueOnce(new Promise((resolve) => (finishSave = resolve)));+ const body = "Intro\n\nhttps://example.com/shot.png\n\n## Test plan\n- [ ] First\n- [ ] Second";+ const ticked = body.replace("- [ ] Second", "- [x] Second");+ await using screen = await render({ ...detail, body, observedAt: 1 });+ const boxes = () => screen.container.querySelectorAll<HTMLInputElement>('input[type="checkbox"]');+ expect([...boxes()].map((box) => box.disabled)).toEqual([false, false]);++ await userEvent.click(boxes()[1]!);+ expect(state.update).toHaveBeenCalledWith({+ environmentId: "environment",+ input: expect.objectContaining({ number: 1, body: ticked }),+ });+ expect([...boxes()].map((box) => box.checked)).toEqual([false, true]);+ await act(async () => finishSave({ _tag: "Success", value: undefined }));++ // The host has not been read since the save, so the editor starts from the ticked body.+ await act(async () =>+ screen.container.querySelector<HTMLButtonElement>('[aria-label="Edit description"]')!.click(),+ );+ expect(screen.container.querySelector("textarea")!.value).toBe(ticked);+});++it("leaves description checkboxes read-only without the right to edit it", async () => {+ setup();+ const body = "- [ ] First";+ {+ await using screen = await render({ ...detail, body, viewer: "someone-else" });+ expect(+ screen.container.querySelector<HTMLInputElement>('input[type="checkbox"]')!.disabled,+ ).toBe(true);+ }+ state.canUpdate = false;+ await using screen = await render({ ...detail, body });+ expect(screen.container.querySelector<HTMLInputElement>('input[type="checkbox"]')!.disabled).toBe(+ true,+ );});diff --git a/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx b/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsxindex f8084aa550a..2ffef724ab7 100644--- a/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx+++ b/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx@@ -1,3 +1,4 @@+import { useAtomValue } from "@effect/atom-react";import {capitalizeTerm,sourceControlClients,@@ -73,7 +74,12 @@ import {import {canEditPullRequestChangeRequest,canEditPullRequestComment,+ descriptionDraftInForce,+ settleDescriptionSave,+ startDescriptionSave,+ type DescriptionDraft,} from "@t3tools/client-runtime/pull-request-editing";+import { setMarkdownTaskChecked } from "@t3tools/shared/markdownTaskList";import { PullRequestMarkdown } from "./PullRequestMarkdown";import { PullRequestCommentBody } from "./PullRequestCommentBody";import { PullRequestMoreReplies } from "./PullRequestMoreReplies";@@ -489,8 +495,23 @@ export function PullRequestSummaryTab({const updateComment = useAtomCommand(pullRequestEnvironment.updateComment, {reportFailure: false,});- const [bodyScope, setBodyScope] = useState<string | null>(null);- const [bodySaving, setBodySaving] = useState(false);+ const canUpdate = useAtomValue(pullRequestEnvironment.update.permissionAtom(environmentId));+ const canEditDescription = canUpdate && canEditPullRequestChangeRequest(detail);+ // The editor keeps the body it opened from, so a failed save cannot reset what was typed.+ const [bodyScope, setBodyScope] = useState<{+ readonly url: string;+ readonly body: string;+ } | null>(null);+ const [descriptionDraft, setDescriptionDraft] = useState<DescriptionDraft | null>(null);+ const descriptionDraftKept = descriptionDraftInForce(+ descriptionDraft,+ detail.url,+ detail.observedAt,+ );+ if (descriptionDraftKept !== descriptionDraft) setDescriptionDraft(descriptionDraftKept);+ const description = descriptionDraftKept?.body ?? detail.body;+ const descriptionSaving = (descriptionDraftKept?.saves ?? 0) > 0;+ const descriptionSavesRunning = useRef(0);// Hosts can reuse comment ids across pull requests.const [commentScope, setCommentScope] = useState<{readonly pullRequest: string;@@ -499,17 +520,26 @@ export function PullRequestSummaryTab({const [commentSaving, setCommentSaving] = useState(false);const editingCommentId = commentScope?.pullRequest === detail.url ? commentScope.commentId : null;- const saveBody = async (body: string) => {- if (bodySaving) return;- setBodySaving(true);+ // Checkbox ticks and the editor share one draft, so each starts from the other's latest body.+ const saveDescription = async (body: string) => {+ const key = detail.url;+ setDescriptionDraft((draft) => startDescriptionSave(draft, detail, body));+ descriptionSavesRunning.current += 1;const result = await update({ environmentId, input: { ...reference, body } });- setBodySaving(false);- if (result._tag === "Failure") {- toastManager.add({ type: "error", title: "Could not save the description" });- return;- }- setBodyScope(null);- onRefresh();+ descriptionSavesRunning.current -= 1;+ const saved = result._tag === "Success";+ setDescriptionDraft((draft) => settleDescriptionSave(draft, key, saved));+ if (!saved) toastManager.add({ type: "error", title: "Could not save the description" });+ if (descriptionSavesRunning.current === 0) onRefresh();+ return saved;+ };+ const saveBody = async (body: string) => {+ if (descriptionSaving) return;+ if (await saveDescription(body)) setBodyScope(null);+ };+ const toggleTask = ({ markerOffset, checked }: { markerOffset: number; checked: boolean }) => {+ const body = setMarkdownTaskChecked(description, markerOffset, checked);+ if (body !== description) void saveDescription(body);};const commentEditing: CommentEditing = {@@ -758,16 +788,16 @@ export function PullRequestSummaryTab({<Section key={`description:${detail.url}`} title="Description" keepMounted><div className="group">- {bodyScope === detail.url ? (+ {bodyScope?.url === detail.url ? (<PullRequestMarkdownEditorallowEmpty- value={detail.body}+ value={bodyScope.body}cwd={detail.workspaceRoot}environmentId={environmentId}threadRef={threadRef}label={`${capitalizeTerm(terminology.singular)} description`}placeholder={`Describe this ${terminology.singular}`}- saving={bodySaving}+ saving={descriptionSaving}onSave={(body) => void saveBody(body)}onCancel={() => setBodyScope(null)}/>@@ -775,15 +805,16 @@ export function PullRequestSummaryTab({<div className="flex items-start gap-1"><PullRequestMarkdownclassName="min-w-0 flex-1"- text={detail.body.trim().length > 0 ? detail.body : "_No description provided._"}+ text={description.trim().length > 0 ? description : "_No description provided._"}cwd={detail.workspaceRoot}environmentId={environmentId}threadRef={threadRef}+ onTaskListChange={canEditDescription ? toggleTask : undefined}/>- {canEditPullRequestChangeRequest(detail) ? (+ {canEditDescription ? (<PullRequestEditButtonaria-label="Edit description"- onClick={() => setBodyScope(detail.url)}+ onClick={() => setBodyScope({ url: detail.url, body: description })}/>) : null}</div>diff --git a/docs/user/source-control.md b/docs/user/source-control.mdindex c32219a02a5..949bddd8afb 100644--- a/docs/user/source-control.md+++ b/docs/user/source-control.md@@ -174,6 +174,8 @@ uses the project's instructions and recent commit subjects.Open **Pull requests** to review changes and comments, request reviewers, check out a branch,or merge. You can edit review titles and descriptions and your own comments where the host allows it.+Where you can edit a description, you can also tick its checkboxes from the Summary tab+(the Overview tab on mobile).GitLab calls these merge requests.On mobile, **Pull requests** lists reviews across your connected environments. Open a reviewdiff --git a/packages/client-runtime/src/pullRequestEditing.test.ts b/packages/client-runtime/src/pullRequestEditing.test.tsindex 1b473f4657d..15d349a7927 100644--- a/packages/client-runtime/src/pullRequestEditing.test.ts+++ b/packages/client-runtime/src/pullRequestEditing.test.ts@@ -11,6 +11,10 @@ import {canEditPullRequestChangeRequest,canEditPullRequestComment,canResolvePullRequestThread,+ descriptionDraftInForce,+ settleDescriptionSave,+ startDescriptionSave,+ type DescriptionDraft,} from "./pullRequestEditing.ts";type Subject = Pick<PullRequestDetail, "author" | "capabilities" | "viewer" | "viewerPermissions">;@@ -202,3 +206,44 @@ describe("canResolvePullRequestThread", () => {).toBe(false);});});++describe("description drafts", () => {+ const url = "https://github.com/owner/repo/pull/1";+ const unticked = "- [ ] Ship it";+ const ticked = "- [x] Ship it";++ it("hides readings taken during the saves and ends at the first one after them", () => {+ // Ticking and unticking the same box saves the host's own body last.+ let draft: DescriptionDraft | null = startDescriptionSave(null, { url, observedAt: 1 }, ticked);+ draft = startDescriptionSave(draft, { url, observedAt: 1 }, unticked);+ expect(descriptionDraftInForce(draft, url, 2)?.body).toBe(unticked);+ draft = descriptionDraftInForce(draft, url, 2);+ draft = settleDescriptionSave(draft, url, true);+ expect(descriptionDraftInForce(draft, url, 2)?.body).toBe(unticked);+ draft = settleDescriptionSave(draft, url, true);+ expect(descriptionDraftInForce(draft, url, 2)?.body).toBe(unticked);+ // The acknowledging reading ends the draft, so the host's later ticks show.+ expect(descriptionDraftInForce(draft, url, 3)).toBeNull();+ });++ it("outlives failed saves until a reading after the last one, losing the body only with it", () => {+ let draft: DescriptionDraft | null = startDescriptionSave(null, { url, observedAt: 1 }, ticked);+ draft = startDescriptionSave(draft, { url, observedAt: 1 }, unticked);+ // The save still running writes the whole body again.+ draft = settleDescriptionSave(draft, url, false);+ expect(descriptionDraftInForce(draft, url, 2)).toMatchObject({ body: unticked, saves: 1 });+ draft = descriptionDraftInForce(draft, url, 2);+ draft = settleDescriptionSave(draft, url, false);+ expect(descriptionDraftInForce(draft, url, 2)).toMatchObject({ body: null, saves: 0 });+ expect(settleDescriptionSave(draft, url, true)).toBe(draft);+ expect(descriptionDraftInForce(draft, url, 3)).toBeNull();+ });++ it("belongs to one change request", () => {+ const draft = startDescriptionSave(null, { url, observedAt: 1 }, ticked);+ const other = "https://github.com/owner/repo/pull/2";+ expect(descriptionDraftInForce(draft, other, 1)).toBeNull();+ expect(settleDescriptionSave(draft, other, false)).toBe(draft);+ expect(startDescriptionSave(draft, { url: other, observedAt: 5 }, unticked).saves).toBe(1);+ });+});diff --git a/packages/client-runtime/src/pullRequestEditing.ts b/packages/client-runtime/src/pullRequestEditing.tsindex e65c19009e6..19ea6554d17 100644--- a/packages/client-runtime/src/pullRequestEditing.ts+++ b/packages/client-runtime/src/pullRequestEditing.ts@@ -49,17 +49,58 @@ export interface MaintainerEditsChoice {* A saved choice ends at the first host reading delivered after the save. Readers refresh once it* succeeds, which drops reads still in flight, so that reading started after the write.*/-export function maintainerEditsChoiceInForce(- choice: MaintainerEditsChoice | null,+export function maintainerEditsChoiceInForce<+ Choice extends { readonly key: string; readonly observedAt: number | undefined },+>(+ choice: Choice | null,key: string,observedAt: number | undefined,saving: boolean,-): MaintainerEditsChoice | null {+): Choice | null {if (choice === null || choice.key !== key) return null;if (saving) return choice.observedAt === observedAt ? choice : { ...choice, observedAt };return observedAt !== undefined && choice.observedAt === observedAt ? choice : null;}+/** A description written from this client, shown in place of the host's copy. */+export interface DescriptionDraft {+ readonly key: string;+ readonly observedAt: number | undefined;+ /** Null once the last save failed: until a host reading, nobody knows which saves landed. */+ readonly body: string | null;+ /** Saves still running. The host applies them in order, so the last one is `body`. */+ readonly saves: number;+}++/** Same lifetime as a maintainer edits choice: until the first host reading after the saves. */+export function descriptionDraftInForce(+ draft: DescriptionDraft | null,+ key: string,+ observedAt: number | undefined,+): DescriptionDraft | null {+ return maintainerEditsChoiceInForce(draft, key, observedAt, (draft?.saves ?? 0) > 0);+}++export function startDescriptionSave(+ draft: DescriptionDraft | null,+ detail: { readonly url: string; readonly observedAt?: number | undefined },+ body: string,+): DescriptionDraft {+ const saves = draft?.key === detail.url ? draft.saves : 0;+ return { key: detail.url, observedAt: detail.observedAt, body, saves: saves + 1 };+}++/** Each save writes the whole body, so a failure only loses `body` when no later save is running. */+export function settleDescriptionSave(+ draft: DescriptionDraft | null,+ key: string,+ saved: boolean,+): DescriptionDraft | null {+ if (draft === null || draft.key !== key || draft.saves === 0) return draft;+ const saves = draft.saves - 1;+ return { ...draft, saves, body: saved || saves > 0 ? draft.body : null };+}+/** Hosts do not support rewriting review summaries through comment mutations. */export function canEditPullRequestComment(detail: EditingSubject,diff --git a/packages/client-runtime/src/pullRequestMarkdown.test.ts b/packages/client-runtime/src/pullRequestMarkdown.test.tsindex 3395d78313b..d07e48f4e83 100644--- a/packages/client-runtime/src/pullRequestMarkdown.test.ts+++ b/packages/client-runtime/src/pullRequestMarkdown.test.ts@@ -11,17 +11,34 @@ describe("pull request body segmentation", () => {"Before\n\nhttps://github.com/user-attachments/assets/2f8c1a90-1b2c-4d5e-8f90-abcdef123456\n\nAfter",),).toEqual([- { id: "markdown:0", kind: "markdown", text: "Before" },+ { id: "markdown:0", kind: "markdown", text: "Before", sourceOffset: 0 },{id: "attachment:1",kind: "attachment",url: "https://github.com/user-attachments/assets/2f8c1a90-1b2c-4d5e-8f90-abcdef123456",media: "video",},- { id: "markdown:2", kind: "markdown", text: "After" },+ { id: "markdown:2", kind: "markdown", text: "After", sourceOffset: 89 },]);});+ it("places each prose run at its offset in the body", () => {+ const body =+ '\n\n- [ ] Before\r\n\nhttps://example.com/shot.png\n\n\n<video controls>\n <source src="https://example.com/a.mp4">\n</video>\n - [ ] code\n- [x] After\n';+ const prose = splitPullRequestBody(body).flatMap((segment) =>+ segment.kind === "markdown" ? [segment] : [],+ );+ expect(prose.map((segment) => segment.text)).toEqual([+ "- [ ] Before",+ " - [ ] code\n- [x] After",+ ]);+ for (const segment of prose) {+ expect(body.slice(segment.sourceOffset, segment.sourceOffset + segment.text.length)).toBe(+ segment.text,+ );+ }+ });+it("reads the source out of a video tag, including a multi-line one", () => {expect(splitPullRequestBody(@@ -41,49 +58,49 @@ describe("pull request body segmentation", () => {const body ='<img width="1414" alt="image" src="https://github.com/user-attachments/assets/7195f963-51a9-4331-be74-3e06be760422" />';expect(splitPullRequestBody(body)).toEqual([- { id: "markdown:0", kind: "markdown", text: body },+ { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },]);});it("leaves an ordinary link alone, whether it is bare or written as markdown", () => {const body = "https://example.com/page\n\n[the docs](https://example.com/docs)";expect(splitPullRequestBody(body)).toEqual([- { id: "markdown:0", kind: "markdown", text: body },+ { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },]);});it("never lifts a link inside fenced code out of it", () => {const body = "```\nhttps://example.com/demo.mp4\n```";expect(splitPullRequestBody(body)).toEqual([- { id: "markdown:0", kind: "markdown", text: body },+ { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },]);});it("does not let a different fence marker close an open fence", () => {const body = "```\n~~~\nhttps://example.com/demo.mp4\n```";expect(splitPullRequestBody(body)).toEqual([- { id: "markdown:0", kind: "markdown", text: body },+ { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },]);});it("keeps a video tag that shares its line with prose as markdown", () => {const body = 'Before <video src="https://example.com/a.mp4"></video> after';expect(splitPullRequestBody(body)).toEqual([- { id: "markdown:0", kind: "markdown", text: body },+ { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },]);});it("treats an info-string fence as a nested opener, not a close", () => {const body = "```\n```javascript\nhttps://example.com/demo.mp4\n```";expect(splitPullRequestBody(body)).toEqual([- { id: "markdown:0", kind: "markdown", text: body },+ { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },]);});it("leaves an indented code line alone even when it is only a video link", () => {const body = " https://example.com/demo.mp4";expect(splitPullRequestBody(body)).toEqual([- { id: "markdown:0", kind: "markdown", text: body },+ { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },]);});@@ -92,14 +109,14 @@ describe("pull request body segmentation", () => {"\n",);expect(splitPullRequestBody(body)).toEqual([- { id: "markdown:0", kind: "markdown", text: body },+ { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },]);});it("refuses a non-http source rather than making a link out of it", () => {const body = '<video src="javascript:alert(1)"></video>';expect(splitPullRequestBody(body)).toEqual([- { id: "markdown:0", kind: "markdown", text: body },+ { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },]);});});@@ -119,7 +136,7 @@ describe("media on custom hosts", () => {const body ="See [recording](https://drop.example.com/a.mp4) for context.\n\n```md\nhttps://drop.example.com/a.png\n```";expect(splitPullRequestBody(body)).toEqual([- { id: "markdown:0", kind: "markdown", text: body },+ { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },]);});});diff --git a/packages/client-runtime/src/pullRequestMarkdown.ts b/packages/client-runtime/src/pullRequestMarkdown.tsindex 1e03c32509e..f8446369244 100644--- a/packages/client-runtime/src/pullRequestMarkdown.ts+++ b/packages/client-runtime/src/pullRequestMarkdown.ts@@ -2,7 +2,13 @@ import { sourceControlClients, type ReferenceAutolink } from "./sourceControlCli/** `id` is positional on purpose: the same attachment can be embedded twice in one body. */export type PullRequestBodySegment =- | { readonly id: string; readonly kind: "markdown"; readonly text: string }+ | {+ readonly id: string;+ readonly kind: "markdown";+ readonly text: string;+ /** Where `text` starts in the body, so an edit made to it can be written back. */+ readonly sourceOffset: number;+ }| {readonly id: string;readonly kind: "attachment";@@ -53,21 +59,31 @@ function attachmentFromLine(export function splitPullRequestBody(body: string): ReadonlyArray<PullRequestBodySegment> {const segments: PullRequestBodySegment[] = [];const markdown: string[] = [];+ let markdownStart = 0;let openFence: string | null = null;// Blank lines around a run are dropped, but never leading spaces: four of them open an// indented code block, so trimming a run would silently turn code into prose.const flushMarkdown = () => {- const text = markdown.join("\n").replace(/^\n+/u, "").replace(/\s+$/u, "");+ const joined = markdown.join("\n");+ const text = joined.replace(/^\n+/u, "");+ const sourceOffset = markdownStart + joined.length - text.length;markdown.length = 0;if (text.trim().length > 0) {- segments.push({ id: `markdown:${segments.length}`, kind: "markdown", text });+ segments.push({+ id: `markdown:${segments.length}`,+ kind: "markdown",+ text: text.replace(/\s+$/u, ""),+ sourceOffset,+ });}};const lines = body.split("\n");- for (let index = 0; index < lines.length; index += 1) {+ let lineStart = 0;+ for (let index = 0; index < lines.length; lineStart += lines[index]!.length + 1, index += 1) {const line = lines[index]!;+ if (markdown.length === 0) markdownStart = lineStart;const fenceMatch = FENCE_PATTERN.exec(line);if (fenceMatch !== null) {const fence = fenceMatch[1]!;@@ -120,7 +136,7 @@ export function splitPullRequestBody(body: string): ReadonlyArray<PullRequestBodmedia: "video",});- index = cursor;+ for (; index < cursor; index += 1) lineStart += lines[index]!.length + 1;} else {// Unclosed, or nothing linkable in it: prose. Only this line is consumed, so the// lines that were looked at are still parsed on their own terms.diff --git a/packages/client-runtime/src/state/pullRequests.test.ts b/packages/client-runtime/src/state/pullRequests.test.tsindex 2564a3da21d..b182beef900 100644--- a/packages/client-runtime/src/state/pullRequests.test.ts+++ b/packages/client-runtime/src/state/pullRequests.test.ts@@ -1363,20 +1363,80 @@ it.effect("shares checks reads across reference property order", () =>it.effect("keeps live detail reads separate from reads that allow stale data", () =>Effect.scoped(Effect.gen(function* () {+ let reads = 0;+ let hostStamp: number | undefined;+ let hold = false;+ const readStarted = yield* Latch.make();+ const releaseRead = yield* Latch.make();const client = {[WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.never,[WS_METHODS.pullRequestsDetail]: (input: { allowStale?: boolean }) =>- Effect.succeed({ title: input.allowStale === false ? "latest checks" : "cached checks" }),+ Effect.gen(function* () {+ reads++;+ if (hold) {+ yield* readStarted.open;+ yield* releaseRead.await;+ }+ return {+ title: input.allowStale === false ? "latest checks" : "cached checks",+ ...(hostStamp === undefined ? {} : { observedAt: hostStamp }),+ };+ }),} as unknown as WsRpcProtocolClient;- const { atoms, registry } = yield* makeTestRuntime(client);+ const { atoms, registry, supervisor } = yield* makeTestRuntime(client);const target = {environmentId: TARGET.environmentId,input: { projectId: ProjectId.make("project-1"), repository: "acme/web", number: 1 },};const cached = atoms.detail(target);const live = atoms.detail({ ...target, input: { ...target.input, allowStale: false } });- expect((yield* AtomRegistry.getResult(registry, cached)).title).toBe("cached checks");+ const first = yield* AtomRegistry.getResult(registry, cached);+ expect(first.title).toBe("cached checks");+ expect(first.observedAt).toBeUndefined();+ const reading = atoms.detailReadVersion(target);+ const firstVersion = registry.get(reading);+ expect(firstVersion).toBeGreaterThan(0);expect((yield* AtomRegistry.getResult(registry, live)).title).toBe("latest checks");+ expect(reads).toBe(2);+ hold = true;+ registry.refresh(cached);+ yield* readStarted.await;+ expect(registry.get(reading)).toBe(firstVersion);+ yield* releaseRead.open;+ expect(yield* AtomRegistry.getResult(registry, cached, { suspendOnWaiting: true })).toBe(+ first,+ );+ const settledVersion = registry.get(reading);+ expect(settledVersion).toBeGreaterThan(firstVersion);+ hold = false;++ yield* SubscriptionRef.update(supervisor.state, (state) => ({+ ...state,+ phase: "offline" as const,+ }));+ yield* Effect.yieldNow;+ registry.refresh(cached);+ const offline = yield* AtomRegistry.getResult(registry, cached, { suspendOnWaiting: true });+ expect(offline.observedAt).toBeUndefined();+ expect(registry.get(reading)).toBe(settledVersion);+ expect(reads).toBe(3);++ yield* SubscriptionRef.update(supervisor.state, (state) => ({+ ...state,+ phase: "connected" as const,+ }));+ yield* Effect.yieldNow;+ registry.refresh(cached);+ const reread = yield* AtomRegistry.getResult(registry, cached, { suspendOnWaiting: true });+ expect(reread).toBe(first);+ expect(reread.observedAt).toBeUndefined();+ expect(registry.get(reading)).toBeGreaterThan(settledVersion);++ hostStamp = 27;+ registry.refresh(cached);+ expect(+ (yield* AtomRegistry.getResult(registry, cached, { suspendOnWaiting: true })).observedAt,+ ).toBe(hostStamp);}),),);diff --git a/packages/client-runtime/src/state/pullRequests.ts b/packages/client-runtime/src/state/pullRequests.tsindex 1785af6fd38..e6566f2b7d5 100644--- a/packages/client-runtime/src/state/pullRequests.ts+++ b/packages/client-runtime/src/state/pullRequests.ts@@ -221,6 +221,14 @@ export function createPullRequestEnvironmentAtoms<R, E>(refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),}),);+ const detailAnswerAtoms = Atom.family((_key: string) =>+ Atom.make<{ readonly value: PullRequestDetail; readonly version: number } | null>(null).pipe(+ Atom.setIdleTTL(5 * 60_000),+ ),+ );+ const detailAnswers = normalizePullRequestQuery((target) =>+ detailAnswerAtoms(JSON.stringify(target)),+ );const detail = writableQueryFamily(createEnvironmentRpcQueryAtomFamily(runtime, {label: "environment-data:pull-requests:detail",@@ -229,9 +237,30 @@ export function createPullRequestEnvironmentAtoms<R, E>(execute: (input) => routedRequest(WS_METHODS.pullRequestsDetail, input),staleTimeMs: 60_000,refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),- ...(onAnswer.detail === undefined ? {} : { onAnswer: onAnswer.detail }),+ onAnswer: (target, value, registry) =>+ Effect.sync(() => {+ // Cache reads bypass onAnswer, and server freshness stays separate from local readbacks.+ registry.update(detailAnswers(target), (previous) => ({+ value,+ version: (previous?.version ?? 0) + 1,+ }));+ }).pipe(Effect.andThen(() => onAnswer.detail?.(target, value, registry) ?? Effect.void)),}),);+ const detailReadVersions = Atom.family((source: ReturnType<typeof detail>) =>+ Atom.family((answer: ReturnType<typeof detailAnswers>) =>+ Atom.make((get) => {+ const result = get(source);+ const latest = get(answer);+ return result._tag === "Success" && !result.waiting && result.value === latest?.value+ ? latest.version+ : Option.getOrElse(get.self<number>(), () => 0);+ }).pipe(Atom.setIdleTTL(5 * 60_000)),+ ),+ );+ const detailReadVersion = normalizePullRequestQuery((target) =>+ detailReadVersions(detail(target))(detailAnswers(target)),+ );const preview = writableQueryFamily(createEnvironmentRpcQueryAtomFamily(runtime, {label: "environment-data:pull-requests:preview",@@ -383,6 +412,7 @@ export function createPullRequestEnvironmentAtoms<R, E>(staleTimeMs: 5 * 60_000,}),detail,+ detailReadVersion,preview,previewCard,checks: normalizePullRequestQuery(diff --git a/packages/shared/package.json b/packages/shared/package.jsonindex 72c53671a1e..b09248b2163 100644--- a/packages/shared/package.json+++ b/packages/shared/package.json@@ -459,6 +459,10 @@"types": "./src/markdownFrontmatter.ts","import": "./src/markdownFrontmatter.ts"},+ "./markdownTaskList": {+ "types": "./src/markdownTaskList.ts",+ "import": "./src/markdownTaskList.ts"+ },"./markdownListIndentation": {"types": "./src/markdownListIndentation.ts","import": "./src/markdownListIndentation.ts"diff --git a/packages/shared/src/markdownTaskList.test.ts b/packages/shared/src/markdownTaskList.test.tsnew file mode 100644index 00000000000..5e00a3926fa--- /dev/null+++ b/packages/shared/src/markdownTaskList.test.ts@@ -0,0 +1,72 @@+import { describe, expect, it } from "vite-plus/test";++import { markdownTaskMarkerOffset, setMarkdownTaskChecked } from "./markdownTaskList.ts";++describe("setMarkdownTaskChecked", () => {+ const markdown = "- [ ] First\n- [x] Second\n";++ it("checks and unchecks the task marker at the supplied offset", () => {+ expect(setMarkdownTaskChecked(markdown, 2, true)).toBe("- [x] First\n- [x] Second\n");+ expect(setMarkdownTaskChecked(markdown, 14, false)).toBe("- [ ] First\n- [ ] Second\n");+ expect(setMarkdownTaskChecked("1. [X] Ordered\n", 3, false)).toBe("1. [ ] Ordered\n");+ });++ it("leaves the document unchanged for a stale or invalid marker offset", () => {+ expect(setMarkdownTaskChecked(markdown, 0, true)).toBe(markdown);+ expect(setMarkdownTaskChecked(markdown, 200, true)).toBe(markdown);+ });+});++describe("markdownTaskMarkerOffset", () => {+ const markdown = [+ "## Test plan",+ "- [ ] `vp lint` passes",+ " - [x] Nested **step**",+ "```md",+ "- [ ] Inside a fence",+ "```",+ "> 1. [X] Quoted [link](https://example.com)",+ "- [ ] Wrapped",+ " onto two lines",+ ].join("\n");+ const marker = (offset: number | null) =>+ offset === null ? null : markdown.slice(offset, offset + 3);++ it("finds the tapped checkbox, skipping look-alikes in code", () => {+ expect(marker(markdownTaskMarkerOffset(markdown, 0, "vp lint passes", true))).toBe("[ ]");+ expect(marker(markdownTaskMarkerOffset(markdown, 1, "Nested step", false))).toBe("[x]");+ // Native numbering restarts after code blocks and blockquotes.+ expect(marker(markdownTaskMarkerOffset(markdown, 0, "Quoted link", false))).toBe("[X]");+ // Android cuts the text at a line break, a soft one too with hard line breaks; iOS doesn't.+ for (const text of ["Wrapped", "Wrapped onto two lines"]) {+ expect(markdownTaskMarkerOffset(markdown, 0, text, true)).toBe(markdown.lastIndexOf("[ ]"));+ }+ });++ it("tells identical labels apart by count within one list and by state", () => {+ const same = "- [ ] Same\n- [ ] Same\n\n```\nx\n```\n\n- [x] Same\n";+ expect(markdownTaskMarkerOffset(same, 0, "Same", true)).toBe(2);+ expect(markdownTaskMarkerOffset(same, 1, "Same", true)).toBe(13);+ expect(markdownTaskMarkerOffset(same, 0, "Same", false)).toBe(same.lastIndexOf("[x]"));+ });++ it("refuses a checkbox it can't trace to exactly one task", () => {+ expect(markdownTaskMarkerOffset(markdown, 1, "vp lint passes", true)).toBeNull();+ expect(markdownTaskMarkerOffset(markdown, 0, "vp lint passes", false)).toBeNull();+ expect(markdownTaskMarkerOffset(markdown, 0, "Wrapped onto", true)).toBeNull();+ expect(markdownTaskMarkerOffset(markdown, 4, "", true)).toBeNull();++ const similar = "- [ ] Similar\n\n```text\nseparator\n```\n\n- [ ] Similar<br>different\n";+ // iOS keeps hard breaks in the text, so it names the second task.+ expect(markdownTaskMarkerOffset(similar, 0, "Similar different", true)).toBe(+ similar.lastIndexOf("[ ]"),+ );+ // Android cuts it to "Similar", which both tasks could be.+ expect(markdownTaskMarkerOffset(similar, 0, "Similar", true)).toBeNull();++ for (const label of ["Similar [docs](https://github.com/pingdotgg/t3code)", "Similar $x$"]) {+ const attachment = similar.replace("Similar<br>different", label);+ expect(markdownTaskMarkerOffset(attachment, 0, "Similar \uFFFC", true)).toBeNull();+ }+ });+});diff --git a/packages/shared/src/markdownTaskList.ts b/packages/shared/src/markdownTaskList.tsnew file mode 100644index 00000000000..fb02f757992--- /dev/null+++ b/packages/shared/src/markdownTaskList.ts@@ -0,0 +1,94 @@+import type { ListItem, Nodes } from "mdast";+import remarkGfm from "remark-gfm";+import remarkParse from "remark-parse";+import { unified } from "unified";++const parser = unified().use(remarkParse).use(remarkGfm);++/** Offset of the `[ ]` marker on the first line of the list item starting at `listItemStart`. */+export function taskListMarkerOffset(markdown: string, listItemStart: number): number | null {+ const firstLineEnd = markdown.indexOf("\n", listItemStart);+ const firstLine = markdown.slice(+ listItemStart,+ firstLineEnd === -1 ? markdown.length : firstLineEnd,+ );+ const match = firstLine.match(/^(?:\s*(?:[-+*]|\d+[.)])\s+)(\[[ xX]\])/);+ if (!match?.[1]) return null;+ return listItemStart + firstLine.indexOf(match[1]);+}++export function setMarkdownTaskChecked(+ markdown: string,+ markerOffset: number,+ checked: boolean,+): string {+ if (+ markerOffset < 0 ||+ markdown[markerOffset] !== "[" ||+ !/[ xX]/.test(markdown[markerOffset + 1] ?? "") ||+ markdown[markerOffset + 2] !== "]"+ ) {+ return markdown;+ }++ return `${markdown.slice(0, markerOffset + 1)}${checked ? "x" : " "}${markdown.slice(markerOffset + 2)}`;+}++/** Hard breaks as U+2028, as iOS draws them; soft breaks stay "\n". */+function plainText(node: Nodes): string {+ if (node.type === "text" || node.type === "inlineCode") return node.value;+ if (node.type === "break" || (node.type === "html" && /^<br\b/i.test(node.value))) {+ return "\u2028";+ }+ return "children" in node ? node.children.map(plainText).join("") : "";+}++const lettersAndDigits = (text: string) => text.replace(/[^\p{L}\p{N}]/gu, "");++/** iOS sends the first paragraph whole. Android cuts it at a hard break, or any break with hard breaks on. */+function renderedTexts(item: ListItem): string[] {+ const first = item.children[0];+ const text = first?.type === "paragraph" ? plainText(first) : "";+ return [text, text.replace(/\u2028[^]*$/, ""), text.replace(/[\u2028\n][^]*$/, "")].map(+ lettersAndDigits,+ );+}++// Native renderers give other top-level blocks (code, tables, quotes, media) their own views, and+// each view numbers its tasks from 0. Lists, headings and rules share the text view around them.+const sharedViewBlocks = new Set(["list", "heading", "thematicBreak"]);++/**+ * Marker offset of the task a native checkbox tap names. Null unless exactly one task has that+ * text and state and could have that index under some split of the document into native views.+ */+export function markdownTaskMarkerOffset(+ markdown: string,+ index: number,+ renderedText: string,+ checked: boolean,+): number | null {+ // Native attachments replace their labels, so the remaining text could name another task.+ if (renderedText.includes("\uFFFC")) return null;+ const tasks: ListItem[] = [];+ const collect = (node: Nodes) => {+ if (node.type === "listItem" && typeof node.checked === "boolean") tasks.push(node);+ if ("children" in node) node.children.forEach(collect);+ };+ const viewStarts = new Set([0]);+ for (const block of parser.parse(markdown).children) {+ const before = tasks.length;+ collect(block);+ if (sharedViewBlocks.has(block.type)) continue;+ for (let count = before; count <= tasks.length; count++) viewStarts.add(count);+ }+ const rendered = lettersAndDigits(renderedText);+ const matches = tasks.filter(+ (task, position) =>+ task.checked === !checked &&+ viewStarts.has(position - index) &&+ renderedTexts(task).includes(rendered),+ );+ const start = matches.length === 1 ? matches[0]?.position?.start.offset : undefined;+ return start === undefined ? null : taskListMarkerOffset(markdown, start);+}