@devries-cameron20 / t3code-1 / commits / 7384cf20da
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(web,mobile): save pull request description checkbox changes (#30704)

Co-authored-by: Maxime Cathala <84846651+mcathala@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

shivam committed Nov 5, 2026 at 06:54 UTC 7384cf20da1a1031c58b91d5900e4f81ae7d0024
24 files changed +680 -98
apps/mobile/src/features/pull-requests/PullRequestDescription.tsx
+6 -2
@@ -5,7 +5,7 @@ import {
5 PullRequestMediaContext,
6 } from "./PullRequestMedia";
7 import { PullRequestSectionHeading } from "./PullRequestSectionHeading";
8 -import { useContext, useMemo, useState, type ReactNode } from "react";
8 +import { useContext, useMemo, useState, type ComponentProps, type ReactNode } from "react";
9 import { Platform, Pressable, ScrollView, StyleSheet, View } from "react-native";
10 import Svg, { Defs, LinearGradient, Rect, Stop } from "react-native-svg";
11 import { pullRequestImageSource } from "./pullRequestMediaSource";
@@ -26,6 +26,7 @@ export function PullRequestDescription(props: {
26 readonly expanded: boolean;
27 readonly onExpandedChange: (expanded: boolean) => void;
28 readonly footer?: ReactNode;
29 + readonly onTaskListChange?: ComponentProps<typeof PullRequestMarkdown>["onTaskListChange"];
30 }) {
31 const { expanded, onExpandedChange } = props;
32 const [bodyHeight, setBodyHeight] = useState(0);
@@ -66,7 +67,10 @@ export function PullRequestDescription(props: {
67 style={{ position: "absolute", top: 0, left: 0, right: 0 }}
68 onLayout={(event) => setBodyHeight(event.nativeEvent.layout.height)}
69 >
69 - <PullRequestMarkdown markdown={props.markdown} />
70 + <PullRequestMarkdown
71 + markdown={props.markdown}
72 + onTaskListChange={props.onTaskListChange}
73 + />
74 </View>
75 </View>
76 {collapsed ? (
apps/mobile/src/features/pull-requests/PullRequestMarkdown.tsx
+34 -1
@@ -1,4 +1,5 @@
1 import { splitPullRequestBody } from "@t3tools/client-runtime/pull-request-markdown";
2 +import { markdownTaskMarkerOffset } from "@t3tools/shared/markdownTaskList";
3 import type { ReactNode } from "react";
4 import { View } from "react-native";
5 import { useProject } from "../../state/entities";
@@ -30,6 +31,7 @@ import {
31 } from "../../components/FilePreviewModal";
32 import { ThreadMarkdownImageView } from "../threads/ThreadMarkdownImage";
33 import type { MarkdownImageRenderer } from "../../native/SelectableMarkdownText";
34 +import type { SelectableMarkdownTextProps } from "../../native/SelectableMarkdownText.types";
35
36 const AutolinksContext = createContext<((text: string) => ReadonlyArray<ReferenceAutolink>) | null>(
37 null,
@@ -97,17 +99,46 @@ export function PullRequestMarkdown(props: {
99 readonly markdown: string;
100 readonly imageGroupMarkdown?: string;
101 readonly lineBreaks?: boolean;
102 + /**
103 + * `markerOffset` is into `markdown`. Returning false, or a tap that can't be traced back to
104 + * the source, undoes the tick the renderer already drew.
105 + */
106 + readonly onTaskListChange?: (input: {
107 + readonly markerOffset: number;
108 + readonly checked: boolean;
109 + }) => boolean;
110 }) {
111 + const { onTaskListChange } = props;
112 const segments = useMemo(() => splitPullRequestBody(props.markdown), [props.markdown]);
113 + const [undoneTicks, setUndoneTicks] = useState(0);
114 return (
115 <View style={{ gap: 12 }}>
116 {segments.map((segment) =>
117 segment.kind === "markdown" ? (
118 <PullRequestMarkdownContent
107 - key={segment.id}
119 + key={`${segment.id}:${undoneTicks}`}
120 markdown={segment.text}
121 imageGroupMarkdown={props.imageGroupMarkdown ?? props.markdown}
122 lineBreaks={props.lineBreaks}
123 + onTaskListItemPress={
124 + onTaskListChange
125 + ? (event) => {
126 + const offset = markdownTaskMarkerOffset(
127 + segment.text,
128 + event.index,
129 + event.text,
130 + event.checked,
131 + );
132 + const kept =
133 + offset !== null &&
134 + onTaskListChange({
135 + markerOffset: segment.sourceOffset + offset,
136 + checked: event.checked,
137 + });
138 + if (!kept) setUndoneTicks((count) => count + 1);
139 + }
140 + : undefined
141 + }
142 />
143 ) : (
144 <PullRequestMedia key={segment.id} url={segment.url} kind={segment.media} />
@@ -121,6 +152,7 @@ function PullRequestMarkdownContent(props: {
152 readonly markdown: string;
153 readonly imageGroupMarkdown?: string;
154 readonly lineBreaks: boolean | undefined;
155 + readonly onTaskListItemPress?: SelectableMarkdownTextProps["onTaskListItemPress"];
156 }) {
157 const hostLineBreaks = useContext(LineBreaksContext);
158 const autolinks = useContext(AutolinksContext);
@@ -153,6 +185,7 @@ function PullRequestMarkdownContent(props: {
185 onLinkPress={openLink}
186 renderImage={renderImage}
187 onImagePress={(href) => setPreview(pullRequestImageSource(href, mediaContext))}
188 + onTaskListItemPress={props.onTaskListItemPress}
189 />
190 <FilePreviewModal source={preview} onRequestClose={() => setPreview(null)} />
191 </FilePreviewGallery>
apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx
+10 -1
@@ -33,6 +33,7 @@ import { Button } from "../../components/ui/Button";
33 import { usePullRequestReviewDraft } from "./usePullRequestReviewDraft";
34 import { usePullRequestFilesViewed } from "./usePullRequestFilesViewed";
35 import { usePullRequestPermissions } from "./usePullRequestPermissions";
36 +import { usePullRequestDescription } from "./usePullRequestDescription";
37 import { usePullRequestAction } from "./usePullRequestAction";
38 import { annotatePullRequestDiff, reviewPosition } from "./pullRequestDiffComments";
39 import { usePullRequestFileFilter } from "./usePullRequestFileFilter";
@@ -293,6 +294,7 @@ function PullRequestLabels(props: {
294
295 function PullRequestOverview(props: {
296 readonly pr: PullRequestDetail;
297 + readonly description: ReturnType<typeof usePullRequestDescription>;
298 readonly params: PullRequestParams;
299 readonly stack: PullRequestStackState;
300 readonly onDescriptionLayout: (y: number) => void;
@@ -320,7 +322,8 @@ function PullRequestOverview(props: {
322 onLayout={(event) => props.onDescriptionLayout(event.nativeEvent.layout.y)}
323 >
324 <PullRequestDescription
323 - markdown={pr.body}
325 + markdown={props.description.body}
326 + onTaskListChange={props.description.toggleTask}
327 onCollapse={props.onDescriptionCollapse}
328 expanded={props.descriptionExpanded}
329 onExpandedChange={props.onDescriptionExpandedChange}
@@ -416,6 +419,7 @@ export function PullRequestRouteScreen({ route }: StaticScreenProps<PullRequestP
419 const identity = pr ?? summary;
420 const terminology = sourceControlClients.get(identity?.provider).changeRequest;
421 const permissions = usePullRequestPermissions(params, pr);
422 + const description = usePullRequestDescription(params, pr, permissions.canEditChangeRequest);
423 const action = usePullRequestAction(params, pr);
424 const maintainerEdits = usePullRequestMaintainerEdits(
425 params,
@@ -524,6 +528,8 @@ export function PullRequestRouteScreen({ route }: StaticScreenProps<PullRequestP
528 {
529 accessibilityLabel: "Edit description",
530 icon: "doc.text" as const,
531 + disabled: description.pending,
532 + subtitle: description.pending ? "Saving…" : undefined,
533 overflowOnly: true,
534 onPress: () =>
535 navigation.navigate("PullRequestEdit", { ...params, field: "body" }),
@@ -629,6 +635,8 @@ export function PullRequestRouteScreen({ route }: StaticScreenProps<PullRequestP
635 {permissions.canEditChangeRequest ? (
636 <Toolbar.MenuAction
637 icon="doc.text"
638 + disabled={description.pending}
639 + subtitle={description.pending ? "Saving…" : undefined}
640 onPress={() => navigation.navigate("PullRequestEdit", { ...params, field: "body" })}
641 >
642 <Toolbar.Label>Edit description</Toolbar.Label>
@@ -779,6 +787,7 @@ export function PullRequestRouteScreen({ route }: StaticScreenProps<PullRequestP
787 {pr ? (
788 <PullRequestOverview
789 pr={pr}
790 + description={description}
791 params={params}
792 stack={stack}
793 descriptionExpanded={descriptionExpanded}
apps/mobile/src/features/pull-requests/usePullRequestDescription.ts new
+65
@@ -0,0 +1,65 @@
1 +import { useAtomRefresh, useAtomValue } from "@effect/atom-react";
2 +import {
3 + descriptionDraftInForce,
4 + settleDescriptionSave,
5 + startDescriptionSave,
6 + type DescriptionDraft,
7 +} from "@t3tools/client-runtime/pull-request-editing";
8 +import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
9 +import type { PullRequestDetail } from "@t3tools/contracts";
10 +import { setMarkdownTaskChecked } from "@t3tools/shared/markdownTaskList";
11 +import { AsyncResult } from "effect/reactivity";
12 +import { useRef, useState } from "react";
13 +import * as Dialog from "../../components/ui/Dialog";
14 +import { composerPullRequests } from "../../state/pull-requests";
15 +import { useAtomCommand } from "../../state/use-atom-command";
16 +import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff";
17 +
18 +/** The description with checkbox ticks shown before the host confirms them. */
19 +export function usePullRequestDescription(
20 + params: PullRequestParams,
21 + pr: PullRequestDetail | null,
22 + canEdit: boolean,
23 +) {
24 + const target = pullRequestTarget(params);
25 + const update = useAtomCommand(composerPullRequests.update, { reportFailure: false });
26 + const refreshDetail = useAtomRefresh(composerPullRequests.detail(target));
27 + const reading = useAtomValue(composerPullRequests.detailReadVersion(target));
28 + const savesRunning = useRef(0);
29 + const [draft, setDraft] = useState<DescriptionDraft | null>(null);
30 + const kept = descriptionDraftInForce(draft, pr?.url ?? "", reading);
31 + if (kept !== draft) setDraft(kept);
32 + const body = kept?.body ?? pr?.body ?? "";
33 + const save = async (detail: PullRequestDetail, next: string) => {
34 + setDraft((current) =>
35 + startDescriptionSave(current, { url: detail.url, observedAt: reading }, next),
36 + );
37 + savesRunning.current += 1;
38 + const response = await update({ ...target, input: { ...target.input, body: next } });
39 + savesRunning.current -= 1;
40 + const saved = !AsyncResult.isFailure(response);
41 + setDraft((current) => settleDescriptionSave(current, detail.url, saved));
42 + if (AsyncResult.isFailure(response)) {
43 + const cause = squashAtomCommandFailure(response);
44 + Dialog.alert(
45 + "Could not save the description",
46 + cause instanceof Error ? cause.message : "Try again.",
47 + );
48 + }
49 + if (savesRunning.current === 0) refreshDetail();
50 + };
51 + return {
52 + body,
53 + /** The edit screen starts from the host's copy, so it waits for a reading with the ticks. */
54 + pending: kept !== null,
55 + toggleTask:
56 + canEdit && pr !== null
57 + ? ({ markerOffset, checked }: { markerOffset: number; checked: boolean }) => {
58 + const next = setMarkdownTaskChecked(body, markerOffset, checked);
59 + if (next === body) return false;
60 + void save(pr, next);
61 + return true;
62 + }
63 + : undefined,
64 + };
65 +}
apps/mobile/src/native/EnrichedMarkdownText.tsx
+2 -1
@@ -337,7 +337,8 @@ export function MobileEnrichedMarkdownText(props: SelectableMarkdownTextProps) {
337 admonitions: true,
338 preserveWindowsPaths: true,
339 }}
340 - enableTaskListItemToggle={false}
340 + enableTaskListItemToggle={props.onTaskListItemPress !== undefined}
341 + onTaskListItemPress={props.onTaskListItemPress}
342 enableCodeBlockWrapToggle
343 spoilerOverlay="solid"
344 onLinkPress={
apps/mobile/src/native/SelectableMarkdownText.types.ts
+9
@@ -76,6 +76,15 @@ export interface SelectableMarkdownTextProps {
76 readonly fileEmbedLabel?: (href: string, standalone: boolean) => string | null;
77 readonly resolveImageSource?: MarkdownImageSourceResolver;
78 readonly onImagePress?: (href: string) => void;
79 + /**
80 + * Makes task checkboxes tappable. The renderer ticks the box itself; `index` counts checkboxes
81 + * in document order and `checked` is the new state.
82 + */
83 + readonly onTaskListItemPress?: (event: {
84 + readonly index: number;
85 + readonly checked: boolean;
86 + readonly text: string;
87 + }) => void;
88 readonly marginTop?: number;
89 readonly marginBottom?: number;
90 readonly writingDirection?: "ltr" | "rtl";
apps/web/src/components/ChatMarkdown.browser.test.tsx
+4 -1
@@ -9,7 +9,7 @@ import "../index.css";
9
10 import { filesystemEnvironment } from "../state/filesystem";
11 import { useRightPanelStore } from "../rightPanelStore";
12 -import { setMarkdownTaskChecked } from "./files/filePreviewMode";
12 +import { setMarkdownTaskChecked } from "@t3tools/shared/markdownTaskList";
13 import { HostImageUrlContext } from "./chat/hostImageUrl";
14
15 const { workspaceSearch, filesystemMetadata } = vi.hoisted(() => ({
@@ -320,6 +320,9 @@ describe("ChatMarkdown streaming", () => {
320 await act(async () => original.click());
321 expect(editedText).toBe("- [ ] A longer first task\n- [x] Second");
322 await vi.waitFor(() => expect(checkboxes()[1]!.checked).toBe(true));
323 + await rerender(message("- [ ] A longer first task\n- [ ] Second"));
324 + expect(checkboxes()[1]).toBe(original);
325 + expect(checkboxes()[1]!.checked).toBe(false);
326 });
327 });
328
apps/web/src/components/ChatMarkdown.tsx
+4 -14
@@ -6,6 +6,7 @@ import {
6 extractMarkdownLinkHrefs,
7 inlineCodeFilePathCandidate,
8 } from "@t3tools/shared/markdownLinks";
9 +import { taskListMarkerOffset } from "@t3tools/shared/markdownTaskList";
10 import { isHostPath, resolveWorkspaceFilePath } from "@t3tools/shared/path";
11 import { usePullRequestLinking } from "~/hooks/usePullRequestLinking";
12 import {
@@ -321,17 +322,6 @@ function CodexArtifactTemplateCard(props: {
322
323 const WINDOWS_DRIVE_PATH_REGEX = /^[A-Za-z]:[\\/]/;
324
324 -function findTaskListMarkerOffset(markdown: string, listItemStart: number): number | null {
325 - const firstLineEnd = markdown.indexOf("\n", listItemStart);
326 - const firstLine = markdown.slice(
327 - listItemStart,
328 - firstLineEnd === -1 ? markdown.length : firstLineEnd,
329 - );
330 - const match = firstLine.match(/^(?:\s*(?:[-+*]|\d+[.)])\s+)(\[[ xX]\])/);
331 - if (!match?.[1]) return null;
332 - return listItemStart + firstLine.indexOf(match[1]);
333 -}
334 -
325 function orderedListGutterStyle(
326 itemCount: number,
327 start: unknown,
@@ -1035,7 +1025,7 @@ const CHAT_MARKDOWN_COMPONENTS = {
1025 <input
1026 {...props}
1027 type={type}
1038 - checked={checked}
1028 + checked={type === "checkbox" ? checked === true : checked}
1029 disabled={_disabled}
1030 readOnly={type === "checkbox"}
1031 />
@@ -1047,11 +1037,11 @@ const CHAT_MARKDOWN_COMPONENTS = {
1037 type="checkbox"
1038 name="markdown-task"
1039 aria-label="Toggle task"
1050 - checked={checked}
1040 + checked={checked === true}
1041 onChange={(event) => {
1042 const listItemStart = Number(event.currentTarget.closest("li")?.dataset.listItemOffset);
1043 if (!Number.isSafeInteger(listItemStart)) return;
1054 - const markerOffset = findTaskListMarkerOffset(text, listItemStart);
1044 + const markerOffset = taskListMarkerOffset(text, listItemStart);
1045 if (markerOffset === null) return;
1046 onTaskListChange({ markerOffset, checked: event.currentTarget.checked });
1047 }}
apps/web/src/components/files/FilePreviewPanel.test.ts
-16
@@ -10,7 +10,6 @@ import {
10 filePreviewReadErrorMessage,
11 isMarkdownPreviewFile,
12 resolveFilePreviewPath,
13 - setMarkdownTaskChecked,
13 shouldShowFileExplorer,
14 workspaceAssetResource,
15 } from "./filePreviewMode";
@@ -76,21 +75,6 @@ describe("isMarkdownPreviewFile", () => {
75 });
76 });
77
79 -describe("setMarkdownTaskChecked", () => {
80 - const markdown = "- [ ] First\n- [x] Second\n";
81 -
82 - it("checks and unchecks the task marker at the supplied offset", () => {
83 - expect(setMarkdownTaskChecked(markdown, 2, true)).toBe("- [x] First\n- [x] Second\n");
84 - expect(setMarkdownTaskChecked(markdown, 14, false)).toBe("- [ ] First\n- [ ] Second\n");
85 - expect(setMarkdownTaskChecked("1. [X] Ordered\n", 3, false)).toBe("1. [ ] Ordered\n");
86 - });
87 -
88 - it("leaves the document unchanged for a stale or invalid marker offset", () => {
89 - expect(setMarkdownTaskChecked(markdown, 0, true)).toBe(markdown);
90 - expect(setMarkdownTaskChecked(markdown, 200, true)).toBe(markdown);
91 - });
92 -});
93 -
78 describe("resolveFilePreviewPath", () => {
79 it.each([
80 ["/repo/project", null],
apps/web/src/components/files/FilePreviewPanel.tsx
+1 -1
@@ -114,10 +114,10 @@ import {
114 filePreviewReadErrorMessage,
115 isMarkdownPreviewFile,
116 resolveFilePreviewPath,
117 - setMarkdownTaskChecked,
117 shouldShowFileExplorer,
118 workspaceAssetResource,
119 } from "./filePreviewMode";
120 +import { setMarkdownTaskChecked } from "@t3tools/shared/markdownTaskList";
121 import { changeFileSaveSession, useFileSaveSession } from "./fileSaveSessions";
122 import { revisionedQuery } from "~/state/revisionedQuery";
123 import {
apps/web/src/components/files/filePreviewMode.ts
-17
@@ -40,23 +40,6 @@ export function shouldShowFileExplorer(input: {
40 return input.explorerOpen || input.relativePath === null;
41 }
42
43 -export function setMarkdownTaskChecked(
44 - markdown: string,
45 - markerOffset: number,
46 - checked: boolean,
47 -): string {
48 - if (
49 - markerOffset < 0 ||
50 - markdown[markerOffset] !== "[" ||
51 - !/[ xX]/.test(markdown[markerOffset + 1] ?? "") ||
52 - markdown[markerOffset + 2] !== "]"
53 - ) {
54 - return markdown;
55 - }
56 -
57 - return `${markdown.slice(0, markerOffset + 1)}${checked ? "x" : " "}${markdown.slice(markerOffset + 2)}`;
58 -}
59 -
43 /**
44 * The server only signs `workspace-file` assets below the workspace root, so a
45 * file opened from outside it, such as an absolute link in the thread, goes
apps/web/src/components/pullRequest/PullRequestMarkdown.tsx
+12
@@ -60,6 +60,7 @@ export function PullRequestMarkdown({
60 threadRef,
61 lineBreaks,
62 className,
63 + onTaskListChange,
64 }: {
65 text: string;
66 cwd: string;
@@ -67,6 +68,8 @@ export function PullRequestMarkdown({
68 threadRef?: ScopedThreadRef | null;
69 lineBreaks?: boolean;
70 className?: string;
71 + /** `markerOffset` is into `text`. Checkboxes stay read-only without it. */
72 + onTaskListChange?: ((input: { markerOffset: number; checked: boolean }) => void) | undefined;
73 }) {
74 const segments = splitPullRequestBody(text);
75 const context = useContext(PullRequestMarkdownContext);
@@ -92,6 +95,15 @@ export function PullRequestMarkdown({
95 {...(context ? { extraRemarkPlugins: context.remarkPlugins } : {})}
96 lineBreaks={lineBreaks ?? context?.lineBreaks ?? false}
97 sourceControlMedia
98 + onTaskListChange={
99 + onTaskListChange && segment.kind === "markdown"
100 + ? ({ markerOffset, checked }) =>
101 + onTaskListChange({
102 + markerOffset: segment.sourceOffset + markerOffset,
103 + checked,
104 + })
105 + : undefined
106 + }
107 />
108 );
109 }
apps/web/src/components/pullRequest/PullRequestSummaryTab.browser.test.tsx
+79 -2
@@ -3,10 +3,39 @@ import { EnvironmentId, ProjectId, type PullRequestDetailView } from "@t3tools/c
3 import { expect, it, vi } from "vite-plus/test";
4 import { userEvent } from "vite-plus/test/browser";
5
6 +const state = vi.hoisted(() => ({ update: vi.fn(), canUpdate: true }));
7 +
8 vi.mock(import("~/state/use-atom-command"), async (original) => ({
9 ...(await original()),
8 - useAtomCommand: (() => vi.fn()) as never,
10 + useAtomCommand: (() => state.update) as never,
11 +}));
12 +vi.mock(import("~/state/session"), async (original) => ({
13 + ...(await original()),
14 + readEnvironmentScope: () => true,
15 + useEnvironmentScope: () => true,
16 }));
17 +vi.mock(import("~/state/pullRequests"), async (original) => {
18 + const actual = await original();
19 + const { Atom } = await import("effect/reactivity");
20 + const allowed = Atom.make(true);
21 + const denied = Atom.make(false);
22 + return {
23 + ...actual,
24 + pullRequestEnvironment: {
25 + ...actual.pullRequestEnvironment,
26 + update: {
27 + ...actual.pullRequestEnvironment.update,
28 + permissionAtom: () => (state.canUpdate ? allowed : denied),
29 + },
30 + },
31 + };
32 +});
33 +
34 +function setup() {
35 + state.update.mockReset();
36 + state.update.mockResolvedValue({ _tag: "Success", value: undefined });
37 + state.canUpdate = true;
38 +}
39
40 import { act, render as renderUi } from "../../../test/render";
41 import { PullRequestSummaryTab } from "./PullRequestSummaryTab";
@@ -95,7 +124,9 @@ async function render(value = detail) {
124 });
125 }
126
98 -it("keeps an unsaved description when collapsed and reopened", async () => {
127 +it("keeps an unsaved description when collapsed and reopened, and after a failed save", async () => {
128 + setup();
129 + state.update.mockResolvedValue({ _tag: "Failure", cause: new Error("offline") });
130 await using screen = await render();
131 await act(async () =>
132 screen.container.querySelector<HTMLButtonElement>('[aria-label="Edit description"]')!.click(),
@@ -107,4 +138,50 @@ it("keeps an unsaved description when collapsed and reopened", async () => {
138 expect(screen.expanded("Description")).toBe("false");
139 await screen.click("Description");
140 expect(screen.container.querySelector("textarea")!.value).toBe("Unsaved description");
141 +
142 + await userEvent.click(screen.getByRole("button", { name: "Save" }));
143 + expect(state.update).toHaveBeenCalledTimes(1);
144 + await expect.element(screen.getByRole("button", { name: "Save" })).toBeEnabled();
145 + expect(screen.container.querySelector("textarea")!.value).toBe("Unsaved description");
146 +});
147 +
148 +it("ticks a description checkbox placed after an attachment and edits from the ticked body", async () => {
149 + setup();
150 + let finishSave = (_result: unknown) => {};
151 + state.update.mockReturnValueOnce(new Promise((resolve) => (finishSave = resolve)));
152 + const body = "Intro\n\nhttps://example.com/shot.png\n\n## Test plan\n- [ ] First\n- [ ] Second";
153 + const ticked = body.replace("- [ ] Second", "- [x] Second");
154 + await using screen = await render({ ...detail, body, observedAt: 1 });
155 + const boxes = () => screen.container.querySelectorAll<HTMLInputElement>('input[type="checkbox"]');
156 + expect([...boxes()].map((box) => box.disabled)).toEqual([false, false]);
157 +
158 + await userEvent.click(boxes()[1]!);
159 + expect(state.update).toHaveBeenCalledWith({
160 + environmentId: "environment",
161 + input: expect.objectContaining({ number: 1, body: ticked }),
162 + });
163 + expect([...boxes()].map((box) => box.checked)).toEqual([false, true]);
164 + await act(async () => finishSave({ _tag: "Success", value: undefined }));
165 +
166 + // The host has not been read since the save, so the editor starts from the ticked body.
167 + await act(async () =>
168 + screen.container.querySelector<HTMLButtonElement>('[aria-label="Edit description"]')!.click(),
169 + );
170 + expect(screen.container.querySelector("textarea")!.value).toBe(ticked);
171 +});
172 +
173 +it("leaves description checkboxes read-only without the right to edit it", async () => {
174 + setup();
175 + const body = "- [ ] First";
176 + {
177 + await using screen = await render({ ...detail, body, viewer: "someone-else" });
178 + expect(
179 + screen.container.querySelector<HTMLInputElement>('input[type="checkbox"]')!.disabled,
180 + ).toBe(true);
181 + }
182 + state.canUpdate = false;
183 + await using screen = await render({ ...detail, body });
184 + expect(screen.container.querySelector<HTMLInputElement>('input[type="checkbox"]')!.disabled).toBe(
185 + true,
186 + );
187 });
apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx
+49 -18
@@ -1,3 +1,4 @@
1 +import { useAtomValue } from "@effect/atom-react";
2 import {
3 capitalizeTerm,
4 sourceControlClients,
@@ -73,7 +74,12 @@ import {
74 import {
75 canEditPullRequestChangeRequest,
76 canEditPullRequestComment,
77 + descriptionDraftInForce,
78 + settleDescriptionSave,
79 + startDescriptionSave,
80 + type DescriptionDraft,
81 } from "@t3tools/client-runtime/pull-request-editing";
82 +import { setMarkdownTaskChecked } from "@t3tools/shared/markdownTaskList";
83 import { PullRequestMarkdown } from "./PullRequestMarkdown";
84 import { PullRequestCommentBody } from "./PullRequestCommentBody";
85 import { PullRequestMoreReplies } from "./PullRequestMoreReplies";
@@ -489,8 +495,23 @@ export function PullRequestSummaryTab({
495 const updateComment = useAtomCommand(pullRequestEnvironment.updateComment, {
496 reportFailure: false,
497 });
492 - const [bodyScope, setBodyScope] = useState<string | null>(null);
493 - const [bodySaving, setBodySaving] = useState(false);
498 + const canUpdate = useAtomValue(pullRequestEnvironment.update.permissionAtom(environmentId));
499 + const canEditDescription = canUpdate && canEditPullRequestChangeRequest(detail);
500 + // The editor keeps the body it opened from, so a failed save cannot reset what was typed.
501 + const [bodyScope, setBodyScope] = useState<{
502 + readonly url: string;
503 + readonly body: string;
504 + } | null>(null);
505 + const [descriptionDraft, setDescriptionDraft] = useState<DescriptionDraft | null>(null);
506 + const descriptionDraftKept = descriptionDraftInForce(
507 + descriptionDraft,
508 + detail.url,
509 + detail.observedAt,
510 + );
511 + if (descriptionDraftKept !== descriptionDraft) setDescriptionDraft(descriptionDraftKept);
512 + const description = descriptionDraftKept?.body ?? detail.body;
513 + const descriptionSaving = (descriptionDraftKept?.saves ?? 0) > 0;
514 + const descriptionSavesRunning = useRef(0);
515 // Hosts can reuse comment ids across pull requests.
516 const [commentScope, setCommentScope] = useState<{
517 readonly pullRequest: string;
@@ -499,17 +520,26 @@ export function PullRequestSummaryTab({
520 const [commentSaving, setCommentSaving] = useState(false);
521 const editingCommentId = commentScope?.pullRequest === detail.url ? commentScope.commentId : null;
522
502 - const saveBody = async (body: string) => {
503 - if (bodySaving) return;
504 - setBodySaving(true);
523 + // Checkbox ticks and the editor share one draft, so each starts from the other's latest body.
524 + const saveDescription = async (body: string) => {
525 + const key = detail.url;
526 + setDescriptionDraft((draft) => startDescriptionSave(draft, detail, body));
527 + descriptionSavesRunning.current += 1;
528 const result = await update({ environmentId, input: { ...reference, body } });
506 - setBodySaving(false);
507 - if (result._tag === "Failure") {
508 - toastManager.add({ type: "error", title: "Could not save the description" });
509 - return;
510 - }
511 - setBodyScope(null);
512 - onRefresh();
529 + descriptionSavesRunning.current -= 1;
530 + const saved = result._tag === "Success";
531 + setDescriptionDraft((draft) => settleDescriptionSave(draft, key, saved));
532 + if (!saved) toastManager.add({ type: "error", title: "Could not save the description" });
533 + if (descriptionSavesRunning.current === 0) onRefresh();
534 + return saved;
535 + };
536 + const saveBody = async (body: string) => {
537 + if (descriptionSaving) return;
538 + if (await saveDescription(body)) setBodyScope(null);
539 + };
540 + const toggleTask = ({ markerOffset, checked }: { markerOffset: number; checked: boolean }) => {
541 + const body = setMarkdownTaskChecked(description, markerOffset, checked);
542 + if (body !== description) void saveDescription(body);
543 };
544
545 const commentEditing: CommentEditing = {
@@ -758,16 +788,16 @@ export function PullRequestSummaryTab({
788
789 <Section key={`description:${detail.url}`} title="Description" keepMounted>
790 <div className="group">
761 - {bodyScope === detail.url ? (
791 + {bodyScope?.url === detail.url ? (
792 <PullRequestMarkdownEditor
793 allowEmpty
764 - value={detail.body}
794 + value={bodyScope.body}
795 cwd={detail.workspaceRoot}
796 environmentId={environmentId}
797 threadRef={threadRef}
798 label={`${capitalizeTerm(terminology.singular)} description`}
799 placeholder={`Describe this ${terminology.singular}`}
770 - saving={bodySaving}
800 + saving={descriptionSaving}
801 onSave={(body) => void saveBody(body)}
802 onCancel={() => setBodyScope(null)}
803 />
@@ -775,15 +805,16 @@ export function PullRequestSummaryTab({
805 <div className="flex items-start gap-1">
806 <PullRequestMarkdown
807 className="min-w-0 flex-1"
778 - text={detail.body.trim().length > 0 ? detail.body : "_No description provided._"}
808 + text={description.trim().length > 0 ? description : "_No description provided._"}
809 cwd={detail.workspaceRoot}
810 environmentId={environmentId}
811 threadRef={threadRef}
812 + onTaskListChange={canEditDescription ? toggleTask : undefined}
813 />
783 - {canEditPullRequestChangeRequest(detail) ? (
814 + {canEditDescription ? (
815 <PullRequestEditButton
816 aria-label="Edit description"
786 - onClick={() => setBodyScope(detail.url)}
817 + onClick={() => setBodyScope({ url: detail.url, body: description })}
818 />
819 ) : null}
820 </div>
docs/user/source-control.md
+2
@@ -174,6 +174,8 @@ uses the project's instructions and recent commit subjects.
174
175 Open **Pull requests** to review changes and comments, request reviewers, check out a branch,
176 or merge. You can edit review titles and descriptions and your own comments where the host allows it.
177 +Where you can edit a description, you can also tick its checkboxes from the Summary tab
178 +(the Overview tab on mobile).
179 GitLab calls these merge requests.
180
181 On mobile, **Pull requests** lists reviews across your connected environments. Open a review
packages/client-runtime/src/pullRequestEditing.test.ts
+45
@@ -11,6 +11,10 @@ import {
11 canEditPullRequestChangeRequest,
12 canEditPullRequestComment,
13 canResolvePullRequestThread,
14 + descriptionDraftInForce,
15 + settleDescriptionSave,
16 + startDescriptionSave,
17 + type DescriptionDraft,
18 } from "./pullRequestEditing.ts";
19
20 type Subject = Pick<PullRequestDetail, "author" | "capabilities" | "viewer" | "viewerPermissions">;
@@ -202,3 +206,44 @@ describe("canResolvePullRequestThread", () => {
206 ).toBe(false);
207 });
208 });
209 +
210 +describe("description drafts", () => {
211 + const url = "https://github.com/owner/repo/pull/1";
212 + const unticked = "- [ ] Ship it";
213 + const ticked = "- [x] Ship it";
214 +
215 + it("hides readings taken during the saves and ends at the first one after them", () => {
216 + // Ticking and unticking the same box saves the host's own body last.
217 + let draft: DescriptionDraft | null = startDescriptionSave(null, { url, observedAt: 1 }, ticked);
218 + draft = startDescriptionSave(draft, { url, observedAt: 1 }, unticked);
219 + expect(descriptionDraftInForce(draft, url, 2)?.body).toBe(unticked);
220 + draft = descriptionDraftInForce(draft, url, 2);
221 + draft = settleDescriptionSave(draft, url, true);
222 + expect(descriptionDraftInForce(draft, url, 2)?.body).toBe(unticked);
223 + draft = settleDescriptionSave(draft, url, true);
224 + expect(descriptionDraftInForce(draft, url, 2)?.body).toBe(unticked);
225 + // The acknowledging reading ends the draft, so the host's later ticks show.
226 + expect(descriptionDraftInForce(draft, url, 3)).toBeNull();
227 + });
228 +
229 + it("outlives failed saves until a reading after the last one, losing the body only with it", () => {
230 + let draft: DescriptionDraft | null = startDescriptionSave(null, { url, observedAt: 1 }, ticked);
231 + draft = startDescriptionSave(draft, { url, observedAt: 1 }, unticked);
232 + // The save still running writes the whole body again.
233 + draft = settleDescriptionSave(draft, url, false);
234 + expect(descriptionDraftInForce(draft, url, 2)).toMatchObject({ body: unticked, saves: 1 });
235 + draft = descriptionDraftInForce(draft, url, 2);
236 + draft = settleDescriptionSave(draft, url, false);
237 + expect(descriptionDraftInForce(draft, url, 2)).toMatchObject({ body: null, saves: 0 });
238 + expect(settleDescriptionSave(draft, url, true)).toBe(draft);
239 + expect(descriptionDraftInForce(draft, url, 3)).toBeNull();
240 + });
241 +
242 + it("belongs to one change request", () => {
243 + const draft = startDescriptionSave(null, { url, observedAt: 1 }, ticked);
244 + const other = "https://github.com/owner/repo/pull/2";
245 + expect(descriptionDraftInForce(draft, other, 1)).toBeNull();
246 + expect(settleDescriptionSave(draft, other, false)).toBe(draft);
247 + expect(startDescriptionSave(draft, { url: other, observedAt: 5 }, unticked).saves).toBe(1);
248 + });
249 +});
packages/client-runtime/src/pullRequestEditing.ts
+44 -3
@@ -49,17 +49,58 @@ export interface MaintainerEditsChoice {
49 * A saved choice ends at the first host reading delivered after the save. Readers refresh once it
50 * succeeds, which drops reads still in flight, so that reading started after the write.
51 */
52 -export function maintainerEditsChoiceInForce(
53 - choice: MaintainerEditsChoice | null,
52 +export function maintainerEditsChoiceInForce<
53 + Choice extends { readonly key: string; readonly observedAt: number | undefined },
54 +>(
55 + choice: Choice | null,
56 key: string,
57 observedAt: number | undefined,
58 saving: boolean,
57 -): MaintainerEditsChoice | null {
59 +): Choice | null {
60 if (choice === null || choice.key !== key) return null;
61 if (saving) return choice.observedAt === observedAt ? choice : { ...choice, observedAt };
62 return observedAt !== undefined && choice.observedAt === observedAt ? choice : null;
63 }
64
65 +/** A description written from this client, shown in place of the host's copy. */
66 +export interface DescriptionDraft {
67 + readonly key: string;
68 + readonly observedAt: number | undefined;
69 + /** Null once the last save failed: until a host reading, nobody knows which saves landed. */
70 + readonly body: string | null;
71 + /** Saves still running. The host applies them in order, so the last one is `body`. */
72 + readonly saves: number;
73 +}
74 +
75 +/** Same lifetime as a maintainer edits choice: until the first host reading after the saves. */
76 +export function descriptionDraftInForce(
77 + draft: DescriptionDraft | null,
78 + key: string,
79 + observedAt: number | undefined,
80 +): DescriptionDraft | null {
81 + return maintainerEditsChoiceInForce(draft, key, observedAt, (draft?.saves ?? 0) > 0);
82 +}
83 +
84 +export function startDescriptionSave(
85 + draft: DescriptionDraft | null,
86 + detail: { readonly url: string; readonly observedAt?: number | undefined },
87 + body: string,
88 +): DescriptionDraft {
89 + const saves = draft?.key === detail.url ? draft.saves : 0;
90 + return { key: detail.url, observedAt: detail.observedAt, body, saves: saves + 1 };
91 +}
92 +
93 +/** Each save writes the whole body, so a failure only loses `body` when no later save is running. */
94 +export function settleDescriptionSave(
95 + draft: DescriptionDraft | null,
96 + key: string,
97 + saved: boolean,
98 +): DescriptionDraft | null {
99 + if (draft === null || draft.key !== key || draft.saves === 0) return draft;
100 + const saves = draft.saves - 1;
101 + return { ...draft, saves, body: saved || saves > 0 ? draft.body : null };
102 +}
103 +
104 /** Hosts do not support rewriting review summaries through comment mutations. */
105 export function canEditPullRequestComment(
106 detail: EditingSubject,
packages/client-runtime/src/pullRequestMarkdown.test.ts
+29 -12
@@ -11,17 +11,34 @@ describe("pull request body segmentation", () => {
11 "Before\n\nhttps://github.com/user-attachments/assets/2f8c1a90-1b2c-4d5e-8f90-abcdef123456\n\nAfter",
12 ),
13 ).toEqual([
14 - { id: "markdown:0", kind: "markdown", text: "Before" },
14 + { id: "markdown:0", kind: "markdown", text: "Before", sourceOffset: 0 },
15 {
16 id: "attachment:1",
17 kind: "attachment",
18 url: "https://github.com/user-attachments/assets/2f8c1a90-1b2c-4d5e-8f90-abcdef123456",
19 media: "video",
20 },
21 - { id: "markdown:2", kind: "markdown", text: "After" },
21 + { id: "markdown:2", kind: "markdown", text: "After", sourceOffset: 89 },
22 ]);
23 });
24
25 + it("places each prose run at its offset in the body", () => {
26 + const body =
27 + '\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';
28 + const prose = splitPullRequestBody(body).flatMap((segment) =>
29 + segment.kind === "markdown" ? [segment] : [],
30 + );
31 + expect(prose.map((segment) => segment.text)).toEqual([
32 + "- [ ] Before",
33 + " - [ ] code\n- [x] After",
34 + ]);
35 + for (const segment of prose) {
36 + expect(body.slice(segment.sourceOffset, segment.sourceOffset + segment.text.length)).toBe(
37 + segment.text,
38 + );
39 + }
40 + });
41 +
42 it("reads the source out of a video tag, including a multi-line one", () => {
43 expect(
44 splitPullRequestBody(
@@ -41,49 +58,49 @@ describe("pull request body segmentation", () => {
58 const body =
59 '<img width="1414" alt="image" src="https://github.com/user-attachments/assets/7195f963-51a9-4331-be74-3e06be760422" />';
60 expect(splitPullRequestBody(body)).toEqual([
44 - { id: "markdown:0", kind: "markdown", text: body },
61 + { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
62 ]);
63 });
64
65 it("leaves an ordinary link alone, whether it is bare or written as markdown", () => {
66 const body = "https://example.com/page\n\n[the docs](https://example.com/docs)";
67 expect(splitPullRequestBody(body)).toEqual([
51 - { id: "markdown:0", kind: "markdown", text: body },
68 + { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
69 ]);
70 });
71
72 it("never lifts a link inside fenced code out of it", () => {
73 const body = "```\nhttps://example.com/demo.mp4\n```";
74 expect(splitPullRequestBody(body)).toEqual([
58 - { id: "markdown:0", kind: "markdown", text: body },
75 + { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
76 ]);
77 });
78
79 it("does not let a different fence marker close an open fence", () => {
80 const body = "```\n~~~\nhttps://example.com/demo.mp4\n```";
81 expect(splitPullRequestBody(body)).toEqual([
65 - { id: "markdown:0", kind: "markdown", text: body },
82 + { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
83 ]);
84 });
85
86 it("keeps a video tag that shares its line with prose as markdown", () => {
87 const body = 'Before <video src="https://example.com/a.mp4"></video> after';
88 expect(splitPullRequestBody(body)).toEqual([
72 - { id: "markdown:0", kind: "markdown", text: body },
89 + { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
90 ]);
91 });
92
93 it("treats an info-string fence as a nested opener, not a close", () => {
94 const body = "```\n```javascript\nhttps://example.com/demo.mp4\n```";
95 expect(splitPullRequestBody(body)).toEqual([
79 - { id: "markdown:0", kind: "markdown", text: body },
96 + { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
97 ]);
98 });
99
100 it("leaves an indented code line alone even when it is only a video link", () => {
101 const body = " https://example.com/demo.mp4";
102 expect(splitPullRequestBody(body)).toEqual([
86 - { id: "markdown:0", kind: "markdown", text: body },
103 + { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
104 ]);
105 });
106
@@ -92,14 +109,14 @@ describe("pull request body segmentation", () => {
109 "\n",
110 );
111 expect(splitPullRequestBody(body)).toEqual([
95 - { id: "markdown:0", kind: "markdown", text: body },
112 + { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
113 ]);
114 });
115
116 it("refuses a non-http source rather than making a link out of it", () => {
117 const body = '<video src="javascript:alert(1)"></video>';
118 expect(splitPullRequestBody(body)).toEqual([
102 - { id: "markdown:0", kind: "markdown", text: body },
119 + { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
120 ]);
121 });
122 });
@@ -119,7 +136,7 @@ describe("media on custom hosts", () => {
136 const body =
137 "See [recording](https://drop.example.com/a.mp4) for context.\n\n```md\nhttps://drop.example.com/a.png\n```";
138 expect(splitPullRequestBody(body)).toEqual([
122 - { id: "markdown:0", kind: "markdown", text: body },
139 + { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
140 ]);
141 });
142 });
packages/client-runtime/src/pullRequestMarkdown.ts
+21 -5
@@ -2,7 +2,13 @@ import { sourceControlClients, type ReferenceAutolink } from "./sourceControlCli
2
3 /** `id` is positional on purpose: the same attachment can be embedded twice in one body. */
4 export type PullRequestBodySegment =
5 - | { readonly id: string; readonly kind: "markdown"; readonly text: string }
5 + | {
6 + readonly id: string;
7 + readonly kind: "markdown";
8 + readonly text: string;
9 + /** Where `text` starts in the body, so an edit made to it can be written back. */
10 + readonly sourceOffset: number;
11 + }
12 | {
13 readonly id: string;
14 readonly kind: "attachment";
@@ -53,21 +59,31 @@ function attachmentFromLine(
59 export function splitPullRequestBody(body: string): ReadonlyArray<PullRequestBodySegment> {
60 const segments: PullRequestBodySegment[] = [];
61 const markdown: string[] = [];
62 + let markdownStart = 0;
63 let openFence: string | null = null;
64
65 // Blank lines around a run are dropped, but never leading spaces: four of them open an
66 // indented code block, so trimming a run would silently turn code into prose.
67 const flushMarkdown = () => {
61 - const text = markdown.join("\n").replace(/^\n+/u, "").replace(/\s+$/u, "");
68 + const joined = markdown.join("\n");
69 + const text = joined.replace(/^\n+/u, "");
70 + const sourceOffset = markdownStart + joined.length - text.length;
71 markdown.length = 0;
72 if (text.trim().length > 0) {
64 - segments.push({ id: `markdown:${segments.length}`, kind: "markdown", text });
73 + segments.push({
74 + id: `markdown:${segments.length}`,
75 + kind: "markdown",
76 + text: text.replace(/\s+$/u, ""),
77 + sourceOffset,
78 + });
79 }
80 };
81
82 const lines = body.split("\n");
69 - for (let index = 0; index < lines.length; index += 1) {
83 + let lineStart = 0;
84 + for (let index = 0; index < lines.length; lineStart += lines[index]!.length + 1, index += 1) {
85 const line = lines[index]!;
86 + if (markdown.length === 0) markdownStart = lineStart;
87 const fenceMatch = FENCE_PATTERN.exec(line);
88 if (fenceMatch !== null) {
89 const fence = fenceMatch[1]!;
@@ -120,7 +136,7 @@ export function splitPullRequestBody(body: string): ReadonlyArray<PullRequestBod
136
137 media: "video",
138 });
123 - index = cursor;
139 + for (; index < cursor; index += 1) lineStart += lines[index]!.length + 1;
140 } else {
141 // Unclosed, or nothing linkable in it: prose. Only this line is consumed, so the
142 // lines that were looked at are still parsed on their own terms.
packages/client-runtime/src/state/pullRequests.test.ts
+63 -3
@@ -1363,20 +1363,80 @@ it.effect("shares checks reads across reference property order", () =>
1363 it.effect("keeps live detail reads separate from reads that allow stale data", () =>
1364 Effect.scoped(
1365 Effect.gen(function* () {
1366 + let reads = 0;
1367 + let hostStamp: number | undefined;
1368 + let hold = false;
1369 + const readStarted = yield* Latch.make();
1370 + const releaseRead = yield* Latch.make();
1371 const client = {
1372 [WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.never,
1373 [WS_METHODS.pullRequestsDetail]: (input: { allowStale?: boolean }) =>
1369 - Effect.succeed({ title: input.allowStale === false ? "latest checks" : "cached checks" }),
1374 + Effect.gen(function* () {
1375 + reads++;
1376 + if (hold) {
1377 + yield* readStarted.open;
1378 + yield* releaseRead.await;
1379 + }
1380 + return {
1381 + title: input.allowStale === false ? "latest checks" : "cached checks",
1382 + ...(hostStamp === undefined ? {} : { observedAt: hostStamp }),
1383 + };
1384 + }),
1385 } as unknown as WsRpcProtocolClient;
1371 - const { atoms, registry } = yield* makeTestRuntime(client);
1386 + const { atoms, registry, supervisor } = yield* makeTestRuntime(client);
1387 const target = {
1388 environmentId: TARGET.environmentId,
1389 input: { projectId: ProjectId.make("project-1"), repository: "acme/web", number: 1 },
1390 };
1391 const cached = atoms.detail(target);
1392 const live = atoms.detail({ ...target, input: { ...target.input, allowStale: false } });
1378 - expect((yield* AtomRegistry.getResult(registry, cached)).title).toBe("cached checks");
1393 + const first = yield* AtomRegistry.getResult(registry, cached);
1394 + expect(first.title).toBe("cached checks");
1395 + expect(first.observedAt).toBeUndefined();
1396 + const reading = atoms.detailReadVersion(target);
1397 + const firstVersion = registry.get(reading);
1398 + expect(firstVersion).toBeGreaterThan(0);
1399 expect((yield* AtomRegistry.getResult(registry, live)).title).toBe("latest checks");
1400 + expect(reads).toBe(2);
1401 + hold = true;
1402 + registry.refresh(cached);
1403 + yield* readStarted.await;
1404 + expect(registry.get(reading)).toBe(firstVersion);
1405 + yield* releaseRead.open;
1406 + expect(yield* AtomRegistry.getResult(registry, cached, { suspendOnWaiting: true })).toBe(
1407 + first,
1408 + );
1409 + const settledVersion = registry.get(reading);
1410 + expect(settledVersion).toBeGreaterThan(firstVersion);
1411 + hold = false;
1412 +
1413 + yield* SubscriptionRef.update(supervisor.state, (state) => ({
1414 + ...state,
1415 + phase: "offline" as const,
1416 + }));
1417 + yield* Effect.yieldNow;
1418 + registry.refresh(cached);
1419 + const offline = yield* AtomRegistry.getResult(registry, cached, { suspendOnWaiting: true });
1420 + expect(offline.observedAt).toBeUndefined();
1421 + expect(registry.get(reading)).toBe(settledVersion);
1422 + expect(reads).toBe(3);
1423 +
1424 + yield* SubscriptionRef.update(supervisor.state, (state) => ({
1425 + ...state,
1426 + phase: "connected" as const,
1427 + }));
1428 + yield* Effect.yieldNow;
1429 + registry.refresh(cached);
1430 + const reread = yield* AtomRegistry.getResult(registry, cached, { suspendOnWaiting: true });
1431 + expect(reread).toBe(first);
1432 + expect(reread.observedAt).toBeUndefined();
1433 + expect(registry.get(reading)).toBeGreaterThan(settledVersion);
1434 +
1435 + hostStamp = 27;
1436 + registry.refresh(cached);
1437 + expect(
1438 + (yield* AtomRegistry.getResult(registry, cached, { suspendOnWaiting: true })).observedAt,
1439 + ).toBe(hostStamp);
1440 }),
1441 ),
1442 );
packages/client-runtime/src/state/pullRequests.ts
+31 -1
@@ -221,6 +221,14 @@ export function createPullRequestEnvironmentAtoms<R, E>(
221 refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),
222 }),
223 );
224 + const detailAnswerAtoms = Atom.family((_key: string) =>
225 + Atom.make<{ readonly value: PullRequestDetail; readonly version: number } | null>(null).pipe(
226 + Atom.setIdleTTL(5 * 60_000),
227 + ),
228 + );
229 + const detailAnswers = normalizePullRequestQuery((target) =>
230 + detailAnswerAtoms(JSON.stringify(target)),
231 + );
232 const detail = writableQueryFamily(
233 createEnvironmentRpcQueryAtomFamily(runtime, {
234 label: "environment-data:pull-requests:detail",
@@ -229,9 +237,30 @@ export function createPullRequestEnvironmentAtoms<R, E>(
237 execute: (input) => routedRequest(WS_METHODS.pullRequestsDetail, input),
238 staleTimeMs: 60_000,
239 refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),
232 - ...(onAnswer.detail === undefined ? {} : { onAnswer: onAnswer.detail }),
240 + onAnswer: (target, value, registry) =>
241 + Effect.sync(() => {
242 + // Cache reads bypass onAnswer, and server freshness stays separate from local readbacks.
243 + registry.update(detailAnswers(target), (previous) => ({
244 + value,
245 + version: (previous?.version ?? 0) + 1,
246 + }));
247 + }).pipe(Effect.andThen(() => onAnswer.detail?.(target, value, registry) ?? Effect.void)),
248 }),
249 );
250 + const detailReadVersions = Atom.family((source: ReturnType<typeof detail>) =>
251 + Atom.family((answer: ReturnType<typeof detailAnswers>) =>
252 + Atom.make((get) => {
253 + const result = get(source);
254 + const latest = get(answer);
255 + return result._tag === "Success" && !result.waiting && result.value === latest?.value
256 + ? latest.version
257 + : Option.getOrElse(get.self<number>(), () => 0);
258 + }).pipe(Atom.setIdleTTL(5 * 60_000)),
259 + ),
260 + );
261 + const detailReadVersion = normalizePullRequestQuery((target) =>
262 + detailReadVersions(detail(target))(detailAnswers(target)),
263 + );
264 const preview = writableQueryFamily(
265 createEnvironmentRpcQueryAtomFamily(runtime, {
266 label: "environment-data:pull-requests:preview",
@@ -383,6 +412,7 @@ export function createPullRequestEnvironmentAtoms<R, E>(
412 staleTimeMs: 5 * 60_000,
413 }),
414 detail,
415 + detailReadVersion,
416 preview,
417 previewCard,
418 checks: normalizePullRequestQuery(
packages/shared/package.json
+4
@@ -459,6 +459,10 @@
459 "types": "./src/markdownFrontmatter.ts",
460 "import": "./src/markdownFrontmatter.ts"
461 },
462 + "./markdownTaskList": {
463 + "types": "./src/markdownTaskList.ts",
464 + "import": "./src/markdownTaskList.ts"
465 + },
466 "./markdownListIndentation": {
467 "types": "./src/markdownListIndentation.ts",
468 "import": "./src/markdownListIndentation.ts"
packages/shared/src/markdownTaskList.test.ts new
+72
@@ -0,0 +1,72 @@
1 +import { describe, expect, it } from "vite-plus/test";
2 +
3 +import { markdownTaskMarkerOffset, setMarkdownTaskChecked } from "./markdownTaskList.ts";
4 +
5 +describe("setMarkdownTaskChecked", () => {
6 + const markdown = "- [ ] First\n- [x] Second\n";
7 +
8 + it("checks and unchecks the task marker at the supplied offset", () => {
9 + expect(setMarkdownTaskChecked(markdown, 2, true)).toBe("- [x] First\n- [x] Second\n");
10 + expect(setMarkdownTaskChecked(markdown, 14, false)).toBe("- [ ] First\n- [ ] Second\n");
11 + expect(setMarkdownTaskChecked("1. [X] Ordered\n", 3, false)).toBe("1. [ ] Ordered\n");
12 + });
13 +
14 + it("leaves the document unchanged for a stale or invalid marker offset", () => {
15 + expect(setMarkdownTaskChecked(markdown, 0, true)).toBe(markdown);
16 + expect(setMarkdownTaskChecked(markdown, 200, true)).toBe(markdown);
17 + });
18 +});
19 +
20 +describe("markdownTaskMarkerOffset", () => {
21 + const markdown = [
22 + "## Test plan",
23 + "- [ ] `vp lint` passes",
24 + " - [x] Nested **step**",
25 + "```md",
26 + "- [ ] Inside a fence",
27 + "```",
28 + "> 1. [X] Quoted [link](https://example.com)",
29 + "- [ ] Wrapped",
30 + " onto two lines",
31 + ].join("\n");
32 + const marker = (offset: number | null) =>
33 + offset === null ? null : markdown.slice(offset, offset + 3);
34 +
35 + it("finds the tapped checkbox, skipping look-alikes in code", () => {
36 + expect(marker(markdownTaskMarkerOffset(markdown, 0, "vp lint passes", true))).toBe("[ ]");
37 + expect(marker(markdownTaskMarkerOffset(markdown, 1, "Nested step", false))).toBe("[x]");
38 + // Native numbering restarts after code blocks and blockquotes.
39 + expect(marker(markdownTaskMarkerOffset(markdown, 0, "Quoted link", false))).toBe("[X]");
40 + // Android cuts the text at a line break, a soft one too with hard line breaks; iOS doesn't.
41 + for (const text of ["Wrapped", "Wrapped onto two lines"]) {
42 + expect(markdownTaskMarkerOffset(markdown, 0, text, true)).toBe(markdown.lastIndexOf("[ ]"));
43 + }
44 + });
45 +
46 + it("tells identical labels apart by count within one list and by state", () => {
47 + const same = "- [ ] Same\n- [ ] Same\n\n```\nx\n```\n\n- [x] Same\n";
48 + expect(markdownTaskMarkerOffset(same, 0, "Same", true)).toBe(2);
49 + expect(markdownTaskMarkerOffset(same, 1, "Same", true)).toBe(13);
50 + expect(markdownTaskMarkerOffset(same, 0, "Same", false)).toBe(same.lastIndexOf("[x]"));
51 + });
52 +
53 + it("refuses a checkbox it can't trace to exactly one task", () => {
54 + expect(markdownTaskMarkerOffset(markdown, 1, "vp lint passes", true)).toBeNull();
55 + expect(markdownTaskMarkerOffset(markdown, 0, "vp lint passes", false)).toBeNull();
56 + expect(markdownTaskMarkerOffset(markdown, 0, "Wrapped onto", true)).toBeNull();
57 + expect(markdownTaskMarkerOffset(markdown, 4, "", true)).toBeNull();
58 +
59 + const similar = "- [ ] Similar\n\n```text\nseparator\n```\n\n- [ ] Similar<br>different\n";
60 + // iOS keeps hard breaks in the text, so it names the second task.
61 + expect(markdownTaskMarkerOffset(similar, 0, "Similar
different", true)).toBe(
62 + similar.lastIndexOf("[ ]"),
63 + );
64 + // Android cuts it to "Similar", which both tasks could be.
65 + expect(markdownTaskMarkerOffset(similar, 0, "Similar", true)).toBeNull();
66 +
67 + for (const label of ["Similar [docs](https://github.com/pingdotgg/t3code)", "Similar $x$"]) {
68 + const attachment = similar.replace("Similar<br>different", label);
69 + expect(markdownTaskMarkerOffset(attachment, 0, "Similar \uFFFC", true)).toBeNull();
70 + }
71 + });
72 +});
packages/shared/src/markdownTaskList.ts new
+94
@@ -0,0 +1,94 @@
1 +import type { ListItem, Nodes } from "mdast";
2 +import remarkGfm from "remark-gfm";
3 +import remarkParse from "remark-parse";
4 +import { unified } from "unified";
5 +
6 +const parser = unified().use(remarkParse).use(remarkGfm);
7 +
8 +/** Offset of the `[ ]` marker on the first line of the list item starting at `listItemStart`. */
9 +export function taskListMarkerOffset(markdown: string, listItemStart: number): number | null {
10 + const firstLineEnd = markdown.indexOf("\n", listItemStart);
11 + const firstLine = markdown.slice(
12 + listItemStart,
13 + firstLineEnd === -1 ? markdown.length : firstLineEnd,
14 + );
15 + const match = firstLine.match(/^(?:\s*(?:[-+*]|\d+[.)])\s+)(\[[ xX]\])/);
16 + if (!match?.[1]) return null;
17 + return listItemStart + firstLine.indexOf(match[1]);
18 +}
19 +
20 +export function setMarkdownTaskChecked(
21 + markdown: string,
22 + markerOffset: number,
23 + checked: boolean,
24 +): string {
25 + if (
26 + markerOffset < 0 ||
27 + markdown[markerOffset] !== "[" ||
28 + !/[ xX]/.test(markdown[markerOffset + 1] ?? "") ||
29 + markdown[markerOffset + 2] !== "]"
30 + ) {
31 + return markdown;
32 + }
33 +
34 + return `${markdown.slice(0, markerOffset + 1)}${checked ? "x" : " "}${markdown.slice(markerOffset + 2)}`;
35 +}
36 +
37 +/** Hard breaks as U+2028, as iOS draws them; soft breaks stay "\n". */
38 +function plainText(node: Nodes): string {
39 + if (node.type === "text" || node.type === "inlineCode") return node.value;
40 + if (node.type === "break" || (node.type === "html" && /^<br\b/i.test(node.value))) {
41 + return "\u2028";
42 + }
43 + return "children" in node ? node.children.map(plainText).join("") : "";
44 +}
45 +
46 +const lettersAndDigits = (text: string) => text.replace(/[^\p{L}\p{N}]/gu, "");
47 +
48 +/** iOS sends the first paragraph whole. Android cuts it at a hard break, or any break with hard breaks on. */
49 +function renderedTexts(item: ListItem): string[] {
50 + const first = item.children[0];
51 + const text = first?.type === "paragraph" ? plainText(first) : "";
52 + return [text, text.replace(/\u2028[^]*$/, ""), text.replace(/[\u2028\n][^]*$/, "")].map(
53 + lettersAndDigits,
54 + );
55 +}
56 +
57 +// Native renderers give other top-level blocks (code, tables, quotes, media) their own views, and
58 +// each view numbers its tasks from 0. Lists, headings and rules share the text view around them.
59 +const sharedViewBlocks = new Set(["list", "heading", "thematicBreak"]);
60 +
61 +/**
62 + * Marker offset of the task a native checkbox tap names. Null unless exactly one task has that
63 + * text and state and could have that index under some split of the document into native views.
64 + */
65 +export function markdownTaskMarkerOffset(
66 + markdown: string,
67 + index: number,
68 + renderedText: string,
69 + checked: boolean,
70 +): number | null {
71 + // Native attachments replace their labels, so the remaining text could name another task.
72 + if (renderedText.includes("\uFFFC")) return null;
73 + const tasks: ListItem[] = [];
74 + const collect = (node: Nodes) => {
75 + if (node.type === "listItem" && typeof node.checked === "boolean") tasks.push(node);
76 + if ("children" in node) node.children.forEach(collect);
77 + };
78 + const viewStarts = new Set([0]);
79 + for (const block of parser.parse(markdown).children) {
80 + const before = tasks.length;
81 + collect(block);
82 + if (sharedViewBlocks.has(block.type)) continue;
83 + for (let count = before; count <= tasks.length; count++) viewStarts.add(count);
84 + }
85 + const rendered = lettersAndDigits(renderedText);
86 + const matches = tasks.filter(
87 + (task, position) =>
88 + task.checked === !checked &&
89 + viewStarts.has(position - index) &&
90 + renderedTexts(task).includes(rendered),
91 + );
92 + const start = matches.length === 1 ? matches[0]?.position?.start.offset : undefined;
93 + return start === undefined ? null : taskListMarkerOffset(markdown, start);
94 +}