feat(web): keep unsent drafts one click away in the sidebar (#5777)
Co-authored-by: Claude Fable 5 <[email protected]>
This commit is contained in:
1 parent
ddaa6afef5
commit
05eb051184
4 files changed
+479
-42
No files matched your search
@@ -163,7 +163,13 @@ import { SidebarContent, SidebarGroup, SidebarMenuButton, useSidebar } from "./u
|
||||
import { SidebarChromeFooter, SidebarChromeHeader } from "./sidebar/SidebarChrome";
|
||||
import { Popover, PopoverPopup, PopoverTrigger } from "./ui/popover";
|
||||
import { Tooltip, TooltipPopup, TooltipProvider, TooltipTrigger } from "./ui/tooltip";
|
||||
import { useComposerDraftStore } from "../composerDraftStore";
|
||||
import {
|
||||
composerDraftHasUserContent,
|
||||
DraftId,
|
||||
useComposerDraftStore,
|
||||
type ComposerThreadDraftState,
|
||||
type DraftSessionState,
|
||||
} from "../composerDraftStore";
|
||||
|
||||
// Settled-tail paging: recent history is the common lookup; the deep tail
|
||||
// stays behind an explicit Show more.
|
||||
@@ -404,6 +410,229 @@ function SortablePinnedThreadRow(props: {
|
||||
return props.children({ listeners, setNodeRef, transform, transition, isDragging });
|
||||
}
|
||||
|
||||
// One unsent draft session the user has invested content in. Two lines,
|
||||
// nothing else: project name, then the typed prompt. All the draft's
|
||||
// settings (model, env mode, branch, worktree) still travel with it —
|
||||
// clicking is a plain navigation to /draft/$draftId, which touches nothing.
|
||||
// While the draft is open the row renders a frozen snapshot (see
|
||||
// SidebarDraftBlock); memoized so per-keystroke block re-renders skip it
|
||||
// entirely.
|
||||
const SidebarDraftRow = memo(function SidebarDraftRow(props: {
|
||||
draftId: DraftId;
|
||||
session: DraftSessionState;
|
||||
composer: ComposerThreadDraftState;
|
||||
projectTitle: string | null;
|
||||
projectCwd: string | null;
|
||||
isActive: boolean;
|
||||
onNavigate: (draftId: DraftId) => void;
|
||||
onDiscard: (draftId: DraftId) => void;
|
||||
}) {
|
||||
const { composer, draftId, onDiscard, onNavigate, session } = props;
|
||||
const promptPreview = composer.prompt.trim().split("\n", 1)[0] ?? "";
|
||||
// images mirrors persistedAttachments once rehydration finishes; before
|
||||
// that only the persisted list is populated, hence max not sum.
|
||||
const attachmentCount =
|
||||
Math.max(composer.images.length, composer.persistedAttachments.length) +
|
||||
composer.terminalContexts.length +
|
||||
composer.elementContexts.length +
|
||||
composer.previewAnnotations.length +
|
||||
composer.reviewComments.length;
|
||||
const preview =
|
||||
promptPreview.length > 0
|
||||
? promptPreview
|
||||
: `${attachmentCount} attachment${attachmentCount === 1 ? "" : "s"}`;
|
||||
const handleActivate = useCallback(() => onNavigate(draftId), [draftId, onNavigate]);
|
||||
const handleKeyDown = useCallback(
|
||||
(event: ReactKeyboardEvent) => {
|
||||
// Keys targeting the nested discard button belong to the button:
|
||||
// preventDefault here would swallow Space's synthesized click and
|
||||
// navigate instead of discarding.
|
||||
if ((event.target as HTMLElement).closest("button")) return;
|
||||
if (event.key === "Enter" || event.key === " ") {
|
||||
event.preventDefault();
|
||||
onNavigate(draftId);
|
||||
}
|
||||
},
|
||||
[draftId, onNavigate],
|
||||
);
|
||||
const handleDiscard = useCallback(
|
||||
(event: ReactMouseEvent) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
onDiscard(draftId);
|
||||
},
|
||||
[draftId, onDiscard],
|
||||
);
|
||||
return (
|
||||
<li className="list-none py-0.5">
|
||||
<div
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
data-testid="sidebar-draft-row"
|
||||
className={cn(
|
||||
"group/sidebar-row relative w-full cursor-pointer overflow-hidden rounded-md text-left text-sidebar-foreground outline-none select-none",
|
||||
props.isActive
|
||||
? "bg-sidebar-row-active"
|
||||
: "bg-amber-400/[0.04] hover:bg-amber-400/[0.08]",
|
||||
)}
|
||||
onClick={handleActivate}
|
||||
onKeyDown={handleKeyDown}
|
||||
>
|
||||
<div className="relative z-10 px-[var(--sidebar-row-content-inset)] py-[var(--sidebar-content-inset)]">
|
||||
<div className="flex h-5 min-w-0 items-center gap-1.5">
|
||||
<SquarePenIcon
|
||||
aria-hidden
|
||||
className="size-3 shrink-0 text-amber-600 dark:text-amber-300/80"
|
||||
/>
|
||||
<ProjectFavicon
|
||||
environmentId={session.environmentId}
|
||||
cwd={props.projectCwd ?? ""}
|
||||
className="size-4 shrink-0"
|
||||
/>
|
||||
<span className="min-w-0 flex-1 truncate text-xs font-medium text-secondary-label">
|
||||
{props.projectTitle}
|
||||
</span>
|
||||
<span className="ml-auto flex h-5 min-w-5 shrink-0 items-center justify-end">
|
||||
<button
|
||||
type="button"
|
||||
aria-label="Discard draft"
|
||||
title="Discard draft"
|
||||
onClick={handleDiscard}
|
||||
className="pointer-events-none inline-flex cursor-pointer items-center rounded-md bg-transparent px-1 text-muted-foreground opacity-0 transition-opacity hover:text-foreground focus-visible:pointer-events-auto focus-visible:opacity-100 group-hover/sidebar-row:pointer-events-auto group-hover/sidebar-row:opacity-100"
|
||||
>
|
||||
<XIcon className="size-3" />
|
||||
</button>
|
||||
</span>
|
||||
</div>
|
||||
<div className="mt-0.5 truncate text-sm font-medium text-foreground/90">{preview}</div>
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
});
|
||||
|
||||
interface SidebarDraftRowData {
|
||||
draftId: DraftId;
|
||||
session: DraftSessionState;
|
||||
composer: ComposerThreadDraftState;
|
||||
}
|
||||
|
||||
// Draft sessions with user content, surfaced above the pinned block so an
|
||||
// interrupted "new thread" stays one click away. Self-contained (own store
|
||||
// subscription + closing divider) so per-keystroke composer updates
|
||||
// re-render only this block, never the whole sidebar. Vanishes at count 0.
|
||||
const SidebarDraftBlock = memo(function SidebarDraftBlock(props: {
|
||||
projectDisplayNameByKey: ReadonlyMap<string, string>;
|
||||
projectCwdByKey: ReadonlyMap<string, string>;
|
||||
scopedProjectKeys: ReadonlySet<string> | null;
|
||||
routeDraftId: string | null;
|
||||
onNavigateToDraft: (draftId: DraftId) => void;
|
||||
}) {
|
||||
const draftThreadsByThreadKey = useComposerDraftStore((store) => store.draftThreadsByThreadKey);
|
||||
const draftsByThreadKey = useComposerDraftStore((store) => store.draftsByThreadKey);
|
||||
const clearDraftThread = useComposerDraftStore((store) => store.clearDraftThread);
|
||||
// The open draft's row is FROZEN at the moment the draft became the route:
|
||||
// it stays visible (like a thread row) but never repaints while the user
|
||||
// types. A draft that was never navigated away from has no snapshot to
|
||||
// freeze, so a fresh typing session shows no row at all. Captured
|
||||
// synchronously on route change (setState-during-render derived state) so
|
||||
// the row never flickers out for a frame between route change and capture.
|
||||
const [frozenActive, setFrozenActive] = useState<{
|
||||
routeDraftId: string | null;
|
||||
row: SidebarDraftRowData | null;
|
||||
}>({ routeDraftId: null, row: null });
|
||||
if (frozenActive.routeDraftId !== props.routeDraftId) {
|
||||
let row: SidebarDraftRowData | null = null;
|
||||
if (props.routeDraftId !== null) {
|
||||
const draftId = DraftId.make(props.routeDraftId);
|
||||
const store = useComposerDraftStore.getState();
|
||||
const session = store.getDraftSession(draftId);
|
||||
const composer = store.getComposerDraft(draftId);
|
||||
row =
|
||||
session && session.promotedTo == null && composer && composerDraftHasUserContent(composer)
|
||||
? { draftId, session, composer }
|
||||
: null;
|
||||
}
|
||||
setFrozenActive({ routeDraftId: props.routeDraftId, row });
|
||||
}
|
||||
const drafts = useMemo(() => {
|
||||
const rows: SidebarDraftRowData[] = [];
|
||||
// Every non-promoted session with content gets a row, mapped or not:
|
||||
// new-thread surfaces mint fresh drafts and leave invested ones behind
|
||||
// unmapped, so the mapping only knows about the latest per project.
|
||||
for (const [draftKey, session] of Object.entries(draftThreadsByThreadKey)) {
|
||||
if (session.promotedTo != null) {
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
props.scopedProjectKeys !== null &&
|
||||
!props.scopedProjectKeys.has(`${session.environmentId}:${session.projectId}`)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
if (draftKey === props.routeDraftId) {
|
||||
// Open draft: render the frozen entry snapshot, or nothing for a
|
||||
// draft that has never been left. Gated on the LIVE session above so
|
||||
// send/discard still removes the row immediately.
|
||||
if (frozenActive.routeDraftId === draftKey && frozenActive.row !== null) {
|
||||
rows.push(frozenActive.row);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
const composer = draftsByThreadKey[draftKey];
|
||||
if (!composer || !composerDraftHasUserContent(composer)) {
|
||||
continue;
|
||||
}
|
||||
rows.push({ draftId: DraftId.make(draftKey), session, composer });
|
||||
}
|
||||
rows.sort((left, right) => right.session.createdAt.localeCompare(left.session.createdAt));
|
||||
return rows;
|
||||
}, [
|
||||
draftThreadsByThreadKey,
|
||||
draftsByThreadKey,
|
||||
frozenActive,
|
||||
props.routeDraftId,
|
||||
props.scopedProjectKeys,
|
||||
]);
|
||||
const handleDiscard = useCallback(
|
||||
(draftId: DraftId) => {
|
||||
// The /draft/$draftId route redirects home on its own when the draft
|
||||
// it renders disappears, so discarding the open draft needs no
|
||||
// special-casing here.
|
||||
clearDraftThread(draftId);
|
||||
},
|
||||
[clearDraftThread],
|
||||
);
|
||||
if (drafts.length === 0) {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
<>
|
||||
{drafts.map(({ composer, draftId, session }) => {
|
||||
const projectKey = `${session.environmentId}:${session.projectId}`;
|
||||
return (
|
||||
<SidebarDraftRow
|
||||
key={draftId}
|
||||
draftId={draftId}
|
||||
session={session}
|
||||
composer={composer}
|
||||
projectTitle={props.projectDisplayNameByKey.get(projectKey) ?? null}
|
||||
projectCwd={props.projectCwdByKey.get(projectKey) ?? null}
|
||||
isActive={draftId === props.routeDraftId}
|
||||
onNavigate={props.onNavigateToDraft}
|
||||
onDiscard={handleDiscard}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
<li
|
||||
aria-hidden
|
||||
data-testid="sidebar-draft-divider"
|
||||
className="mx-2.5 my-1.5 h-px list-none bg-sidebar-border/60"
|
||||
/>
|
||||
</>
|
||||
);
|
||||
});
|
||||
|
||||
const SidebarThreadRow = memo(function SidebarThreadRow(props: {
|
||||
thread: SidebarThreadSummary;
|
||||
variant: "card" | "slim";
|
||||
@@ -1554,6 +1783,32 @@ export default function Sidebar() {
|
||||
setProjectScopeKey(null);
|
||||
}
|
||||
}, [projectScopeKey, scopedProjectGroup]);
|
||||
// Count-only subscription: the parent needs "are there draft rows" for the
|
||||
// empty state, while SidebarDraftBlock owns the per-keystroke content
|
||||
// subscription. Selecting a number keeps typing in a draft composer from
|
||||
// re-rendering the whole sidebar. Approximates the block's row filter
|
||||
// (every non-promoted session with content); it can overcount by one for
|
||||
// an open never-left draft, which only softens the empty state.
|
||||
const routeDraftIdForRows = routeTarget?.kind === "draft" ? routeTarget.draftId : null;
|
||||
const visibleDraftSessionCount = useComposerDraftStore((store) => {
|
||||
let count = 0;
|
||||
for (const [draftKey, session] of Object.entries(store.draftThreadsByThreadKey)) {
|
||||
if (session.promotedTo != null) {
|
||||
continue;
|
||||
}
|
||||
if (!composerDraftHasUserContent(store.draftsByThreadKey[draftKey])) {
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
scopedProjectKeys !== null &&
|
||||
!scopedProjectKeys.has(`${session.environmentId}:${session.projectId}`)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
count += 1;
|
||||
}
|
||||
return count;
|
||||
});
|
||||
// Scope flips drop the selection: rows selected under the old scope may be
|
||||
// hidden now, and bulk actions must never count or touch invisible rows.
|
||||
useEffect(() => {
|
||||
@@ -1876,6 +2131,21 @@ export default function Sidebar() {
|
||||
[clearSelection, isMobile, router, setOpenMobile, setSelectionAnchor],
|
||||
);
|
||||
|
||||
const navigateToDraft = useCallback(
|
||||
(draftId: DraftId) => {
|
||||
// Unconditional: also drops a stale selection anchor left by
|
||||
// plain-click navigation, so a later shift-click starts fresh
|
||||
// instead of ranging from a row that is no longer the context.
|
||||
// (clearSelection no-ops when there is nothing to clear.)
|
||||
clearSelection();
|
||||
if (isMobile) {
|
||||
setOpenMobile(false);
|
||||
}
|
||||
void router.navigate({ to: "/draft/$draftId", params: { draftId } });
|
||||
},
|
||||
[clearSelection, isMobile, router, setOpenMobile],
|
||||
);
|
||||
|
||||
const clearThreadSearch = useCallback(() => {
|
||||
setThreadSearchQuery("");
|
||||
setActiveSearchResultIndex(0);
|
||||
@@ -3198,13 +3468,22 @@ export default function Sidebar() {
|
||||
/>
|
||||
);
|
||||
};
|
||||
// Pinned block: full cards above the inbox, closed by a
|
||||
// thin divider (the pin glyphs carry the meaning, so no
|
||||
// header text). Vanishes entirely at count 0.
|
||||
// Rows render in the one shared pinned order; only
|
||||
// Draft block above everything, then the pinned block:
|
||||
// full cards above the inbox, closed by a thin divider (the
|
||||
// pin glyphs carry the meaning, so no header text). Both
|
||||
// vanish entirely at count 0.
|
||||
// Pinned rows render in the one shared pinned order; only
|
||||
// reorder-capable rows register as sortable (legacy-server
|
||||
// pins render in place as plain rows).
|
||||
const items: ReactNode[] = [
|
||||
<SidebarDraftBlock
|
||||
key="draft-sessions"
|
||||
projectDisplayNameByKey={projectDisplayNameByKey}
|
||||
projectCwdByKey={projectCwdByKey}
|
||||
scopedProjectKeys={scopedProjectKeys}
|
||||
routeDraftId={routeDraftIdForRows}
|
||||
onNavigateToDraft={navigateToDraft}
|
||||
/>,
|
||||
<DndContext
|
||||
key="pinned-dnd"
|
||||
sensors={pinnedDndSensors}
|
||||
@@ -3340,6 +3619,7 @@ export default function Sidebar() {
|
||||
</TooltipProvider>
|
||||
) : null}
|
||||
{!isSearchingThreads &&
|
||||
visibleDraftSessionCount === 0 &&
|
||||
pinnedThreads.length +
|
||||
activeThreads.length +
|
||||
snoozedThreads.length +
|
||||
|
||||
@@ -836,10 +836,9 @@ describe("composerDraftStore project draft thread mapping", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("clears orphaned composer drafts when remapping a project to a new draft thread", () => {
|
||||
it("clears empty composer drafts when remapping a project to a new draft thread", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
store.setProjectDraftThreadId(projectRef, draftId, { threadId });
|
||||
store.setPrompt(draftId, "orphan me");
|
||||
|
||||
store.setProjectDraftThreadId(projectRef, otherDraftId, { threadId: otherThreadId });
|
||||
|
||||
@@ -850,6 +849,39 @@ describe("composerDraftStore project draft thread mapping", () => {
|
||||
expect(draftByKey(draftId)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("keeps invested composer drafts alive unmapped when remapping a project to a new draft thread", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
store.setProjectDraftThreadId(projectRef, draftId, { threadId });
|
||||
store.setPrompt(draftId, "keep me around");
|
||||
|
||||
store.setProjectDraftThreadId(projectRef, otherDraftId, { threadId: otherThreadId });
|
||||
|
||||
// The mapping moved to the fresh draft...
|
||||
expect(useComposerDraftStore.getState().getDraftThreadByProjectRef(projectRef)?.threadId).toBe(
|
||||
otherThreadId,
|
||||
);
|
||||
// ...but the invested draft survives with its content for the sidebar
|
||||
// draft rows to surface.
|
||||
expect(useComposerDraftStore.getState().getDraftThread(draftId)?.threadId).toBe(threadId);
|
||||
expect(draftByKey(draftId)?.prompt).toBe("keep me around");
|
||||
});
|
||||
|
||||
it("clears every session for a project, including unmapped invested drafts", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
store.setProjectDraftThreadId(projectRef, draftId, { threadId });
|
||||
store.setPrompt(draftId, "invested");
|
||||
// The remap leaves the invested draft alive unmapped; project removal
|
||||
// must still sweep it, or its sidebar row outlives the project.
|
||||
store.setProjectDraftThreadId(projectRef, otherDraftId, { threadId: otherThreadId });
|
||||
|
||||
store.clearProjectDraftThreadId(projectRef);
|
||||
|
||||
expect(useComposerDraftStore.getState().getDraftThreadByProjectRef(projectRef)).toBeNull();
|
||||
expect(useComposerDraftStore.getState().getDraftThread(draftId)).toBeNull();
|
||||
expect(useComposerDraftStore.getState().getDraftThread(otherDraftId)).toBeNull();
|
||||
expect(draftByKey(draftId)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("keeps composer drafts when the thread is still mapped by another project", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
store.setProjectDraftThreadId(projectRef, draftId, { threadId });
|
||||
|
||||
@@ -277,6 +277,31 @@ export interface ComposerThreadDraftState {
|
||||
interactionMode: ProviderInteractionMode | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* True when the user has invested real content in the draft: typed text or
|
||||
* any attachment/context. Model selection and mode choices alone do not
|
||||
* count — those are ambient defaults, not work in progress. Used by the
|
||||
* sidebar draft rows (which draft sessions deserve a row) and by new-thread
|
||||
* resurrection (a draft with content keeps its settings instead of being
|
||||
* reset to defaults).
|
||||
*/
|
||||
export function composerDraftHasUserContent(
|
||||
draft: ComposerThreadDraftState | null | undefined,
|
||||
): boolean {
|
||||
if (!draft) {
|
||||
return false;
|
||||
}
|
||||
return (
|
||||
draft.prompt.trim().length > 0 ||
|
||||
draft.images.length > 0 ||
|
||||
draft.persistedAttachments.length > 0 ||
|
||||
draft.terminalContexts.length > 0 ||
|
||||
draft.elementContexts.length > 0 ||
|
||||
draft.previewAnnotations.length > 0 ||
|
||||
draft.reviewComments.length > 0
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Mutable routing and execution context for a pre-thread draft session.
|
||||
*
|
||||
@@ -1831,6 +1856,24 @@ function migratePersistedComposerDraftStoreState(
|
||||
function partializeComposerDraftStoreState(
|
||||
state: ComposerDraftStoreState,
|
||||
): PersistedComposerDraftStoreState {
|
||||
// Draft sessions worth persisting: mapped (a new-thread flow targets
|
||||
// them), promoting (mid-send), or holding real user content (they back a
|
||||
// sidebar row). Everything else is a zombie — and its composer blob must
|
||||
// be dropped WITH it, or model/mode-only entries would persist forever
|
||||
// keyed to a session that no longer exists.
|
||||
const mappedDraftKeys = new Set(
|
||||
Object.values(state.logicalProjectDraftThreadKeyByLogicalProjectKey),
|
||||
);
|
||||
const keptSessionKeys = new Set(
|
||||
Object.entries(state.draftThreadsByThreadKey)
|
||||
.filter(
|
||||
([threadKey, draftThread]) =>
|
||||
mappedDraftKeys.has(threadKey) ||
|
||||
isDraftThreadPromoting(draftThread) ||
|
||||
composerDraftHasUserContent(state.draftsByThreadKey[threadKey]),
|
||||
)
|
||||
.map(([threadKey]) => threadKey),
|
||||
);
|
||||
const persistedDraftsByThreadKey: DeepMutable<
|
||||
PersistedComposerDraftStoreState["draftsByThreadKey"]
|
||||
> = {};
|
||||
@@ -1838,6 +1881,11 @@ function partializeComposerDraftStoreState(
|
||||
if (typeof threadKey !== "string" || threadKey.length === 0) {
|
||||
continue;
|
||||
}
|
||||
// Composer content keyed to a dropped draft session goes with it.
|
||||
// Server-thread keys have no session entry and are unaffected.
|
||||
if (state.draftThreadsByThreadKey[threadKey] !== undefined && !keptSessionKeys.has(threadKey)) {
|
||||
continue;
|
||||
}
|
||||
const hasModelData =
|
||||
Object.keys(draft.modelSelectionByProvider).length > 0 || draft.activeProvider !== null;
|
||||
if (
|
||||
@@ -1911,9 +1959,18 @@ function partializeComposerDraftStoreState(
|
||||
};
|
||||
persistedDraftsByThreadKey[threadKey] = persistedDraft;
|
||||
}
|
||||
const persistedDraftThreadsByThreadKey: DeepMutable<
|
||||
PersistedComposerDraftStoreState["draftThreadsByThreadKey"]
|
||||
> = {};
|
||||
for (const [threadKey, draftThread] of Object.entries(state.draftThreadsByThreadKey)) {
|
||||
if (!keptSessionKeys.has(threadKey)) {
|
||||
continue;
|
||||
}
|
||||
persistedDraftThreadsByThreadKey[threadKey] = draftThread;
|
||||
}
|
||||
return {
|
||||
draftsByThreadKey: persistedDraftsByThreadKey,
|
||||
draftThreadsByThreadKey: state.draftThreadsByThreadKey,
|
||||
draftThreadsByThreadKey: persistedDraftThreadsByThreadKey,
|
||||
logicalProjectDraftThreadKeyByLogicalProjectKey:
|
||||
state.logicalProjectDraftThreadKeyByLogicalProjectKey,
|
||||
stickyModelSelectionByProvider: compactModelSelectionByProvider(
|
||||
@@ -2214,7 +2271,25 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
|
||||
return get().getDraftSessionByProjectRef(projectRef);
|
||||
},
|
||||
getDraftSessionByProjectRef: (projectRef) => {
|
||||
for (const [draftId, draftThread] of Object.entries(get().draftThreadsByThreadKey)) {
|
||||
const state = get();
|
||||
// Mapped drafts win: a project can also own older unmapped drafts
|
||||
// (invested ones left behind by a remap), but "the" draft for a
|
||||
// project is the one new-thread flows currently target.
|
||||
for (const draftId of Object.values(
|
||||
state.logicalProjectDraftThreadKeyByLogicalProjectKey,
|
||||
)) {
|
||||
const draftThread = state.draftThreadsByThreadKey[draftId];
|
||||
if (!draftThread || isDraftThreadPromoting(draftThread)) {
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
draftThread.projectId === projectRef.projectId &&
|
||||
draftThread.environmentId === projectRef.environmentId
|
||||
) {
|
||||
return toProjectDraftSession(DraftId.make(draftId), draftThread);
|
||||
}
|
||||
}
|
||||
for (const [draftId, draftThread] of Object.entries(state.draftThreadsByThreadKey)) {
|
||||
if (isDraftThreadPromoting(draftThread)) {
|
||||
continue;
|
||||
}
|
||||
@@ -2289,6 +2364,11 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
|
||||
previousThreadKeyForLogicalProject === undefined
|
||||
? undefined
|
||||
: nextDraftThreadsByThreadKey[previousThreadKeyForLogicalProject];
|
||||
// A remap only garbage-collects the previous draft when the user
|
||||
// never invested content in it. A draft with typed text or
|
||||
// attachments stays alive unmapped — the sidebar draft rows list
|
||||
// every such session, so "new thread" can mint a fresh draft
|
||||
// without destroying the one the user walked away from.
|
||||
if (
|
||||
previousThreadKeyForLogicalProject &&
|
||||
previousThreadKeyForLogicalProject !== draftId &&
|
||||
@@ -2296,7 +2376,10 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
|
||||
nextLogicalProjectDraftThreadKeyByLogicalProjectKey,
|
||||
previousThreadKeyForLogicalProject,
|
||||
) &&
|
||||
!isDraftThreadPromoting(previousDraftThread)
|
||||
!isDraftThreadPromoting(previousDraftThread) &&
|
||||
!composerDraftHasUserContent(
|
||||
state.draftsByThreadKey[previousThreadKeyForLogicalProject],
|
||||
)
|
||||
) {
|
||||
delete nextDraftThreadsByThreadKey[previousThreadKeyForLogicalProject];
|
||||
if (state.draftsByThreadKey[previousThreadKeyForLogicalProject] !== undefined) {
|
||||
@@ -2405,15 +2488,30 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
|
||||
},
|
||||
clearProjectDraftThreadId: (projectRef) => {
|
||||
set((state) => {
|
||||
const matchingThreadEntry = Object.entries(state.draftThreadsByThreadKey).find(
|
||||
([, draftThread]) =>
|
||||
draftThread.projectId === projectRef.projectId &&
|
||||
draftThread.environmentId === projectRef.environmentId,
|
||||
);
|
||||
if (!matchingThreadEntry) {
|
||||
// A project can own several sessions (invested drafts survive
|
||||
// remaps unmapped), so project removal must sweep them all — a
|
||||
// leftover would render a sidebar row for a project that no
|
||||
// longer exists.
|
||||
const matchingThreadKeys = Object.entries(state.draftThreadsByThreadKey)
|
||||
.filter(
|
||||
([, draftThread]) =>
|
||||
draftThread.projectId === projectRef.projectId &&
|
||||
draftThread.environmentId === projectRef.environmentId,
|
||||
)
|
||||
.map(([threadKey]) => threadKey);
|
||||
if (matchingThreadKeys.length === 0) {
|
||||
return state;
|
||||
}
|
||||
return removeDraftThreadReferences(state, matchingThreadEntry[0]);
|
||||
let nextState = {
|
||||
draftsByThreadKey: state.draftsByThreadKey,
|
||||
draftThreadsByThreadKey: state.draftThreadsByThreadKey,
|
||||
logicalProjectDraftThreadKeyByLogicalProjectKey:
|
||||
state.logicalProjectDraftThreadKeyByLogicalProjectKey,
|
||||
};
|
||||
for (const threadKey of matchingThreadKeys) {
|
||||
nextState = removeDraftThreadReferences(nextState, threadKey);
|
||||
}
|
||||
return nextState;
|
||||
});
|
||||
},
|
||||
clearProjectDraftThreadById: (projectRef, threadRef) => {
|
||||
|
||||
@@ -8,6 +8,7 @@ import { DEFAULT_RUNTIME_MODE, type ScopedProjectRef } from "@t3tools/contracts"
|
||||
import { useParams, useRouter } from "@tanstack/react-router";
|
||||
import { useCallback, useMemo } from "react";
|
||||
import {
|
||||
composerDraftHasUserContent,
|
||||
markPromotedDraftThreadByRef,
|
||||
type DraftThreadEnvMode,
|
||||
type DraftThreadState,
|
||||
@@ -160,48 +161,66 @@ export function useNewThreadHandler() {
|
||||
if (storedDraftThreadRef && reusableStoredDraftThread === null) {
|
||||
markPromotedDraftThreadByRef(storedDraftThreadRef);
|
||||
}
|
||||
// New-thread surfaces (button, hotkeys, "/" landing, palette) only
|
||||
// ever reuse a draft the user has NOT invested in. A draft with typed
|
||||
// text or attachments is work in progress: it stays alive where it is
|
||||
// (reachable from the sidebar draft rows) and this request mints a
|
||||
// fresh draft instead — the remap in the store preserves invested
|
||||
// drafts rather than deleting them.
|
||||
const emptyStoredDraftThread =
|
||||
reusableStoredDraftThread &&
|
||||
!composerDraftHasUserContent(getComposerDraft(reusableStoredDraftThread.draftId))
|
||||
? reusableStoredDraftThread
|
||||
: null;
|
||||
const latestActiveDraftThread: DraftThreadState | null = currentRouteTarget
|
||||
? currentRouteTarget.kind === "server"
|
||||
? getDraftThread(currentRouteTarget.threadRef)
|
||||
: getDraftSession(currentRouteTarget.draftId)
|
||||
: null;
|
||||
if (reusableStoredDraftThread) {
|
||||
if (emptyStoredDraftThread) {
|
||||
return (async () => {
|
||||
const isDraftAlreadyOpen =
|
||||
currentRouteTarget?.kind === "draft" &&
|
||||
currentRouteTarget.draftId === reusableStoredDraftThread.draftId;
|
||||
currentRouteTarget.draftId === emptyStoredDraftThread.draftId;
|
||||
const hasExplicitWorkspaceOption =
|
||||
hasBranchOption ||
|
||||
hasWorktreePathOption ||
|
||||
hasEnvModeOption ||
|
||||
hasStartFromOriginOption;
|
||||
// Resurrecting a stored draft must not resurrect its stale context:
|
||||
// explicit workspace options win outright; otherwise the env context
|
||||
// resets to the configured defaults so drafts seeded before a
|
||||
// defaults change (or by the old carry-over behavior) stop landing
|
||||
// on "current checkout" branches forever. Composer text is
|
||||
// preserved. When the draft is already open and no options were
|
||||
// passed, leave it alone entirely — the user may have just picked a
|
||||
// branch in the composer.
|
||||
// Resurrecting an empty stored draft must not resurrect its stale
|
||||
// context: explicit workspace options win outright; otherwise the
|
||||
// env context resets to the configured defaults so drafts seeded
|
||||
// before a defaults change (or by the old carry-over behavior) stop
|
||||
// landing on "current checkout" branches forever. When the draft is
|
||||
// already open and no options were passed, leave it alone entirely —
|
||||
// the user may have just picked a branch in the composer.
|
||||
let workspaceContext: NewThreadWorkspaceOptions | null = null;
|
||||
if (hasExplicitWorkspaceOption) {
|
||||
workspaceContext = pickExplicitWorkspaceOptions(options);
|
||||
} else if (!isDraftAlreadyOpen) {
|
||||
const defaultEnvMode = await resolveDefaultEnvMode();
|
||||
// The await yields. If the draft was opened (a concurrent
|
||||
// invocation's navigation landed) or promoted to a real thread
|
||||
// in the meantime, this invocation is a stale loser: resetting
|
||||
// context, remapping (which wipes branch/worktree on a member
|
||||
// change), or navigating would all clobber state written after
|
||||
// the snapshot above. Bail out entirely — the winner already
|
||||
// did this work.
|
||||
// invocation's navigation landed), promoted to a real thread,
|
||||
// remapped away (a concurrent invocation registered a fresh
|
||||
// draft — remapping back would evict the winner and let the
|
||||
// store GC it), or gained content (no longer a reusable empty
|
||||
// draft) in the meantime, this invocation is a stale loser:
|
||||
// resetting context, remapping, or navigating would all clobber
|
||||
// state written after the snapshot above. Bail out entirely —
|
||||
// the winner already did this work.
|
||||
const routeTargetNow = getCurrentRouteTarget();
|
||||
const openedMeanwhile =
|
||||
routeTargetNow?.kind === "draft" &&
|
||||
routeTargetNow.draftId === reusableStoredDraftThread.draftId;
|
||||
routeTargetNow.draftId === emptyStoredDraftThread.draftId;
|
||||
const promotedMeanwhile =
|
||||
storedDraftThreadRef !== null && readThreadShell(storedDraftThreadRef) !== null;
|
||||
if (openedMeanwhile || promotedMeanwhile) {
|
||||
const remappedMeanwhile =
|
||||
getDraftSessionByLogicalProjectKey(logicalProjectKey)?.draftId !==
|
||||
emptyStoredDraftThread.draftId;
|
||||
const investedMeanwhile = composerDraftHasUserContent(
|
||||
getComposerDraft(emptyStoredDraftThread.draftId),
|
||||
);
|
||||
if (openedMeanwhile || promotedMeanwhile || remappedMeanwhile || investedMeanwhile) {
|
||||
return;
|
||||
}
|
||||
workspaceContext = {
|
||||
@@ -215,7 +234,7 @@ export function useNewThreadHandler() {
|
||||
};
|
||||
}
|
||||
if (workspaceContext) {
|
||||
setDraftThreadContext(reusableStoredDraftThread.draftId, {
|
||||
setDraftThreadContext(emptyStoredDraftThread.draftId, {
|
||||
...workspaceContext,
|
||||
...(carryRuntimeMode ? { runtimeMode: carryRuntimeMode } : {}),
|
||||
...(carryInteractionMode ? { interactionMode: carryInteractionMode } : {}),
|
||||
@@ -224,7 +243,7 @@ export function useNewThreadHandler() {
|
||||
// The carried selection is a complete snapshot of the viewed
|
||||
// thread's model state: absent options mean "no options", not
|
||||
// "keep the stale draft's options".
|
||||
setModelSelection(reusableStoredDraftThread.draftId, carryModelSelection, {
|
||||
setModelSelection(emptyStoredDraftThread.draftId, carryModelSelection, {
|
||||
replaceOptions: true,
|
||||
});
|
||||
}
|
||||
@@ -236,9 +255,9 @@ export function useNewThreadHandler() {
|
||||
setLogicalProjectDraftThreadId(
|
||||
logicalProjectKey,
|
||||
projectRef,
|
||||
reusableStoredDraftThread.draftId,
|
||||
emptyStoredDraftThread.draftId,
|
||||
{
|
||||
threadId: reusableStoredDraftThread.threadId,
|
||||
threadId: emptyStoredDraftThread.threadId,
|
||||
...workspaceContext,
|
||||
...(carryRuntimeMode ? { runtimeMode: carryRuntimeMode } : {}),
|
||||
...(carryInteractionMode ? { interactionMode: carryInteractionMode } : {}),
|
||||
@@ -250,13 +269,13 @@ export function useNewThreadHandler() {
|
||||
const routeTargetAfterWrites = getCurrentRouteTarget();
|
||||
if (
|
||||
routeTargetAfterWrites?.kind === "draft" &&
|
||||
routeTargetAfterWrites.draftId === reusableStoredDraftThread.draftId
|
||||
routeTargetAfterWrites.draftId === emptyStoredDraftThread.draftId
|
||||
) {
|
||||
return;
|
||||
}
|
||||
await router.navigate({
|
||||
to: "/draft/$draftId",
|
||||
params: { draftId: reusableStoredDraftThread.draftId },
|
||||
params: { draftId: emptyStoredDraftThread.draftId },
|
||||
replace: options?.replace ?? false,
|
||||
});
|
||||
})();
|
||||
@@ -266,7 +285,10 @@ export function useNewThreadHandler() {
|
||||
latestActiveDraftThread &&
|
||||
currentRouteTarget?.kind === "draft" &&
|
||||
latestActiveDraftThread.logicalProjectKey === logicalProjectKey &&
|
||||
latestActiveDraftThread.promotedTo == null
|
||||
latestActiveDraftThread.promotedTo == null &&
|
||||
// Same content rule as above: a new-thread request while viewing an
|
||||
// invested draft mints a fresh one instead of repurposing it.
|
||||
!composerDraftHasUserContent(getComposerDraft(currentRouteTarget.draftId))
|
||||
) {
|
||||
if (
|
||||
hasBranchOption ||
|
||||
@@ -298,6 +320,11 @@ export function useNewThreadHandler() {
|
||||
const racedDraft = getDraftSessionByLogicalProjectKey(logicalProjectKey);
|
||||
if (
|
||||
racedDraft &&
|
||||
// Only a draft REGISTERED during the await counts as a raced
|
||||
// winner. An invested draft this invocation deliberately declined
|
||||
// to reuse is still mapped at this point — reusing it here would
|
||||
// silently undo mint-fresh semantics.
|
||||
racedDraft.draftId !== storedDraftThread?.draftId &&
|
||||
readThreadShell(scopeThreadRef(racedDraft.environmentId, racedDraft.threadId)) === null
|
||||
) {
|
||||
// Same remap the reuse paths above perform: point the draft at the
|
||||
|
||||
Reference in new issue
Block a user