4195 lines
162 KiB
TypeScript
4195 lines
162 KiB
TypeScript
import {
|
|
DEFAULT_MODEL,
|
|
DEFAULT_MODEL_BY_PROVIDER,
|
|
defaultInstanceIdForDriver,
|
|
EnvironmentId,
|
|
ModelSelection,
|
|
ProjectId,
|
|
ProviderInstanceId,
|
|
ProviderInteractionMode,
|
|
ProviderDriverKind,
|
|
ProviderOptionSelection,
|
|
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
|
|
PreviewAnnotationPayloadSchema,
|
|
type PreviewAnnotationPayload,
|
|
RuntimeMode,
|
|
type ServerProvider,
|
|
type ScopedProjectRef,
|
|
type ScopedThreadRef,
|
|
ThreadId,
|
|
} from "@t3tools/contracts";
|
|
import {
|
|
parseScopedProjectKey,
|
|
parseScopedThreadKey,
|
|
scopedProjectKey,
|
|
scopeProjectRef,
|
|
scopedThreadKey,
|
|
scopeThreadRef,
|
|
} from "@t3tools/client-runtime/environment";
|
|
import * as Schema from "effect/Schema";
|
|
import * as Equal from "effect/Equal";
|
|
import * as Effect from "effect/Effect";
|
|
import { DeepMutable } from "effect/Types";
|
|
import { createModelSelection, normalizeModelSlug } from "@t3tools/shared/model";
|
|
import { useMemo } from "react";
|
|
import { getLocalStorageItem } from "./hooks/useLocalStorage";
|
|
import { resolveAppModelSelection, resolveAppModelSelectionForInstance } from "./modelSelection";
|
|
import {
|
|
DEFAULT_INTERACTION_MODE,
|
|
DEFAULT_RUNTIME_MODE,
|
|
type ChatFileAttachment,
|
|
type ChatImageAttachment,
|
|
videoMimeType,
|
|
} from "./types";
|
|
import {
|
|
type TerminalContextDraft,
|
|
ensureInlineTerminalContextPlaceholders,
|
|
normalizeTerminalContextText,
|
|
} from "./lib/terminalContext";
|
|
import {
|
|
type ElementContextDraft,
|
|
type ElementContextSelection,
|
|
elementContextDedupKey,
|
|
newElementContextId,
|
|
} from "./lib/elementContext";
|
|
import { create } from "zustand";
|
|
import { persist, type PersistStorage, type StorageValue } from "zustand/middleware";
|
|
import { useShallow } from "zustand/react/shallow";
|
|
import { createDeferredStorage, createMemoryStorage } from "./lib/storage";
|
|
import { getDefaultServerModel } from "./providerModels";
|
|
import { UnifiedSettings } from "@t3tools/contracts/settings";
|
|
import { ReviewCommentContextSchema, type ReviewCommentContext } from "./reviewCommentContext";
|
|
const isRuntimeMode = Schema.is(RuntimeMode);
|
|
const isProviderDriverKind = Schema.is(ProviderDriverKind);
|
|
const isReviewCommentContext = Schema.is(ReviewCommentContextSchema);
|
|
|
|
export const COMPOSER_DRAFT_STORAGE_KEY = "t3code:composer-drafts:v1";
|
|
const COMPOSER_DRAFT_STORAGE_VERSION = 9;
|
|
const DraftThreadEnvModeSchema = Schema.Literals(["local", "worktree"]);
|
|
export type DraftThreadEnvMode = typeof DraftThreadEnvModeSchema.Type;
|
|
|
|
export const DraftId = Schema.String.pipe(Schema.brand("DraftId"));
|
|
export type DraftId = typeof DraftId.Type;
|
|
|
|
const COMPOSER_PERSIST_DEBOUNCE_MS = 300;
|
|
|
|
// Keep the immutable state until flush. Migration writebacks already have the persisted shape.
|
|
type ComposerPersistState =
|
|
| { capturedState: ComposerDraftStoreState }
|
|
| PersistedComposerDraftStoreState;
|
|
|
|
const composerDebouncedStorage = createDeferredStorage<StorageValue<ComposerPersistState>>(
|
|
typeof localStorage !== "undefined" ? localStorage : createMemoryStorage(),
|
|
(value) =>
|
|
JSON.stringify({
|
|
state:
|
|
"capturedState" in value.state
|
|
? partializeComposerDraftStoreState(value.state.capturedState)
|
|
: value.state,
|
|
version: value.version,
|
|
}),
|
|
COMPOSER_PERSIST_DEBOUNCE_MS,
|
|
);
|
|
|
|
const composerPersistStorage: PersistStorage<ComposerPersistState> = {
|
|
getItem: (name) => {
|
|
// The base storage is localStorage (or in-memory), which is synchronous.
|
|
const raw = composerDebouncedStorage.getItem(name);
|
|
if (typeof raw !== "string") {
|
|
return null;
|
|
}
|
|
// Parsed persisted JSON. `migrate` and `merge` normalize it from unknown,
|
|
// so the cast mirrors the one zustand's createJSONStorage performs.
|
|
return JSON.parse(raw) as StorageValue<ComposerPersistState>;
|
|
},
|
|
setItem: (name, value) => composerDebouncedStorage.setItem(name, value),
|
|
removeItem: (name) => composerDebouncedStorage.removeItem(name),
|
|
};
|
|
|
|
// Flush pending composer draft writes before page unload to prevent data loss.
|
|
if (typeof window !== "undefined" && typeof window.addEventListener === "function") {
|
|
window.addEventListener("beforeunload", () => {
|
|
composerDebouncedStorage.flush();
|
|
});
|
|
}
|
|
|
|
export const PersistedComposerImageAttachment = Schema.Struct({
|
|
id: Schema.String,
|
|
name: Schema.String,
|
|
mimeType: Schema.String,
|
|
sizeBytes: Schema.Number,
|
|
dataUrl: Schema.String,
|
|
});
|
|
export type PersistedComposerImageAttachment = typeof PersistedComposerImageAttachment.Type;
|
|
|
|
export interface ComposerImageAttachment extends Omit<ChatImageAttachment, "previewUrl"> {
|
|
previewUrl: string;
|
|
file: File;
|
|
}
|
|
|
|
export interface ComposerFileAttachment extends Omit<ChatFileAttachment, "previewUrl"> {
|
|
file: File | null;
|
|
uploadedAttachmentId?: string;
|
|
uploadEnvironmentId?: EnvironmentId;
|
|
}
|
|
|
|
/**
|
|
* A hydrated draft file whose upload never finished before the reload has
|
|
* neither bytes (`file` is only ever null after hydration) nor a server-side
|
|
* upload. The composer renders it as a needs-reattach row: the user must
|
|
* attach the file again or remove it before sending.
|
|
*/
|
|
export function composerFileNeedsReattach(file: ComposerFileAttachment): boolean {
|
|
return file.file === null && file.uploadedAttachmentId === undefined;
|
|
}
|
|
|
|
function clearStaleFileUploadMetadata(
|
|
draft: ComposerThreadDraftState,
|
|
environmentId: EnvironmentId,
|
|
): ComposerThreadDraftState {
|
|
let changed = false;
|
|
const files = draft.files.map((file) => {
|
|
if (
|
|
(file.uploadedAttachmentId === undefined && file.uploadEnvironmentId === undefined) ||
|
|
file.uploadEnvironmentId === environmentId
|
|
) {
|
|
return file;
|
|
}
|
|
|
|
changed = true;
|
|
const nextFile = { ...file };
|
|
delete nextFile.uploadedAttachmentId;
|
|
delete nextFile.uploadEnvironmentId;
|
|
return nextFile;
|
|
});
|
|
|
|
return changed ? { ...draft, files } : draft;
|
|
}
|
|
|
|
export const PersistedComposerFileAttachment = Schema.Struct({
|
|
id: Schema.String,
|
|
name: Schema.String,
|
|
mimeType: Schema.String,
|
|
sizeBytes: Schema.Number,
|
|
attachmentId: Schema.String,
|
|
environmentId: EnvironmentId,
|
|
});
|
|
export type PersistedComposerFileAttachment = typeof PersistedComposerFileAttachment.Type;
|
|
|
|
/**
|
|
* Draft-persisted file. Unlike a stash entry (which requires a finished
|
|
* upload), a draft may hold a file whose upload never completed. Its `File`
|
|
* handle cannot serialize, so it persists as a metadata-only marker (no
|
|
* `attachmentId`) and hydrates as a needs-reattach row instead of vanishing.
|
|
*/
|
|
export const PersistedComposerDraftFileAttachment = Schema.Struct({
|
|
id: Schema.String,
|
|
name: Schema.String,
|
|
mimeType: Schema.String,
|
|
sizeBytes: Schema.Number,
|
|
attachmentId: Schema.optionalKey(Schema.String),
|
|
environmentId: Schema.optionalKey(EnvironmentId),
|
|
});
|
|
export type PersistedComposerDraftFileAttachment = typeof PersistedComposerDraftFileAttachment.Type;
|
|
const isPersistedComposerDraftFileAttachment = Schema.is(PersistedComposerDraftFileAttachment);
|
|
|
|
const PersistedTerminalContextDraft = Schema.Struct({
|
|
id: Schema.String,
|
|
threadId: ThreadId,
|
|
createdAt: Schema.String,
|
|
terminalId: Schema.String,
|
|
terminalLabel: Schema.String,
|
|
lineStart: Schema.Number,
|
|
lineEnd: Schema.Number,
|
|
});
|
|
type PersistedTerminalContextDraft = typeof PersistedTerminalContextDraft.Type;
|
|
|
|
const PersistedElementContextStackFrame = Schema.Struct({
|
|
functionName: Schema.NullOr(Schema.String),
|
|
fileName: Schema.NullOr(Schema.String),
|
|
lineNumber: Schema.NullOr(Schema.Number),
|
|
columnNumber: Schema.NullOr(Schema.Number),
|
|
});
|
|
|
|
const PersistedElementContextDraft = Schema.Struct({
|
|
id: Schema.String,
|
|
threadId: ThreadId,
|
|
pickedAt: Schema.String,
|
|
pageUrl: Schema.String,
|
|
pageTitle: Schema.NullOr(Schema.String),
|
|
tagName: Schema.String,
|
|
selector: Schema.NullOr(Schema.String),
|
|
htmlPreview: Schema.String,
|
|
componentName: Schema.NullOr(Schema.String),
|
|
source: Schema.NullOr(PersistedElementContextStackFrame),
|
|
styles: Schema.String,
|
|
});
|
|
type PersistedElementContextDraft = typeof PersistedElementContextDraft.Type;
|
|
|
|
const PersistedComposerThreadDraftState = Schema.Struct({
|
|
prompt: Schema.String,
|
|
attachments: Schema.Array(PersistedComposerImageAttachment),
|
|
files: Schema.optionalKey(Schema.Array(PersistedComposerDraftFileAttachment)),
|
|
terminalContexts: Schema.optionalKey(Schema.Array(PersistedTerminalContextDraft)),
|
|
elementContexts: Schema.optionalKey(Schema.Array(PersistedElementContextDraft)),
|
|
previewAnnotations: Schema.optionalKey(Schema.Array(PreviewAnnotationPayloadSchema)),
|
|
reviewComments: Schema.optionalKey(Schema.Array(ReviewCommentContextSchema)),
|
|
// Keyed by `ProviderInstanceId` (open branded slug) so custom provider
|
|
// instances (e.g. `codex_personal`) round-trip alongside the built-in
|
|
// `codex` / `claudeAgent` / ... entries. Every prior `ProviderDriverKind`
|
|
// literal satisfies the `ProviderInstanceId` slug pattern, so existing
|
|
// persisted drafts decode unchanged.
|
|
//
|
|
// The record's value schema is NOT wrapped in `Schema.optionalKey`:
|
|
// that helper is only meaningful on property signatures with a known
|
|
// key set, and `Schema.Record(<branded string>, …)` produces an index
|
|
// signature at runtime (Schema rejects the combination). Absence of
|
|
// an entry already encodes "no selection for this instance".
|
|
modelSelectionByProvider: Schema.optionalKey(Schema.Record(ProviderInstanceId, ModelSelection)),
|
|
activeProvider: Schema.optionalKey(Schema.NullOr(ProviderInstanceId)),
|
|
// True only when a human picked this selection in the composer. Seeded
|
|
// selections (project default / sticky) leave it unset so later seeds can
|
|
// replace them; legacy entries predate the flag and read as seeded too.
|
|
modelSelectionExplicit: Schema.optionalKey(Schema.Boolean),
|
|
runtimeMode: Schema.optionalKey(RuntimeMode),
|
|
interactionMode: Schema.optionalKey(ProviderInteractionMode),
|
|
});
|
|
type PersistedComposerThreadDraftState = typeof PersistedComposerThreadDraftState.Type;
|
|
|
|
/**
|
|
* Per-provider record of generic option selections. Used as a transient
|
|
* representation when migrating legacy v2 storage payloads and when
|
|
* deriving per-provider option bundles for downstream consumers.
|
|
*/
|
|
type ProviderOptionSelectionsByProvider = Partial<
|
|
Record<string, ReadonlyArray<ProviderOptionSelection>>
|
|
>;
|
|
|
|
type LegacyCodexFields = {
|
|
effort?: unknown;
|
|
codexFastMode?: unknown;
|
|
serviceTier?: unknown;
|
|
};
|
|
|
|
type LegacyThreadModelFields = {
|
|
provider?: unknown;
|
|
model?: unknown;
|
|
modelOptions?: unknown;
|
|
};
|
|
|
|
type LegacyV2ThreadDraftFields = {
|
|
modelSelection?: ModelSelection | null;
|
|
modelOptions?: unknown;
|
|
};
|
|
|
|
type LegacyPersistedComposerThreadDraftState = PersistedComposerThreadDraftState &
|
|
LegacyCodexFields &
|
|
LegacyThreadModelFields &
|
|
LegacyV2ThreadDraftFields;
|
|
|
|
type LegacyStickyModelFields = {
|
|
stickyProvider?: unknown;
|
|
stickyModel?: unknown;
|
|
stickyModelOptions?: unknown;
|
|
};
|
|
|
|
type LegacyV2StoreFields = {
|
|
stickyModelSelection?: ModelSelection | null;
|
|
stickyModelOptions?: unknown;
|
|
projectDraftThreadIdByProjectId?: Record<string, string> | null;
|
|
draftsByThreadId?: Record<string, PersistedComposerThreadDraftState> | null;
|
|
draftThreadsByThreadId?: Record<string, PersistedDraftThreadState> | null;
|
|
projectDraftThreadIdByProjectKey?: Record<string, string> | null;
|
|
draftsByThreadKey?: Record<string, PersistedComposerThreadDraftState> | null;
|
|
draftThreadsByThreadKey?: Record<string, PersistedDraftThreadState> | null;
|
|
projectDraftThreadKeyByProjectKey?: Record<string, string> | null;
|
|
logicalProjectDraftThreadKeyByLogicalProjectKey?: Record<string, string> | null;
|
|
};
|
|
|
|
type LegacyPersistedComposerDraftStoreState = PersistedComposerDraftStoreState &
|
|
LegacyStickyModelFields &
|
|
LegacyV2StoreFields;
|
|
|
|
const PersistedDraftThreadState = Schema.Struct({
|
|
threadId: ThreadId,
|
|
environmentId: Schema.String,
|
|
projectId: ProjectId,
|
|
logicalProjectKey: Schema.optionalKey(Schema.String),
|
|
environmentSelection: Schema.optionalKey(Schema.Literals(["auto", "manual"])),
|
|
loadBalancedEnvironmentId: Schema.optionalKey(Schema.NullOr(Schema.String)),
|
|
createdAt: Schema.String,
|
|
runtimeMode: RuntimeMode,
|
|
interactionMode: ProviderInteractionMode,
|
|
branch: Schema.NullOr(Schema.String),
|
|
worktreePath: Schema.NullOr(Schema.String),
|
|
envMode: DraftThreadEnvModeSchema,
|
|
startFromOrigin: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
|
|
promotedTo: Schema.optionalKey(
|
|
Schema.NullOr(
|
|
Schema.Struct({
|
|
environmentId: Schema.String,
|
|
threadId: Schema.String,
|
|
}),
|
|
),
|
|
),
|
|
});
|
|
type PersistedDraftThreadState = typeof PersistedDraftThreadState.Type;
|
|
|
|
const PersistedComposerDraftStoreState = Schema.Struct({
|
|
draftsByThreadKey: Schema.Record(Schema.String, PersistedComposerThreadDraftState),
|
|
draftThreadsByThreadKey: Schema.Record(Schema.String, PersistedDraftThreadState),
|
|
logicalProjectDraftThreadKeyByLogicalProjectKey: Schema.Record(Schema.String, Schema.String),
|
|
stickyModelSelectionByProvider: Schema.optionalKey(
|
|
Schema.Record(ProviderInstanceId, ModelSelection),
|
|
),
|
|
stickyActiveProvider: Schema.optionalKey(Schema.NullOr(ProviderInstanceId)),
|
|
});
|
|
type PersistedComposerDraftStoreState = typeof PersistedComposerDraftStoreState.Type;
|
|
|
|
const PersistedComposerDraftStoreStorage = Schema.Struct({
|
|
version: Schema.Number,
|
|
state: PersistedComposerDraftStoreState,
|
|
});
|
|
|
|
/**
|
|
* Composer content keyed by either a draft session (`DraftId`) or a real server
|
|
* thread (`ScopedThreadRef`). This is the editable payload shown in the composer.
|
|
*/
|
|
export interface ComposerThreadDraftState {
|
|
prompt: string;
|
|
images: ComposerImageAttachment[];
|
|
files: ComposerFileAttachment[];
|
|
nonPersistedImageIds: string[];
|
|
persistedAttachments: PersistedComposerImageAttachment[];
|
|
terminalContexts: TerminalContextDraft[];
|
|
/**
|
|
* Element-pick attachments captured from the in-app preview browser. The
|
|
* full payload (selector / html / styles / source frame) is persisted
|
|
* inline because — unlike terminal contexts — there's no live session to
|
|
* re-derive the snapshot from on reload.
|
|
*/
|
|
elementContexts: ElementContextDraft[];
|
|
previewAnnotations: PreviewAnnotationPayload[];
|
|
reviewComments: ReviewCommentContext[];
|
|
/**
|
|
* Per-instance model selection. Keyed by `ProviderInstanceId` (open
|
|
* branded slug) so a default `codex` instance and a user-authored
|
|
* `codex_personal` instance each persist their own selected model. Every
|
|
* historical `ProviderDriverKind` literal (`codex` / `claudeAgent` / `cursor` /
|
|
* `opencode`) also satisfies the `ProviderInstanceId` slug pattern, so
|
|
* legacy kind-keyed drafts round-trip unchanged.
|
|
*/
|
|
modelSelectionByProvider: Partial<Record<ProviderInstanceId, ModelSelection>>;
|
|
/** Routing key of the last picked instance (see `modelSelectionByProvider`). */
|
|
activeProvider: ProviderInstanceId | null;
|
|
/**
|
|
* True only when a human picked the active selection in the composer.
|
|
* Absent/false means seeded (project default / sticky), so later seeds
|
|
* may replace it. Legacy entries predate the flag and read as seeded.
|
|
*/
|
|
modelSelectionExplicit?: boolean;
|
|
runtimeMode: RuntimeMode | null;
|
|
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.files.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.
|
|
*
|
|
* Unlike a real server thread, a draft session can still change target
|
|
* environment/worktree configuration before the first send.
|
|
*/
|
|
export interface DraftSessionState {
|
|
threadId: ThreadId;
|
|
environmentId: EnvironmentId;
|
|
projectId: ProjectId;
|
|
logicalProjectKey: string;
|
|
environmentSelection?: "auto" | "manual";
|
|
loadBalancedEnvironmentId?: EnvironmentId | null;
|
|
createdAt: string;
|
|
runtimeMode: RuntimeMode;
|
|
interactionMode: ProviderInteractionMode;
|
|
branch: string | null;
|
|
worktreePath: string | null;
|
|
envMode: DraftThreadEnvMode;
|
|
startFromOrigin: boolean;
|
|
promotedTo?: ScopedThreadRef | null;
|
|
}
|
|
|
|
export type DraftThreadState = DraftSessionState;
|
|
|
|
/**
|
|
* Draft session metadata paired with its stable draft-session identity.
|
|
*/
|
|
interface ProjectDraftSession extends DraftSessionState {
|
|
draftId: DraftId;
|
|
}
|
|
|
|
/**
|
|
* App-facing composer identity:
|
|
* - `DraftId` for pre-thread draft sessions
|
|
* - `ScopedThreadRef` for server-backed threads
|
|
*
|
|
* Raw `ThreadId` is intentionally excluded so callers cannot drop environment
|
|
* identity for real threads.
|
|
*/
|
|
export type ComposerThreadTarget = ScopedThreadRef | DraftId;
|
|
|
|
/**
|
|
* Persisted store for composer content plus draft-session metadata.
|
|
*
|
|
* The store intentionally models two domains:
|
|
* - draft sessions keyed by `DraftId`
|
|
* - server thread composer state keyed by `ScopedThreadRef`
|
|
*/
|
|
interface ComposerDraftStoreState {
|
|
draftsByThreadKey: Record<string, ComposerThreadDraftState>;
|
|
draftThreadsByThreadKey: Record<string, DraftThreadState>;
|
|
logicalProjectDraftThreadKeyByLogicalProjectKey: Record<string, string>;
|
|
backgroundSubmissionThreadKeys: Record<string, true>;
|
|
stickyModelSelectionByProvider: Partial<Record<ProviderInstanceId, ModelSelection>>;
|
|
stickyActiveProvider: ProviderInstanceId | null;
|
|
/** Returns the editable composer content for a draft session or server thread. */
|
|
getComposerDraft: (target: ComposerThreadTarget) => ComposerThreadDraftState | null;
|
|
/** Looks up the active draft session for a logical project identity. */
|
|
getDraftThreadByLogicalProjectKey: (logicalProjectKey: string) => ProjectDraftSession | null;
|
|
getDraftSessionByLogicalProjectKey: (logicalProjectKey: string) => ProjectDraftSession | null;
|
|
getDraftThreadByProjectRef: (projectRef: ScopedProjectRef) => ProjectDraftSession | null;
|
|
getDraftSessionByProjectRef: (projectRef: ScopedProjectRef) => ProjectDraftSession | null;
|
|
/** Reads mutable draft-session metadata by `DraftId`. */
|
|
getDraftSession: (draftId: DraftId) => DraftSessionState | null;
|
|
/** Resolves a server-thread ref back to a matching draft session when one exists. */
|
|
getDraftSessionByRef: (threadRef: ScopedThreadRef) => DraftSessionState | null;
|
|
getDraftThreadByRef: (threadRef: ScopedThreadRef) => DraftThreadState | null;
|
|
getDraftThread: (threadRef: ComposerThreadTarget) => DraftThreadState | null;
|
|
listDraftThreadKeys: () => string[];
|
|
hasDraftThreadsInEnvironment: (environmentId: EnvironmentId) => boolean;
|
|
/**
|
|
* Creates or updates the draft session tracked for a logical project.
|
|
* Reassigning an existing draft removes its previous logical-project
|
|
* mapping so one session cannot resolve from two projects.
|
|
*/
|
|
setLogicalProjectDraftThreadId: (
|
|
logicalProjectKey: string,
|
|
projectRef: ScopedProjectRef,
|
|
draftId: DraftId,
|
|
options?: {
|
|
threadId?: ThreadId;
|
|
branch?: string | null;
|
|
worktreePath?: string | null;
|
|
createdAt?: string;
|
|
envMode?: DraftThreadEnvMode;
|
|
startFromOrigin?: boolean;
|
|
runtimeMode?: RuntimeMode;
|
|
interactionMode?: ProviderInteractionMode;
|
|
environmentSelection?: "auto" | "manual";
|
|
loadBalancedEnvironmentId?: EnvironmentId | null;
|
|
},
|
|
) => void;
|
|
/** Creates or updates the draft session tracked for a concrete project ref. */
|
|
setProjectDraftThreadId: (
|
|
projectRef: ScopedProjectRef,
|
|
draftId: DraftId,
|
|
options?: {
|
|
threadId?: ThreadId;
|
|
branch?: string | null;
|
|
worktreePath?: string | null;
|
|
createdAt?: string;
|
|
envMode?: DraftThreadEnvMode;
|
|
startFromOrigin?: boolean;
|
|
runtimeMode?: RuntimeMode;
|
|
interactionMode?: ProviderInteractionMode;
|
|
environmentSelection?: "auto" | "manual";
|
|
loadBalancedEnvironmentId?: EnvironmentId | null;
|
|
},
|
|
) => void;
|
|
/** Updates mutable draft-session metadata without touching composer content. */
|
|
setDraftThreadContext: (
|
|
threadRef: ComposerThreadTarget,
|
|
options: {
|
|
branch?: string | null;
|
|
worktreePath?: string | null;
|
|
projectRef?: ScopedProjectRef;
|
|
createdAt?: string;
|
|
envMode?: DraftThreadEnvMode;
|
|
startFromOrigin?: boolean;
|
|
runtimeMode?: RuntimeMode;
|
|
interactionMode?: ProviderInteractionMode;
|
|
environmentSelection?: "auto" | "manual";
|
|
loadBalancedEnvironmentId?: EnvironmentId | null;
|
|
},
|
|
) => void;
|
|
clearProjectDraftThreadId: (projectRef: ScopedProjectRef) => void;
|
|
clearProjectDraftThreadById: (
|
|
projectRef: ScopedProjectRef,
|
|
threadRef: ComposerThreadTarget,
|
|
) => void;
|
|
/** Marks a draft session as being promoted to a real server thread. */
|
|
markDraftThreadPromoting: (threadRef: ComposerThreadTarget, promotedTo?: ScopedThreadRef) => void;
|
|
/** Removes draft-session metadata after promotion is complete. */
|
|
finalizePromotedDraftThread: (threadRef: ComposerThreadTarget) => void;
|
|
clearDraftThread: (threadRef: ComposerThreadTarget) => void;
|
|
setStickyModelSelection: (modelSelection: ModelSelection | null | undefined) => void;
|
|
setPrompt: (threadRef: ComposerThreadTarget, prompt: string) => void;
|
|
setTerminalContexts: (threadRef: ComposerThreadTarget, contexts: TerminalContextDraft[]) => void;
|
|
setModelSelection: (
|
|
threadRef: ComposerThreadTarget,
|
|
modelSelection: ModelSelection | null | undefined,
|
|
opts?: {
|
|
explicit?: boolean;
|
|
/**
|
|
* Replace the stored entry outright instead of preserving its
|
|
* existing options when the incoming selection has none. Used when
|
|
* the selection is a complete snapshot (e.g. carried from another
|
|
* thread) rather than a model-only change.
|
|
*/
|
|
replaceOptions?: boolean;
|
|
},
|
|
) => void;
|
|
/** Replace the model options for one or more providers in the draft. */
|
|
setModelOptions: (
|
|
threadRef: ComposerThreadTarget,
|
|
modelOptions:
|
|
| Partial<Record<string, ReadonlyArray<ProviderOptionSelection>>>
|
|
| null
|
|
| undefined,
|
|
) => void;
|
|
applyStickyState: (threadRef: ComposerThreadTarget) => void;
|
|
setProviderModelOptions: (
|
|
threadRef: ComposerThreadTarget,
|
|
provider: ProviderDriverKind,
|
|
nextProviderOptions: ReadonlyArray<ProviderOptionSelection> | null | undefined,
|
|
options?: {
|
|
instanceId?: ProviderInstanceId | null | undefined;
|
|
model?: string | null | undefined;
|
|
persistSticky?: boolean;
|
|
},
|
|
) => void;
|
|
setRuntimeMode: (
|
|
threadRef: ComposerThreadTarget,
|
|
runtimeMode: RuntimeMode | null | undefined,
|
|
) => void;
|
|
setInteractionMode: (
|
|
threadRef: ComposerThreadTarget,
|
|
interactionMode: ProviderInteractionMode | null | undefined,
|
|
) => void;
|
|
addImage: (threadRef: ComposerThreadTarget, image: ComposerImageAttachment) => void;
|
|
addImages: (threadRef: ComposerThreadTarget, images: ComposerImageAttachment[]) => void;
|
|
removeImage: (threadRef: ComposerThreadTarget, imageId: string) => void;
|
|
addFiles: (threadRef: ComposerThreadTarget, files: ComposerFileAttachment[]) => void;
|
|
removeFile: (threadRef: ComposerThreadTarget, fileId: string) => void;
|
|
setFileUpload: (
|
|
threadRef: ComposerThreadTarget,
|
|
fileId: string,
|
|
environmentId: EnvironmentId,
|
|
attachmentId: string,
|
|
) => void;
|
|
markFileUploadMissing: (
|
|
threadRef: ComposerThreadTarget,
|
|
fileId: string,
|
|
environmentId: EnvironmentId,
|
|
attachmentId: string,
|
|
) => boolean;
|
|
insertTerminalContext: (
|
|
threadRef: ComposerThreadTarget,
|
|
prompt: string,
|
|
context: TerminalContextDraft,
|
|
index: number,
|
|
) => boolean;
|
|
addTerminalContext: (threadRef: ComposerThreadTarget, context: TerminalContextDraft) => void;
|
|
addTerminalContexts: (threadRef: ComposerThreadTarget, contexts: TerminalContextDraft[]) => void;
|
|
removeTerminalContext: (threadRef: ComposerThreadTarget, contextId: string) => void;
|
|
clearTerminalContexts: (threadRef: ComposerThreadTarget) => void;
|
|
/**
|
|
* Append a fresh element pick to the draft. Returns true when accepted,
|
|
* false when deduped against an existing pick of the same element.
|
|
*/
|
|
addElementContext: (
|
|
threadRef: ComposerThreadTarget,
|
|
selection: ElementContextSelection,
|
|
) => boolean;
|
|
/**
|
|
* Replace the entire element-contexts list (used by send-failure retry to
|
|
* restore the pre-send snapshot).
|
|
*/
|
|
setElementContexts: (
|
|
threadRef: ComposerThreadTarget,
|
|
contexts: ReadonlyArray<ElementContextDraft>,
|
|
) => void;
|
|
removeElementContext: (threadRef: ComposerThreadTarget, contextId: string) => void;
|
|
clearElementContexts: (threadRef: ComposerThreadTarget) => void;
|
|
addPreviewAnnotation: (
|
|
threadRef: ComposerThreadTarget,
|
|
annotation: PreviewAnnotationPayload,
|
|
) => void;
|
|
setPreviewAnnotations: (
|
|
threadRef: ComposerThreadTarget,
|
|
annotations: ReadonlyArray<PreviewAnnotationPayload>,
|
|
) => void;
|
|
removePreviewAnnotation: (threadRef: ComposerThreadTarget, annotationId: string) => void;
|
|
addReviewComment: (threadRef: ComposerThreadTarget, comment: ReviewCommentContext) => void;
|
|
setReviewComments: (
|
|
threadRef: ComposerThreadTarget,
|
|
comments: ReadonlyArray<ReviewCommentContext>,
|
|
) => void;
|
|
removeReviewComment: (threadRef: ComposerThreadTarget, commentId: string) => void;
|
|
clearPersistedAttachments: (threadRef: ComposerThreadTarget) => void;
|
|
syncPersistedAttachments: (
|
|
threadRef: ComposerThreadTarget,
|
|
attachments: PersistedComposerImageAttachment[],
|
|
) => void;
|
|
clearComposerContent: (threadRef: ComposerThreadTarget) => void;
|
|
/**
|
|
* Clears the prompt text and attachments, preserving terminal /
|
|
* element contexts, preview annotations, and review comments. Used by the
|
|
* prompt stash. Session-bound context stays in the source draft.
|
|
*/
|
|
clearComposerPromptAndImages: (threadRef: ComposerThreadTarget) => void;
|
|
}
|
|
|
|
export interface EffectiveComposerModelState {
|
|
selectedModel: string;
|
|
modelOptions: ProviderOptionSelectionsByProvider | null;
|
|
}
|
|
|
|
interface ComposerDraftModelState {
|
|
activeProvider: ProviderInstanceId | null;
|
|
modelSelectionByProvider: Partial<Record<ProviderInstanceId, ModelSelection>>;
|
|
}
|
|
|
|
function providerSelectionsFromModelSelection(
|
|
modelSelection: ModelSelection | null | undefined,
|
|
): ProviderOptionSelectionsByProvider | null {
|
|
if (!modelSelection) {
|
|
return null;
|
|
}
|
|
const options = modelSelection.options;
|
|
if (!options || options.length === 0) {
|
|
return null;
|
|
}
|
|
return { [modelSelection.instanceId]: options };
|
|
}
|
|
|
|
function modelSelectionByProviderToOptions(
|
|
map: Partial<Record<string, ModelSelection>> | null | undefined,
|
|
): ProviderOptionSelectionsByProvider | null {
|
|
if (!map) return null;
|
|
const result: ProviderOptionSelectionsByProvider = {};
|
|
for (const [provider, selection] of Object.entries(map)) {
|
|
if (selection?.options && selection.options.length > 0) {
|
|
result[provider] = selection.options;
|
|
}
|
|
}
|
|
return Object.keys(result).length > 0 ? result : null;
|
|
}
|
|
|
|
function cloneModelSelection(selection: ModelSelection): DeepMutable<ModelSelection> {
|
|
return {
|
|
...selection,
|
|
...(selection.options ? { options: selection.options.map((option) => ({ ...option })) } : {}),
|
|
} as DeepMutable<ModelSelection>;
|
|
}
|
|
|
|
function compactModelSelectionByProvider(
|
|
selections: Partial<Record<ProviderInstanceId, ModelSelection>>,
|
|
): DeepMutable<Record<ProviderInstanceId, ModelSelection>> {
|
|
const entries: Array<[string, DeepMutable<ModelSelection>]> = [];
|
|
for (const [provider, selection] of Object.entries(selections)) {
|
|
if (selection !== undefined) {
|
|
entries.push([provider, cloneModelSelection(selection)]);
|
|
}
|
|
}
|
|
return Object.fromEntries(entries) as DeepMutable<Record<ProviderInstanceId, ModelSelection>>;
|
|
}
|
|
|
|
const EMPTY_PERSISTED_DRAFT_STORE_STATE = Object.freeze<PersistedComposerDraftStoreState>({
|
|
draftsByThreadKey: {},
|
|
draftThreadsByThreadKey: {},
|
|
logicalProjectDraftThreadKeyByLogicalProjectKey: {},
|
|
stickyModelSelectionByProvider: {},
|
|
stickyActiveProvider: null,
|
|
});
|
|
|
|
const EMPTY_IMAGES: ComposerImageAttachment[] = [];
|
|
const EMPTY_FILES: ComposerFileAttachment[] = [];
|
|
const EMPTY_IDS: string[] = [];
|
|
const EMPTY_PERSISTED_ATTACHMENTS: PersistedComposerImageAttachment[] = [];
|
|
const EMPTY_TERMINAL_CONTEXTS: TerminalContextDraft[] = [];
|
|
const EMPTY_ELEMENT_CONTEXTS: ElementContextDraft[] = [];
|
|
const EMPTY_PREVIEW_ANNOTATIONS: PreviewAnnotationPayload[] = [];
|
|
const EMPTY_REVIEW_COMMENTS: ReviewCommentContext[] = [];
|
|
Object.freeze(EMPTY_IMAGES);
|
|
Object.freeze(EMPTY_FILES);
|
|
Object.freeze(EMPTY_IDS);
|
|
Object.freeze(EMPTY_PERSISTED_ATTACHMENTS);
|
|
Object.freeze(EMPTY_ELEMENT_CONTEXTS);
|
|
Object.freeze(EMPTY_PREVIEW_ANNOTATIONS);
|
|
Object.freeze(EMPTY_REVIEW_COMMENTS);
|
|
const EMPTY_MODEL_SELECTION_BY_PROVIDER: Partial<Record<ProviderDriverKind, ModelSelection>> =
|
|
Object.freeze({});
|
|
const EMPTY_COMPOSER_DRAFT_MODEL_STATE = Object.freeze<ComposerDraftModelState>({
|
|
activeProvider: null,
|
|
modelSelectionByProvider: EMPTY_MODEL_SELECTION_BY_PROVIDER,
|
|
});
|
|
|
|
const EMPTY_THREAD_DRAFT = Object.freeze<ComposerThreadDraftState>({
|
|
prompt: "",
|
|
images: EMPTY_IMAGES,
|
|
files: EMPTY_FILES,
|
|
nonPersistedImageIds: EMPTY_IDS,
|
|
persistedAttachments: EMPTY_PERSISTED_ATTACHMENTS,
|
|
terminalContexts: EMPTY_TERMINAL_CONTEXTS,
|
|
elementContexts: EMPTY_ELEMENT_CONTEXTS,
|
|
previewAnnotations: EMPTY_PREVIEW_ANNOTATIONS,
|
|
reviewComments: EMPTY_REVIEW_COMMENTS,
|
|
modelSelectionByProvider: EMPTY_MODEL_SELECTION_BY_PROVIDER,
|
|
activeProvider: null,
|
|
runtimeMode: null,
|
|
interactionMode: null,
|
|
});
|
|
|
|
/**
|
|
* Canonical factory for a blank `ComposerThreadDraftState`. Exported so tests
|
|
* (and any other call sites) can build a draft without re-declaring every
|
|
* slice — adding a new field to the interface (e.g. `elementContexts`) only
|
|
* has to be reflected here, not in every stub.
|
|
*/
|
|
function createEmptyThreadDraft(): ComposerThreadDraftState {
|
|
return {
|
|
prompt: "",
|
|
images: [],
|
|
files: [],
|
|
nonPersistedImageIds: [],
|
|
persistedAttachments: [],
|
|
terminalContexts: [],
|
|
elementContexts: [],
|
|
previewAnnotations: [],
|
|
reviewComments: [],
|
|
modelSelectionByProvider: {},
|
|
activeProvider: null,
|
|
runtimeMode: null,
|
|
interactionMode: null,
|
|
};
|
|
}
|
|
|
|
function composerImageDedupKey(image: ComposerImageAttachment): string {
|
|
// Keep this independent from File.lastModified so dedupe is stable for hydrated
|
|
// images reconstructed from localStorage (which get a fresh lastModified value).
|
|
return `${image.mimeType}\u0000${image.sizeBytes}\u0000${image.name}`;
|
|
}
|
|
|
|
export function composerFileDedupKey(
|
|
file: Pick<ComposerFileAttachment, "mimeType" | "sizeBytes" | "name">,
|
|
): string {
|
|
return `${file.mimeType}\u0000${file.sizeBytes}\u0000${file.name}`;
|
|
}
|
|
|
|
export function composerFileMatchesReattachMarker(
|
|
marker: Pick<ComposerFileAttachment, "mimeType" | "sizeBytes" | "name">,
|
|
file: Pick<ComposerFileAttachment, "mimeType" | "sizeBytes" | "name">,
|
|
): boolean {
|
|
if (marker.name !== file.name || marker.sizeBytes !== file.sizeBytes) return false;
|
|
if (marker.mimeType === file.mimeType) return true;
|
|
const markerMimeType = marker.mimeType.toLowerCase();
|
|
return (
|
|
(markerMimeType === "" || markerMimeType === "application/octet-stream") &&
|
|
videoMimeType(marker) !== null &&
|
|
videoMimeType(file) !== null
|
|
);
|
|
}
|
|
|
|
function terminalContextDedupKey(context: TerminalContextDraft): string {
|
|
return `${context.terminalId}\u0000${context.lineStart}\u0000${context.lineEnd}`;
|
|
}
|
|
|
|
function normalizeTerminalContextForThread(
|
|
threadId: ThreadId,
|
|
context: TerminalContextDraft,
|
|
): TerminalContextDraft | null {
|
|
const terminalId = context.terminalId.trim();
|
|
const terminalLabel = context.terminalLabel.trim();
|
|
if (terminalId.length === 0 || terminalLabel.length === 0) {
|
|
return null;
|
|
}
|
|
const lineStart = Math.max(1, Math.floor(context.lineStart));
|
|
const lineEnd = Math.max(lineStart, Math.floor(context.lineEnd));
|
|
return {
|
|
...context,
|
|
threadId,
|
|
terminalId,
|
|
terminalLabel,
|
|
lineStart,
|
|
lineEnd,
|
|
text: normalizeTerminalContextText(context.text),
|
|
};
|
|
}
|
|
|
|
function normalizeTerminalContextsForThread(
|
|
threadId: ThreadId,
|
|
contexts: ReadonlyArray<TerminalContextDraft>,
|
|
): TerminalContextDraft[] {
|
|
const existingIds = new Set<string>();
|
|
const existingDedupKeys = new Set<string>();
|
|
const normalizedContexts: TerminalContextDraft[] = [];
|
|
|
|
for (const context of contexts) {
|
|
const normalizedContext = normalizeTerminalContextForThread(threadId, context);
|
|
if (!normalizedContext) {
|
|
continue;
|
|
}
|
|
const dedupKey = terminalContextDedupKey(normalizedContext);
|
|
if (existingIds.has(normalizedContext.id) || existingDedupKeys.has(dedupKey)) {
|
|
continue;
|
|
}
|
|
normalizedContexts.push(normalizedContext);
|
|
existingIds.add(normalizedContext.id);
|
|
existingDedupKeys.add(dedupKey);
|
|
}
|
|
|
|
return normalizedContexts;
|
|
}
|
|
|
|
function shouldRemoveDraft(draft: ComposerThreadDraftState): boolean {
|
|
return (
|
|
draft.prompt.length === 0 &&
|
|
draft.images.length === 0 &&
|
|
draft.files.length === 0 &&
|
|
draft.persistedAttachments.length === 0 &&
|
|
draft.terminalContexts.length === 0 &&
|
|
draft.elementContexts.length === 0 &&
|
|
draft.previewAnnotations.length === 0 &&
|
|
draft.reviewComments.length === 0 &&
|
|
Object.keys(draft.modelSelectionByProvider).length === 0 &&
|
|
draft.activeProvider === null &&
|
|
draft.runtimeMode === null &&
|
|
draft.interactionMode === null
|
|
);
|
|
}
|
|
|
|
function normalizeProviderDriverKind(value: unknown): ProviderDriverKind | null {
|
|
return isProviderDriverKind(value) ? value : null;
|
|
}
|
|
|
|
/**
|
|
* Match the `ProviderInstanceId` slug pattern (letter followed by
|
|
* letters/digits/`-`/`_`, 1..64 chars). Permissive validator — the schema
|
|
* layer owns authoritative validation; this is used inline to gate typed
|
|
* writes to the draft's instance-keyed maps without pulling the full
|
|
* Effect Schema runtime into the hot path.
|
|
*/
|
|
const PROVIDER_INSTANCE_ID_PATTERN = /^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/;
|
|
|
|
/**
|
|
* Coerce an arbitrary persisted value into a valid `ProviderInstanceId`. Used
|
|
* wherever we need to accept both legacy driver-kind keys and custom instance
|
|
* slugs (e.g. `codex_personal`) as routing keys.
|
|
*/
|
|
function normalizeProviderInstanceId(value: unknown): ProviderInstanceId | null {
|
|
if (typeof value !== "string") return null;
|
|
if (!PROVIDER_INSTANCE_ID_PATTERN.test(value)) return null;
|
|
return value as ProviderInstanceId;
|
|
}
|
|
|
|
/**
|
|
* Coerce an unknown value into a `ReadonlyArray<ProviderOptionSelection>`.
|
|
* Accepts either:
|
|
* - the v3 representation: an array of `{ id, value }` entries
|
|
* - the legacy v2 representation: a record of `{ id: string | boolean }`
|
|
*
|
|
* Validation is intentionally permissive: descriptors are the source of truth
|
|
* for which option ids are meaningful for a given provider/model. Anything
|
|
* outside the descriptor list is harmless trailing data and will simply be
|
|
* ignored downstream.
|
|
*/
|
|
function coerceProviderOptionSelections(
|
|
value: unknown,
|
|
): ReadonlyArray<ProviderOptionSelection> | undefined {
|
|
if (Array.isArray(value)) {
|
|
const out: ProviderOptionSelection[] = [];
|
|
for (const entry of value) {
|
|
if (!entry || typeof entry !== "object") continue;
|
|
const record = entry as Record<string, unknown>;
|
|
const id = record.id;
|
|
const optionValue = record.value;
|
|
if (typeof id !== "string" || id.length === 0) continue;
|
|
if (typeof optionValue === "string" || typeof optionValue === "boolean") {
|
|
out.push({ id, value: optionValue });
|
|
}
|
|
}
|
|
return out.length > 0 ? out : undefined;
|
|
}
|
|
if (value && typeof value === "object") {
|
|
const record = value as Record<string, unknown>;
|
|
const out: ProviderOptionSelection[] = [];
|
|
for (const [id, raw] of Object.entries(record)) {
|
|
if (typeof raw === "string" || typeof raw === "boolean") {
|
|
out.push({ id, value: raw });
|
|
}
|
|
}
|
|
return out.length > 0 ? out : undefined;
|
|
}
|
|
return undefined;
|
|
}
|
|
|
|
/**
|
|
* Normalize a per-provider options bag from either the v3 or legacy v2 shape.
|
|
*
|
|
* `provider` and `legacy` parameters are migration-only inputs used to
|
|
* recover legacy codex fields (effort/codexFastMode/serviceTier) that lived
|
|
* directly on the draft instead of inside `modelOptions.codex`.
|
|
*/
|
|
function normalizeProviderModelOptions(
|
|
value: unknown,
|
|
provider?: ProviderDriverKind | null,
|
|
legacy?: LegacyCodexFields,
|
|
): ProviderOptionSelectionsByProvider | null {
|
|
const candidate = value && typeof value === "object" ? (value as Record<string, unknown>) : null;
|
|
const result: ProviderOptionSelectionsByProvider = {};
|
|
for (const providerKey of ["codex", "claudeAgent", "cursor", "opencode"] as const) {
|
|
const selections = coerceProviderOptionSelections(candidate?.[providerKey]);
|
|
if (selections) {
|
|
result[providerKey] = selections;
|
|
}
|
|
}
|
|
|
|
// Recover legacy codex fields that lived outside modelOptions.
|
|
if (provider === "codex" && legacy) {
|
|
const codexExtras: ProviderOptionSelection[] = [];
|
|
if (typeof legacy.effort === "string" && legacy.effort.length > 0) {
|
|
codexExtras.push({ id: "reasoningEffort", value: legacy.effort });
|
|
}
|
|
const fastMode =
|
|
legacy.codexFastMode === true ||
|
|
(typeof legacy.serviceTier === "string" && legacy.serviceTier === "fast");
|
|
if (fastMode) {
|
|
codexExtras.push({ id: "fastMode", value: true });
|
|
}
|
|
if (codexExtras.length > 0) {
|
|
const existing = result.codex ?? [];
|
|
const existingIds = new Set(existing.map((entry) => entry.id));
|
|
const merged = [...existing];
|
|
for (const extra of codexExtras) {
|
|
if (!existingIds.has(extra.id)) merged.push(extra);
|
|
}
|
|
result.codex = merged;
|
|
}
|
|
}
|
|
|
|
return Object.keys(result).length > 0 ? result : null;
|
|
}
|
|
|
|
// Returns a model selection whose `instanceId` is a valid
|
|
// `ProviderInstanceId` slug. Legacy `provider` fields are promoted verbatim
|
|
// because default instance ids used the same slug as the driver kind.
|
|
//
|
|
// Selections whose instance id doesn't match the slug pattern collapse to
|
|
// `null` — caller is responsible for deciding whether that's a dropped
|
|
// write or a routed error.
|
|
function normalizeModelSelection(
|
|
value: unknown,
|
|
legacy?: {
|
|
provider?: unknown;
|
|
model?: unknown;
|
|
modelOptions?: unknown;
|
|
legacyCodex?: LegacyCodexFields;
|
|
},
|
|
): NormalizedModelSelection | null {
|
|
const candidate = value && typeof value === "object" ? (value as Record<string, unknown>) : null;
|
|
// Post-migration ModelSelection carries `instanceId`; pre-migration (v2
|
|
// storage, legacy wire shapes) carries `provider`. Accept either so both
|
|
// normalized stores and legacy drafts round-trip through this helper.
|
|
const instanceId = normalizeProviderInstanceId(
|
|
candidate?.instanceId ?? candidate?.provider ?? legacy?.provider,
|
|
);
|
|
if (instanceId === null) {
|
|
return null;
|
|
}
|
|
const rawModel = candidate?.model ?? legacy?.model;
|
|
if (typeof rawModel !== "string") {
|
|
return null;
|
|
}
|
|
// Slug normalization can use provider-kind-specific rules when a legacy
|
|
// driver key is present. Instance-only selections are not reverse-inferred
|
|
// into a driver kind here; they get generic default normalization.
|
|
const driverKindHint =
|
|
normalizeProviderDriverKind(candidate?.provider ?? legacy?.provider) ??
|
|
ProviderDriverKind.make("codex");
|
|
const model = normalizeModelSlug(rawModel, driverKindHint);
|
|
if (!model) {
|
|
return null;
|
|
}
|
|
if (Array.isArray(candidate?.options)) {
|
|
const selections = coerceProviderOptionSelections(candidate.options);
|
|
return createModelSelection(instanceId, model, selections) as NormalizedModelSelection;
|
|
}
|
|
// Per-kind options were a pre-migration concern; only recover them for a
|
|
// built-in-kind instance. Custom instances don't have a legacy options
|
|
// store to thread through here.
|
|
const kindForLegacyOptions = normalizeProviderDriverKind(instanceId);
|
|
const modelOptions = kindForLegacyOptions
|
|
? normalizeProviderModelOptions(
|
|
candidate?.options ? { [kindForLegacyOptions]: candidate.options } : legacy?.modelOptions,
|
|
kindForLegacyOptions,
|
|
kindForLegacyOptions === "codex" ? legacy?.legacyCodex : undefined,
|
|
)
|
|
: null;
|
|
const options = kindForLegacyOptions ? modelOptions?.[kindForLegacyOptions] : undefined;
|
|
return createModelSelection(instanceId, model, options) as NormalizedModelSelection;
|
|
}
|
|
|
|
type NormalizedModelSelection = Omit<ModelSelection, "instanceId"> & {
|
|
readonly instanceId: ProviderInstanceId;
|
|
};
|
|
|
|
// ── Legacy sync helpers (used only during migration from v2 storage) ──
|
|
//
|
|
// These operate against the legacy kind-keyed `modelOptions` map. The
|
|
// normalized selection now carries an open `ProviderInstanceId`; legacy
|
|
// migration only recovers options for keys that existed before custom
|
|
// provider instances.
|
|
|
|
function legacySyncModelSelectionOptions(
|
|
modelSelection: NormalizedModelSelection | null,
|
|
modelOptions: ProviderOptionSelectionsByProvider | null | undefined,
|
|
): NormalizedModelSelection | null {
|
|
if (modelSelection === null) {
|
|
return null;
|
|
}
|
|
const kind = normalizeProviderDriverKind(modelSelection.instanceId);
|
|
const options = kind ? modelOptions?.[kind] : undefined;
|
|
return createModelSelection(
|
|
modelSelection.instanceId,
|
|
modelSelection.model,
|
|
options,
|
|
) as NormalizedModelSelection;
|
|
}
|
|
|
|
function legacyMergeModelSelectionIntoProviderModelOptions(
|
|
modelSelection: NormalizedModelSelection | null,
|
|
currentModelOptions: ProviderOptionSelectionsByProvider | null | undefined,
|
|
): ProviderOptionSelectionsByProvider | null {
|
|
if (!modelSelection?.options || modelSelection.options.length === 0) {
|
|
return normalizeProviderModelOptions(currentModelOptions);
|
|
}
|
|
const kind = normalizeProviderDriverKind(modelSelection.instanceId);
|
|
if (!kind) {
|
|
return normalizeProviderModelOptions(currentModelOptions);
|
|
}
|
|
return legacyReplaceProviderModelOptions(
|
|
normalizeProviderModelOptions(currentModelOptions),
|
|
kind,
|
|
modelSelection.options,
|
|
);
|
|
}
|
|
|
|
function legacyReplaceProviderModelOptions(
|
|
currentModelOptions: ProviderOptionSelectionsByProvider | null | undefined,
|
|
provider: ProviderDriverKind,
|
|
nextProviderOptions: ReadonlyArray<ProviderOptionSelection> | null | undefined,
|
|
): ProviderOptionSelectionsByProvider | null {
|
|
const { [provider]: _discardedProviderModelOptions, ...otherProviderModelOptions } =
|
|
currentModelOptions ?? {};
|
|
const merged: ProviderOptionSelectionsByProvider = { ...otherProviderModelOptions };
|
|
if (nextProviderOptions && nextProviderOptions.length > 0) {
|
|
merged[provider] = nextProviderOptions;
|
|
}
|
|
return Object.keys(merged).length > 0 ? merged : null;
|
|
}
|
|
|
|
// ── New helpers for the consolidated representation ────────────────────
|
|
|
|
function legacyToModelSelectionByProvider(
|
|
modelSelection: NormalizedModelSelection | null,
|
|
modelOptions: ProviderOptionSelectionsByProvider | null | undefined,
|
|
): Partial<Record<ProviderInstanceId, ModelSelection>> {
|
|
const result: Partial<Record<ProviderInstanceId, ModelSelection>> = {};
|
|
if (modelOptions) {
|
|
for (const provider of ["codex", "claudeAgent", "cursor", "opencode"] as const) {
|
|
const options = modelOptions[provider];
|
|
if (options && options.length > 0) {
|
|
const driverKind = ProviderDriverKind.make(provider);
|
|
const instanceKey = defaultInstanceIdForDriver(driverKind);
|
|
result[instanceKey] = createModelSelection(
|
|
instanceKey,
|
|
modelSelection?.instanceId === instanceKey
|
|
? modelSelection.model
|
|
: (DEFAULT_MODEL_BY_PROVIDER[driverKind] ?? DEFAULT_MODEL),
|
|
options,
|
|
);
|
|
}
|
|
}
|
|
}
|
|
if (modelSelection) {
|
|
result[modelSelection.instanceId] = modelSelection as ModelSelection;
|
|
}
|
|
return result;
|
|
}
|
|
|
|
export function deriveEffectiveComposerModelState(input: {
|
|
draft:
|
|
| Pick<ComposerThreadDraftState, "modelSelectionByProvider" | "activeProvider">
|
|
| null
|
|
| undefined;
|
|
providers: ReadonlyArray<ServerProvider>;
|
|
selectedProvider: ProviderDriverKind;
|
|
/**
|
|
* Optional routing key of the instance whose selection should override
|
|
* the driver-level lookup. When present, the draft is queried by
|
|
* `modelSelectionByProvider[selectedInstanceId]` so a custom Codex
|
|
* instance (e.g. `codex_personal`) reads its own saved model instead of
|
|
* collapsing to the default Codex bucket.
|
|
*/
|
|
selectedInstanceId?: ProviderInstanceId | null | undefined;
|
|
threadModelSelection: ModelSelection | null | undefined;
|
|
projectModelSelection: ModelSelection | null | undefined;
|
|
settings: UnifiedSettings;
|
|
}): EffectiveComposerModelState {
|
|
const baseModelCandidate =
|
|
input.threadModelSelection?.model ?? input.projectModelSelection?.model ?? null;
|
|
const preserveThreadModel =
|
|
input.selectedInstanceId !== null &&
|
|
input.selectedInstanceId !== undefined &&
|
|
input.threadModelSelection?.instanceId === input.selectedInstanceId;
|
|
const baseModel =
|
|
(input.selectedInstanceId
|
|
? resolveAppModelSelectionForInstance(
|
|
input.selectedInstanceId,
|
|
input.settings,
|
|
input.providers,
|
|
baseModelCandidate,
|
|
{ preserveUnavailableSelection: preserveThreadModel },
|
|
)
|
|
: null) ??
|
|
// Antigravity has no static model or cross-account catalog fallback.
|
|
(input.selectedProvider === "antigravity" && input.selectedInstanceId ? "" : null) ??
|
|
resolveAppModelSelection(
|
|
input.selectedProvider,
|
|
input.settings,
|
|
input.providers,
|
|
baseModelCandidate,
|
|
) ??
|
|
normalizeModelSlug(baseModelCandidate, input.selectedProvider) ??
|
|
getDefaultServerModel(input.providers, input.selectedProvider);
|
|
// Look up the instance's saved selection first; fall back to the
|
|
// driver-kind bucket so legacy kind-keyed drafts still resolve. Every
|
|
// `ProviderDriverKind` literal is a valid `ProviderInstanceId` slug, so the
|
|
// cast to the branded type is safe.
|
|
const instanceSelection = input.selectedInstanceId
|
|
? input.draft?.modelSelectionByProvider?.[input.selectedInstanceId]
|
|
: undefined;
|
|
const legacySelection =
|
|
input.selectedProvider === "antigravity" &&
|
|
input.selectedInstanceId &&
|
|
input.selectedInstanceId !== defaultInstanceIdForDriver(input.selectedProvider)
|
|
? undefined
|
|
: input.draft?.modelSelectionByProvider?.[ProviderInstanceId.make(input.selectedProvider)];
|
|
const activeSelection = instanceSelection ?? legacySelection;
|
|
const activeSelectionInstanceId = instanceSelection
|
|
? (input.selectedInstanceId ?? ProviderInstanceId.make(input.selectedProvider))
|
|
: ProviderInstanceId.make(input.selectedProvider);
|
|
const selectedModel = activeSelection?.model
|
|
? (resolveAppModelSelectionForInstance(
|
|
activeSelectionInstanceId,
|
|
input.settings,
|
|
input.providers,
|
|
activeSelection.model,
|
|
{ preserveUnavailableSelection: true },
|
|
) ??
|
|
(input.selectedProvider === "antigravity" ? "" : null) ??
|
|
resolveAppModelSelection(
|
|
input.selectedProvider,
|
|
input.settings,
|
|
input.providers,
|
|
activeSelection.model,
|
|
))
|
|
: baseModel;
|
|
const modelOptions =
|
|
modelSelectionByProviderToOptions(input.draft?.modelSelectionByProvider) ??
|
|
providerSelectionsFromModelSelection(input.threadModelSelection) ??
|
|
providerSelectionsFromModelSelection(input.projectModelSelection) ??
|
|
null;
|
|
|
|
return {
|
|
selectedModel,
|
|
modelOptions,
|
|
};
|
|
}
|
|
|
|
function revokeObjectPreviewUrl(previewUrl: string): void {
|
|
if (typeof URL === "undefined") {
|
|
return;
|
|
}
|
|
if (!previewUrl.startsWith("blob:")) {
|
|
return;
|
|
}
|
|
URL.revokeObjectURL(previewUrl);
|
|
}
|
|
|
|
function revokeDraftThreadPreviewUrls(draft: ComposerThreadDraftState | undefined): void {
|
|
if (!draft) {
|
|
return;
|
|
}
|
|
for (const image of draft.images) {
|
|
revokeObjectPreviewUrl(image.previewUrl);
|
|
}
|
|
}
|
|
|
|
function normalizePersistedAttachment(value: unknown): PersistedComposerImageAttachment | null {
|
|
if (!value || typeof value !== "object") {
|
|
return null;
|
|
}
|
|
const candidate = value as Record<string, unknown>;
|
|
const id = candidate.id;
|
|
const name = candidate.name;
|
|
const mimeType = candidate.mimeType;
|
|
const sizeBytes = candidate.sizeBytes;
|
|
const dataUrl = candidate.dataUrl;
|
|
if (
|
|
typeof id !== "string" ||
|
|
typeof name !== "string" ||
|
|
typeof mimeType !== "string" ||
|
|
typeof sizeBytes !== "number" ||
|
|
!Number.isFinite(sizeBytes) ||
|
|
typeof dataUrl !== "string" ||
|
|
id.length === 0 ||
|
|
dataUrl.length === 0
|
|
) {
|
|
return null;
|
|
}
|
|
return {
|
|
id,
|
|
name,
|
|
mimeType,
|
|
sizeBytes,
|
|
dataUrl,
|
|
};
|
|
}
|
|
|
|
function normalizePersistedElementContextDraft(
|
|
value: unknown,
|
|
): PersistedElementContextDraft | null {
|
|
if (!value || typeof value !== "object") return null;
|
|
const candidate = value as Record<string, unknown>;
|
|
const id = candidate.id;
|
|
const threadId = candidate.threadId;
|
|
const pickedAt = candidate.pickedAt;
|
|
const pageUrl = candidate.pageUrl;
|
|
const tagName = candidate.tagName;
|
|
if (
|
|
typeof id !== "string" ||
|
|
id.length === 0 ||
|
|
typeof threadId !== "string" ||
|
|
threadId.length === 0 ||
|
|
typeof pickedAt !== "string" ||
|
|
pickedAt.length === 0 ||
|
|
typeof pageUrl !== "string" ||
|
|
pageUrl.length === 0 ||
|
|
typeof tagName !== "string" ||
|
|
tagName.length === 0
|
|
) {
|
|
return null;
|
|
}
|
|
const sourceCandidate = candidate.source;
|
|
let source: PersistedElementContextDraft["source"] = null;
|
|
if (sourceCandidate && typeof sourceCandidate === "object") {
|
|
const sourceRecord = sourceCandidate as Record<string, unknown>;
|
|
source = {
|
|
functionName:
|
|
typeof sourceRecord.functionName === "string" ? sourceRecord.functionName : null,
|
|
fileName: typeof sourceRecord.fileName === "string" ? sourceRecord.fileName : null,
|
|
lineNumber:
|
|
typeof sourceRecord.lineNumber === "number" && Number.isFinite(sourceRecord.lineNumber)
|
|
? sourceRecord.lineNumber
|
|
: null,
|
|
columnNumber:
|
|
typeof sourceRecord.columnNumber === "number" && Number.isFinite(sourceRecord.columnNumber)
|
|
? sourceRecord.columnNumber
|
|
: null,
|
|
};
|
|
}
|
|
return {
|
|
id,
|
|
threadId: threadId as ThreadId,
|
|
pickedAt,
|
|
pageUrl,
|
|
pageTitle: typeof candidate.pageTitle === "string" ? candidate.pageTitle : null,
|
|
tagName,
|
|
selector: typeof candidate.selector === "string" ? candidate.selector : null,
|
|
htmlPreview: typeof candidate.htmlPreview === "string" ? candidate.htmlPreview : "",
|
|
componentName: typeof candidate.componentName === "string" ? candidate.componentName : null,
|
|
source,
|
|
styles: typeof candidate.styles === "string" ? candidate.styles : "",
|
|
};
|
|
}
|
|
|
|
function normalizePersistedTerminalContextDraft(
|
|
value: unknown,
|
|
): PersistedTerminalContextDraft | null {
|
|
if (!value || typeof value !== "object") {
|
|
return null;
|
|
}
|
|
const candidate = value as Record<string, unknown>;
|
|
const id = candidate.id;
|
|
const threadId = candidate.threadId;
|
|
const createdAt = candidate.createdAt;
|
|
const lineStart = candidate.lineStart;
|
|
const lineEnd = candidate.lineEnd;
|
|
if (
|
|
typeof id !== "string" ||
|
|
id.length === 0 ||
|
|
typeof threadId !== "string" ||
|
|
threadId.length === 0 ||
|
|
typeof createdAt !== "string" ||
|
|
createdAt.length === 0 ||
|
|
typeof lineStart !== "number" ||
|
|
!Number.isFinite(lineStart) ||
|
|
typeof lineEnd !== "number" ||
|
|
!Number.isFinite(lineEnd)
|
|
) {
|
|
return null;
|
|
}
|
|
const terminalId = typeof candidate.terminalId === "string" ? candidate.terminalId.trim() : "";
|
|
const terminalLabel =
|
|
typeof candidate.terminalLabel === "string" ? candidate.terminalLabel.trim() : "";
|
|
if (terminalId.length === 0 || terminalLabel.length === 0) {
|
|
return null;
|
|
}
|
|
const normalizedLineStart = Math.max(1, Math.floor(lineStart));
|
|
const normalizedLineEnd = Math.max(normalizedLineStart, Math.floor(lineEnd));
|
|
return {
|
|
id,
|
|
threadId: threadId as ThreadId,
|
|
createdAt,
|
|
terminalId,
|
|
terminalLabel,
|
|
lineStart: normalizedLineStart,
|
|
lineEnd: normalizedLineEnd,
|
|
};
|
|
}
|
|
|
|
function normalizeDraftThreadEnvMode(
|
|
value: unknown,
|
|
fallbackWorktreePath: string | null,
|
|
): DraftThreadEnvMode {
|
|
if (value === "local" || value === "worktree") {
|
|
return value;
|
|
}
|
|
return fallbackWorktreePath ? "worktree" : "local";
|
|
}
|
|
|
|
function projectDraftKey(projectRef: ScopedProjectRef): string {
|
|
return scopedProjectKey(projectRef);
|
|
}
|
|
|
|
function logicalProjectDraftKey(logicalProjectKey: string): string {
|
|
return logicalProjectKey.trim();
|
|
}
|
|
|
|
/**
|
|
* Runtime composer storage key for app-facing identities only.
|
|
*
|
|
* Draft sessions are keyed by `DraftId`. Real threads are keyed by
|
|
* `ScopedThreadRef` so environment identity is always preserved.
|
|
*/
|
|
export function composerTargetKey(target: ScopedThreadRef | DraftId): string {
|
|
if (typeof target === "string") {
|
|
return target.trim();
|
|
}
|
|
return scopedThreadKey(target);
|
|
}
|
|
|
|
/**
|
|
* Legacy persisted data may still be keyed by a raw `ThreadId`. This helper is
|
|
* intentionally migration-only so live code cannot accidentally accept that
|
|
* incomplete identity.
|
|
*/
|
|
function normalizeLegacyComposerStorageKey(
|
|
threadKeyOrId: string,
|
|
options?: {
|
|
environmentId?: EnvironmentId;
|
|
},
|
|
): string {
|
|
const parsedThreadRef = parseScopedThreadKey(threadKeyOrId);
|
|
if (parsedThreadRef) {
|
|
return composerTargetKey(parsedThreadRef);
|
|
}
|
|
if (options?.environmentId) {
|
|
return composerTargetKey(scopeThreadRef(options.environmentId, threadKeyOrId as ThreadId));
|
|
}
|
|
return threadKeyOrId;
|
|
}
|
|
|
|
function composerThreadRefFromKey(threadKey: string): ScopedThreadRef | null {
|
|
return parseScopedThreadKey(threadKey);
|
|
}
|
|
|
|
type ComposerThreadLookupState = Pick<
|
|
ComposerDraftStoreState,
|
|
"draftsByThreadKey" | "draftThreadsByThreadKey"
|
|
>;
|
|
|
|
function normalizeComposerTarget(
|
|
state: ComposerThreadLookupState,
|
|
target: ComposerThreadTarget,
|
|
): ComposerThreadTarget | null {
|
|
if (typeof target === "string") {
|
|
const draftId = target.trim();
|
|
return draftId.length > 0 ? DraftId.make(draftId) : null;
|
|
}
|
|
return target;
|
|
}
|
|
|
|
function resolveComposerDraftKey(
|
|
state: ComposerThreadLookupState,
|
|
target: ComposerThreadTarget,
|
|
): string | null {
|
|
const normalizedTarget = normalizeComposerTarget(state, target);
|
|
if (!normalizedTarget) {
|
|
return null;
|
|
}
|
|
if (typeof normalizedTarget !== "string") {
|
|
const scopedKey = composerTargetKey(normalizedTarget);
|
|
if (state.draftsByThreadKey[scopedKey]) {
|
|
return scopedKey;
|
|
}
|
|
for (const [draftId, draftSession] of Object.entries(state.draftThreadsByThreadKey)) {
|
|
if (
|
|
draftSession.environmentId === normalizedTarget.environmentId &&
|
|
draftSession.threadId === normalizedTarget.threadId
|
|
) {
|
|
return draftId;
|
|
}
|
|
}
|
|
return scopedKey;
|
|
}
|
|
const threadKey = composerTargetKey(normalizedTarget);
|
|
return threadKey.length > 0 ? threadKey : null;
|
|
}
|
|
|
|
function resolveComposerThreadId(
|
|
state: ComposerThreadLookupState,
|
|
target: ComposerThreadTarget,
|
|
): ThreadId | null {
|
|
const normalizedTarget = normalizeComposerTarget(state, target);
|
|
if (!normalizedTarget) {
|
|
return null;
|
|
}
|
|
if (typeof normalizedTarget !== "string") {
|
|
return normalizedTarget.threadId;
|
|
}
|
|
return state.draftThreadsByThreadKey[normalizedTarget]?.threadId ?? null;
|
|
}
|
|
|
|
function getComposerDraftState(
|
|
state: Pick<ComposerDraftStoreState, "draftsByThreadKey" | "draftThreadsByThreadKey">,
|
|
target: ComposerThreadTarget,
|
|
): ComposerThreadDraftState | null {
|
|
const threadKey = resolveComposerDraftKey(state, target);
|
|
if (!threadKey) {
|
|
return null;
|
|
}
|
|
return state.draftsByThreadKey[threadKey] ?? null;
|
|
}
|
|
|
|
function isComposerThreadKeyInUse(mappings: Record<string, string>, threadKey: string): boolean {
|
|
return Object.values(mappings).includes(threadKey);
|
|
}
|
|
|
|
function toProjectDraftSession(
|
|
draftId: DraftId,
|
|
draftSession: DraftSessionState,
|
|
): ProjectDraftSession {
|
|
return {
|
|
draftId,
|
|
...draftSession,
|
|
};
|
|
}
|
|
|
|
function createDraftThreadState(
|
|
projectRef: ScopedProjectRef,
|
|
threadId: ThreadId,
|
|
logicalProjectKey: string,
|
|
existingThread: DraftThreadState | undefined,
|
|
options?: {
|
|
threadId?: ThreadId;
|
|
branch?: string | null;
|
|
worktreePath?: string | null;
|
|
createdAt?: string;
|
|
envMode?: DraftThreadEnvMode;
|
|
startFromOrigin?: boolean;
|
|
runtimeMode?: RuntimeMode;
|
|
interactionMode?: ProviderInteractionMode;
|
|
environmentSelection?: "auto" | "manual";
|
|
loadBalancedEnvironmentId?: EnvironmentId | null;
|
|
},
|
|
): DraftThreadState {
|
|
// A project change (including switching environments within a logical
|
|
// project) invalidates machine-specific context: the branch may not exist
|
|
// there and the worktree path certainly doesn't. The user's *intent* —
|
|
// env mode and start-from-origin — is machine-independent and carries.
|
|
const projectChanged =
|
|
existingThread !== undefined &&
|
|
(existingThread.environmentId !== projectRef.environmentId ||
|
|
existingThread.projectId !== projectRef.projectId);
|
|
const nextWorktreePath =
|
|
options?.worktreePath === undefined
|
|
? projectChanged
|
|
? null
|
|
: (existingThread?.worktreePath ?? null)
|
|
: (options.worktreePath ?? null);
|
|
const nextBranch =
|
|
options?.branch === undefined
|
|
? projectChanged
|
|
? null
|
|
: (existingThread?.branch ?? null)
|
|
: (options.branch ?? null);
|
|
const nextStartFromOrigin =
|
|
options?.startFromOrigin === undefined
|
|
? (existingThread?.startFromOrigin ?? false)
|
|
: options.startFromOrigin;
|
|
const environmentSelection =
|
|
options?.environmentSelection ?? existingThread?.environmentSelection;
|
|
return {
|
|
threadId,
|
|
environmentId: projectRef.environmentId,
|
|
projectId: projectRef.projectId,
|
|
logicalProjectKey,
|
|
...(environmentSelection ? { environmentSelection } : {}),
|
|
...(options?.loadBalancedEnvironmentId !== undefined
|
|
? { loadBalancedEnvironmentId: options.loadBalancedEnvironmentId }
|
|
: existingThread?.loadBalancedEnvironmentId !== undefined
|
|
? {
|
|
loadBalancedEnvironmentId: projectChanged
|
|
? null
|
|
: existingThread.loadBalancedEnvironmentId,
|
|
}
|
|
: {}),
|
|
createdAt: options?.createdAt ?? existingThread?.createdAt ?? new Date().toISOString(),
|
|
runtimeMode: options?.runtimeMode ?? existingThread?.runtimeMode ?? DEFAULT_RUNTIME_MODE,
|
|
interactionMode:
|
|
options?.interactionMode ?? existingThread?.interactionMode ?? DEFAULT_INTERACTION_MODE,
|
|
branch: nextBranch,
|
|
worktreePath: nextWorktreePath,
|
|
envMode:
|
|
options?.envMode ?? (nextWorktreePath ? "worktree" : (existingThread?.envMode ?? "local")),
|
|
startFromOrigin: nextStartFromOrigin,
|
|
promotedTo: null,
|
|
};
|
|
}
|
|
|
|
function scopedThreadRefsEqual(
|
|
left: ScopedThreadRef | null | undefined,
|
|
right: ScopedThreadRef | null | undefined,
|
|
): boolean {
|
|
if (!left || !right) {
|
|
return left === right;
|
|
}
|
|
return left.environmentId === right.environmentId && left.threadId === right.threadId;
|
|
}
|
|
|
|
function isDraftThreadPromoting(draftThread: DraftThreadState | null | undefined): boolean {
|
|
return draftThread?.promotedTo !== null && draftThread?.promotedTo !== undefined;
|
|
}
|
|
|
|
function draftThreadsEqual(left: DraftThreadState | undefined, right: DraftThreadState): boolean {
|
|
return (
|
|
!!left &&
|
|
left.threadId === right.threadId &&
|
|
left.environmentId === right.environmentId &&
|
|
left.projectId === right.projectId &&
|
|
left.logicalProjectKey === right.logicalProjectKey &&
|
|
left.environmentSelection === right.environmentSelection &&
|
|
left.loadBalancedEnvironmentId === right.loadBalancedEnvironmentId &&
|
|
left.createdAt === right.createdAt &&
|
|
left.runtimeMode === right.runtimeMode &&
|
|
left.interactionMode === right.interactionMode &&
|
|
left.branch === right.branch &&
|
|
left.worktreePath === right.worktreePath &&
|
|
left.envMode === right.envMode &&
|
|
left.startFromOrigin === right.startFromOrigin &&
|
|
scopedThreadRefsEqual(left.promotedTo, right.promotedTo)
|
|
);
|
|
}
|
|
|
|
function removeDraftThreadReferences(
|
|
state: Pick<
|
|
ComposerDraftStoreState,
|
|
| "draftThreadsByThreadKey"
|
|
| "draftsByThreadKey"
|
|
| "logicalProjectDraftThreadKeyByLogicalProjectKey"
|
|
>,
|
|
threadKey: string,
|
|
composerDestination?: ScopedThreadRef,
|
|
): Pick<
|
|
ComposerDraftStoreState,
|
|
| "draftThreadsByThreadKey"
|
|
| "draftsByThreadKey"
|
|
| "logicalProjectDraftThreadKeyByLogicalProjectKey"
|
|
> {
|
|
const nextLogicalMappings = Object.fromEntries(
|
|
Object.entries(state.logicalProjectDraftThreadKeyByLogicalProjectKey).filter(
|
|
([, draftThreadKey]) => draftThreadKey !== threadKey,
|
|
),
|
|
) as Record<string, string>;
|
|
const { [threadKey]: _removedDraftThread, ...restDraftThreadsByThreadKey } =
|
|
state.draftThreadsByThreadKey;
|
|
const { [threadKey]: removedComposerDraft, ...restDraftsByThreadKey } = state.draftsByThreadKey;
|
|
if (composerDestination && removedComposerDraft) {
|
|
restDraftsByThreadKey[composerTargetKey(composerDestination)] = removedComposerDraft;
|
|
} else {
|
|
revokeDraftThreadPreviewUrls(removedComposerDraft);
|
|
}
|
|
return {
|
|
draftsByThreadKey: restDraftsByThreadKey,
|
|
draftThreadsByThreadKey: restDraftThreadsByThreadKey,
|
|
logicalProjectDraftThreadKeyByLogicalProjectKey: nextLogicalMappings,
|
|
};
|
|
}
|
|
|
|
function normalizePersistedDraftThreads(
|
|
rawDraftThreadsByThreadId: unknown,
|
|
rawProjectDraftThreadIdByProjectKey: unknown,
|
|
): Pick<
|
|
PersistedComposerDraftStoreState,
|
|
"draftThreadsByThreadKey" | "logicalProjectDraftThreadKeyByLogicalProjectKey"
|
|
> {
|
|
const draftThreadsByThreadKey: Record<string, PersistedDraftThreadState> = {};
|
|
const environmentIdByThreadId = new Map<ThreadId, EnvironmentId>();
|
|
if (
|
|
rawProjectDraftThreadIdByProjectKey &&
|
|
typeof rawProjectDraftThreadIdByProjectKey === "object"
|
|
) {
|
|
for (const [projectKey, threadId] of Object.entries(
|
|
rawProjectDraftThreadIdByProjectKey as Record<string, unknown>,
|
|
)) {
|
|
if (typeof threadId !== "string" || threadId.length === 0) {
|
|
continue;
|
|
}
|
|
const projectRef = parseScopedProjectKey(projectKey);
|
|
if (!projectRef) {
|
|
continue;
|
|
}
|
|
const parsedThreadRef = parseScopedThreadKey(threadId);
|
|
if (parsedThreadRef) {
|
|
environmentIdByThreadId.set(parsedThreadRef.threadId, parsedThreadRef.environmentId);
|
|
continue;
|
|
}
|
|
environmentIdByThreadId.set(threadId as ThreadId, projectRef.environmentId);
|
|
}
|
|
}
|
|
if (rawDraftThreadsByThreadId && typeof rawDraftThreadsByThreadId === "object") {
|
|
for (const [threadKeyOrId, rawDraftThread] of Object.entries(
|
|
rawDraftThreadsByThreadId as Record<string, unknown>,
|
|
)) {
|
|
if (typeof threadKeyOrId !== "string" || threadKeyOrId.length === 0) {
|
|
continue;
|
|
}
|
|
if (!rawDraftThread || typeof rawDraftThread !== "object") {
|
|
continue;
|
|
}
|
|
const candidateDraftThread = rawDraftThread as Record<string, unknown>;
|
|
const parsedThreadRef = parseScopedThreadKey(threadKeyOrId);
|
|
const threadKey = normalizeLegacyComposerStorageKey(threadKeyOrId);
|
|
const threadId =
|
|
parsedThreadRef?.threadId ??
|
|
(typeof candidateDraftThread.threadId === "string" &&
|
|
candidateDraftThread.threadId.length > 0
|
|
? (candidateDraftThread.threadId as ThreadId)
|
|
: (threadKeyOrId as ThreadId));
|
|
const environmentId =
|
|
parsedThreadRef?.environmentId ??
|
|
(typeof candidateDraftThread.environmentId === "string" &&
|
|
candidateDraftThread.environmentId.length > 0
|
|
? (candidateDraftThread.environmentId as EnvironmentId)
|
|
: environmentIdByThreadId.get(threadKeyOrId as ThreadId));
|
|
const projectId = candidateDraftThread.projectId;
|
|
const createdAt = candidateDraftThread.createdAt;
|
|
const branch = candidateDraftThread.branch;
|
|
const worktreePath = candidateDraftThread.worktreePath;
|
|
const startFromOrigin = candidateDraftThread.startFromOrigin === true;
|
|
const normalizedWorktreePath = typeof worktreePath === "string" ? worktreePath : null;
|
|
const promotedToCandidate = candidateDraftThread.promotedTo;
|
|
const promotedToRecord =
|
|
promotedToCandidate && typeof promotedToCandidate === "object"
|
|
? (promotedToCandidate as Record<string, unknown>)
|
|
: null;
|
|
const promotedTo =
|
|
promotedToRecord &&
|
|
typeof promotedToRecord.environmentId === "string" &&
|
|
promotedToRecord.environmentId.length > 0 &&
|
|
typeof promotedToRecord.threadId === "string" &&
|
|
promotedToRecord.threadId.length > 0
|
|
? scopeThreadRef(
|
|
promotedToRecord.environmentId as EnvironmentId,
|
|
promotedToRecord.threadId as ThreadId,
|
|
)
|
|
: null;
|
|
if (typeof projectId !== "string" || projectId.length === 0 || environmentId === undefined) {
|
|
continue;
|
|
}
|
|
const normalizedEnvironmentId = environmentId as EnvironmentId;
|
|
draftThreadsByThreadKey[threadKey] = {
|
|
threadId,
|
|
environmentId: normalizedEnvironmentId,
|
|
projectId: projectId as ProjectId,
|
|
logicalProjectKey:
|
|
typeof candidateDraftThread.logicalProjectKey === "string" &&
|
|
candidateDraftThread.logicalProjectKey.length > 0
|
|
? candidateDraftThread.logicalProjectKey
|
|
: parsedThreadRef
|
|
? projectDraftKey(scopeProjectRef(normalizedEnvironmentId, projectId as ProjectId))
|
|
: threadKeyOrId,
|
|
createdAt:
|
|
typeof createdAt === "string" && createdAt.length > 0
|
|
? createdAt
|
|
: new Date().toISOString(),
|
|
runtimeMode: isRuntimeMode(candidateDraftThread.runtimeMode)
|
|
? candidateDraftThread.runtimeMode
|
|
: DEFAULT_RUNTIME_MODE,
|
|
interactionMode:
|
|
candidateDraftThread.interactionMode === "plan" ||
|
|
candidateDraftThread.interactionMode === "default"
|
|
? candidateDraftThread.interactionMode
|
|
: DEFAULT_INTERACTION_MODE,
|
|
branch: typeof branch === "string" ? branch : null,
|
|
worktreePath: normalizedWorktreePath,
|
|
envMode: normalizeDraftThreadEnvMode(candidateDraftThread.envMode, normalizedWorktreePath),
|
|
startFromOrigin,
|
|
...(candidateDraftThread.environmentSelection === "manual" ||
|
|
candidateDraftThread.environmentSelection === "auto"
|
|
? { environmentSelection: candidateDraftThread.environmentSelection }
|
|
: {}),
|
|
...(typeof candidateDraftThread.loadBalancedEnvironmentId === "string" &&
|
|
candidateDraftThread.loadBalancedEnvironmentId.length > 0
|
|
? { loadBalancedEnvironmentId: candidateDraftThread.loadBalancedEnvironmentId }
|
|
: candidateDraftThread.loadBalancedEnvironmentId === null
|
|
? { loadBalancedEnvironmentId: null }
|
|
: {}),
|
|
promotedTo,
|
|
};
|
|
}
|
|
}
|
|
|
|
const logicalProjectDraftThreadKeyByLogicalProjectKey: Record<string, string> = {};
|
|
if (
|
|
rawProjectDraftThreadIdByProjectKey &&
|
|
typeof rawProjectDraftThreadIdByProjectKey === "object"
|
|
) {
|
|
for (const [logicalProjectKey, threadKeyOrId] of Object.entries(
|
|
rawProjectDraftThreadIdByProjectKey as Record<string, unknown>,
|
|
)) {
|
|
if (typeof threadKeyOrId !== "string" || threadKeyOrId.length === 0) {
|
|
continue;
|
|
}
|
|
const projectRef = parseScopedProjectKey(logicalProjectKey);
|
|
const parsedThreadRef = parseScopedThreadKey(threadKeyOrId);
|
|
const threadKey = normalizeLegacyComposerStorageKey(threadKeyOrId);
|
|
logicalProjectDraftThreadKeyByLogicalProjectKey[logicalProjectKey] = threadKey;
|
|
const existingDraftThread = draftThreadsByThreadKey[threadKey];
|
|
if (parsedThreadRef) {
|
|
environmentIdByThreadId.set(parsedThreadRef.threadId, parsedThreadRef.environmentId);
|
|
}
|
|
// Logical project keys may contain a workspace path after the
|
|
// environment prefix. When the persisted draft already names that
|
|
// logical key, its concrete project id remains authoritative.
|
|
if (existingDraftThread?.logicalProjectKey === logicalProjectKey) {
|
|
continue;
|
|
}
|
|
if (!projectRef) {
|
|
if (existingDraftThread) {
|
|
draftThreadsByThreadKey[threadKey] = {
|
|
...existingDraftThread,
|
|
logicalProjectKey,
|
|
};
|
|
}
|
|
continue;
|
|
}
|
|
if (!existingDraftThread) {
|
|
draftThreadsByThreadKey[threadKey] = {
|
|
threadId: parsedThreadRef?.threadId ?? (threadKey as ThreadId),
|
|
environmentId: projectRef.environmentId,
|
|
projectId: projectRef.projectId,
|
|
logicalProjectKey,
|
|
createdAt: new Date().toISOString(),
|
|
runtimeMode: DEFAULT_RUNTIME_MODE,
|
|
interactionMode: DEFAULT_INTERACTION_MODE,
|
|
branch: null,
|
|
worktreePath: null,
|
|
envMode: "local",
|
|
startFromOrigin: false,
|
|
promotedTo: null,
|
|
};
|
|
} else if (
|
|
existingDraftThread.projectId !== projectRef.projectId ||
|
|
existingDraftThread.environmentId !== projectRef.environmentId
|
|
) {
|
|
draftThreadsByThreadKey[threadKey] = {
|
|
...existingDraftThread,
|
|
threadId: existingDraftThread.threadId,
|
|
environmentId: projectRef.environmentId,
|
|
projectId: projectRef.projectId,
|
|
logicalProjectKey,
|
|
};
|
|
}
|
|
}
|
|
}
|
|
|
|
return { draftThreadsByThreadKey, logicalProjectDraftThreadKeyByLogicalProjectKey };
|
|
}
|
|
|
|
function normalizePersistedDraftsByThreadId(
|
|
rawDraftMap: unknown,
|
|
draftThreadsByThreadKey: PersistedComposerDraftStoreState["draftThreadsByThreadKey"],
|
|
): PersistedComposerDraftStoreState["draftsByThreadKey"] {
|
|
if (!rawDraftMap || typeof rawDraftMap !== "object") {
|
|
return {};
|
|
}
|
|
|
|
const environmentIdByThreadId = new Map<ThreadId, EnvironmentId>();
|
|
for (const [threadKey, draftThread] of Object.entries(draftThreadsByThreadKey)) {
|
|
const parsedThreadRef = composerThreadRefFromKey(threadKey);
|
|
if (!parsedThreadRef) {
|
|
continue;
|
|
}
|
|
environmentIdByThreadId.set(
|
|
parsedThreadRef.threadId,
|
|
draftThread.environmentId as EnvironmentId,
|
|
);
|
|
}
|
|
|
|
const nextDraftsByThreadKey: DeepMutable<PersistedComposerDraftStoreState["draftsByThreadKey"]> =
|
|
{};
|
|
for (const [threadKeyOrId, draftValue] of Object.entries(
|
|
rawDraftMap as Record<string, unknown>,
|
|
)) {
|
|
if (typeof threadKeyOrId !== "string" || threadKeyOrId.length === 0) {
|
|
continue;
|
|
}
|
|
if (!draftValue || typeof draftValue !== "object") {
|
|
continue;
|
|
}
|
|
const draftCandidate = draftValue as PersistedComposerThreadDraftState;
|
|
const promptCandidate = typeof draftCandidate.prompt === "string" ? draftCandidate.prompt : "";
|
|
const attachments = Array.isArray(draftCandidate.attachments)
|
|
? draftCandidate.attachments.flatMap((entry) => {
|
|
const normalized = normalizePersistedAttachment(entry);
|
|
return normalized ? [normalized] : [];
|
|
})
|
|
: [];
|
|
const files = Array.isArray(draftCandidate.files)
|
|
? draftCandidate.files.filter(isPersistedComposerDraftFileAttachment)
|
|
: [];
|
|
const terminalContexts = Array.isArray(draftCandidate.terminalContexts)
|
|
? draftCandidate.terminalContexts.flatMap((entry) => {
|
|
const normalized = normalizePersistedTerminalContextDraft(entry);
|
|
return normalized ? [normalized] : [];
|
|
})
|
|
: [];
|
|
const elementContexts = Array.isArray(draftCandidate.elementContexts)
|
|
? draftCandidate.elementContexts.flatMap((entry) => {
|
|
const normalized = normalizePersistedElementContextDraft(entry);
|
|
return normalized ? [normalized] : [];
|
|
})
|
|
: [];
|
|
const reviewComments = Array.isArray(draftCandidate.reviewComments)
|
|
? draftCandidate.reviewComments.filter(isReviewCommentContext)
|
|
: [];
|
|
const runtimeMode = isRuntimeMode(draftCandidate.runtimeMode)
|
|
? draftCandidate.runtimeMode
|
|
: null;
|
|
const interactionMode =
|
|
draftCandidate.interactionMode === "plan" || draftCandidate.interactionMode === "default"
|
|
? draftCandidate.interactionMode
|
|
: null;
|
|
const prompt = ensureInlineTerminalContextPlaceholders(
|
|
promptCandidate,
|
|
terminalContexts.length,
|
|
);
|
|
// If the draft already has the v3 shape, use it directly
|
|
const legacyDraftCandidate = draftValue as LegacyPersistedComposerThreadDraftState;
|
|
let modelSelectionByProvider: Partial<Record<ProviderInstanceId, ModelSelection>> = {};
|
|
let activeProvider: ProviderInstanceId | null = null;
|
|
let modelSelectionExplicit: true | undefined = undefined;
|
|
|
|
if (
|
|
draftCandidate.modelSelectionByProvider &&
|
|
typeof draftCandidate.modelSelectionByProvider === "object"
|
|
) {
|
|
// v3 format
|
|
modelSelectionByProvider = draftCandidate.modelSelectionByProvider as Partial<
|
|
Record<ProviderInstanceId, ModelSelection>
|
|
>;
|
|
activeProvider = normalizeProviderInstanceId(draftCandidate.activeProvider);
|
|
modelSelectionExplicit = draftCandidate.modelSelectionExplicit === true ? true : undefined;
|
|
} else {
|
|
// v2 or legacy format: migrate
|
|
const normalizedModelOptions =
|
|
normalizeProviderModelOptions(
|
|
legacyDraftCandidate.modelOptions,
|
|
undefined,
|
|
legacyDraftCandidate,
|
|
) ?? null;
|
|
const normalizedModelSelection = normalizeModelSelection(
|
|
legacyDraftCandidate.modelSelection,
|
|
{
|
|
provider: legacyDraftCandidate.provider,
|
|
model: legacyDraftCandidate.model,
|
|
modelOptions: normalizedModelOptions ?? (legacyDraftCandidate.modelOptions as unknown),
|
|
legacyCodex: legacyDraftCandidate,
|
|
},
|
|
);
|
|
const mergedModelOptions = legacyMergeModelSelectionIntoProviderModelOptions(
|
|
normalizedModelSelection,
|
|
normalizedModelOptions,
|
|
);
|
|
const modelSelection = legacySyncModelSelectionOptions(
|
|
normalizedModelSelection,
|
|
mergedModelOptions,
|
|
);
|
|
modelSelectionByProvider = legacyToModelSelectionByProvider(
|
|
modelSelection,
|
|
mergedModelOptions,
|
|
);
|
|
activeProvider = modelSelection?.instanceId ?? null;
|
|
}
|
|
|
|
const hasModelData =
|
|
Object.keys(modelSelectionByProvider).length > 0 || activeProvider !== null;
|
|
if (
|
|
promptCandidate.length === 0 &&
|
|
attachments.length === 0 &&
|
|
files.length === 0 &&
|
|
terminalContexts.length === 0 &&
|
|
elementContexts.length === 0 &&
|
|
reviewComments.length === 0 &&
|
|
!hasModelData &&
|
|
!runtimeMode &&
|
|
!interactionMode
|
|
) {
|
|
continue;
|
|
}
|
|
const parsedThreadRef = parseScopedThreadKey(threadKeyOrId);
|
|
const normalizedThreadKey =
|
|
parsedThreadRef !== null
|
|
? normalizeLegacyComposerStorageKey(threadKeyOrId)
|
|
: draftThreadsByThreadKey[threadKeyOrId] !== undefined
|
|
? threadKeyOrId
|
|
: (() => {
|
|
const environmentId = environmentIdByThreadId.get(threadKeyOrId as ThreadId);
|
|
return environmentId
|
|
? normalizeLegacyComposerStorageKey(threadKeyOrId, { environmentId })
|
|
: threadKeyOrId;
|
|
})();
|
|
nextDraftsByThreadKey[normalizedThreadKey] = {
|
|
prompt,
|
|
attachments,
|
|
...(files.length > 0 ? { files } : {}),
|
|
...(terminalContexts.length > 0 ? { terminalContexts } : {}),
|
|
...(elementContexts.length > 0 ? { elementContexts } : {}),
|
|
...(reviewComments.length > 0 ? { reviewComments } : {}),
|
|
...(hasModelData
|
|
? {
|
|
modelSelectionByProvider: compactModelSelectionByProvider(modelSelectionByProvider),
|
|
activeProvider,
|
|
...(modelSelectionExplicit ? { modelSelectionExplicit: true } : {}),
|
|
}
|
|
: {}),
|
|
...(runtimeMode ? { runtimeMode } : {}),
|
|
...(interactionMode ? { interactionMode } : {}),
|
|
};
|
|
}
|
|
|
|
return nextDraftsByThreadKey;
|
|
}
|
|
|
|
function persistedComposerDraftHasUserContent(draft: PersistedComposerThreadDraftState): boolean {
|
|
return (
|
|
draft.prompt.trim().length > 0 ||
|
|
draft.attachments.length > 0 ||
|
|
(draft.files?.length ?? 0) > 0 ||
|
|
(draft.terminalContexts?.length ?? 0) > 0 ||
|
|
(draft.elementContexts?.length ?? 0) > 0 ||
|
|
(draft.previewAnnotations?.length ?? 0) > 0 ||
|
|
(draft.reviewComments?.length ?? 0) > 0
|
|
);
|
|
}
|
|
|
|
function stripLegacyModelSeedsFromEmptyDraftSessions(
|
|
draftsByThreadKey: PersistedComposerDraftStoreState["draftsByThreadKey"],
|
|
draftThreadsByThreadKey: PersistedComposerDraftStoreState["draftThreadsByThreadKey"],
|
|
): PersistedComposerDraftStoreState["draftsByThreadKey"] {
|
|
return Object.fromEntries(
|
|
Object.entries(draftsByThreadKey).flatMap(([threadKey, draft]) => {
|
|
if (
|
|
draftThreadsByThreadKey[threadKey] === undefined ||
|
|
draft.modelSelectionExplicit === true ||
|
|
persistedComposerDraftHasUserContent(draft)
|
|
) {
|
|
return [[threadKey, draft]];
|
|
}
|
|
|
|
const {
|
|
activeProvider: _activeProvider,
|
|
modelSelectionByProvider: _modelSelectionByProvider,
|
|
modelSelectionExplicit: _modelSelectionExplicit,
|
|
...retained
|
|
} = draft;
|
|
return retained.runtimeMode || retained.interactionMode ? [[threadKey, retained]] : [];
|
|
}),
|
|
);
|
|
}
|
|
|
|
function migratePersistedComposerDraftStoreState(
|
|
persistedState: unknown,
|
|
): PersistedComposerDraftStoreState {
|
|
const normalized = normalizeCurrentPersistedComposerDraftStoreState(persistedState);
|
|
return {
|
|
...normalized,
|
|
draftsByThreadKey: stripLegacyModelSeedsFromEmptyDraftSessions(
|
|
normalized.draftsByThreadKey,
|
|
normalized.draftThreadsByThreadKey,
|
|
),
|
|
};
|
|
}
|
|
|
|
/** Select the persisted draft fields when the storage write is ready to flush. */
|
|
export 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"]
|
|
> = {};
|
|
for (const [threadKey, draft] of Object.entries(state.draftsByThreadKey)) {
|
|
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 (
|
|
draft.prompt.length === 0 &&
|
|
draft.persistedAttachments.length === 0 &&
|
|
draft.files.length === 0 &&
|
|
draft.terminalContexts.length === 0 &&
|
|
draft.elementContexts.length === 0 &&
|
|
draft.previewAnnotations.length === 0 &&
|
|
draft.reviewComments.length === 0 &&
|
|
!hasModelData &&
|
|
draft.runtimeMode === null &&
|
|
draft.interactionMode === null
|
|
) {
|
|
continue;
|
|
}
|
|
const persistedDraft: DeepMutable<PersistedComposerThreadDraftState> = {
|
|
prompt: draft.prompt,
|
|
attachments: draft.persistedAttachments,
|
|
...(draft.files.length > 0
|
|
? {
|
|
// A file whose upload has not finished has no serializable bytes.
|
|
// It persists as a metadata-only marker so it can surface as a
|
|
// needs-reattach row after reload instead of silently vanishing.
|
|
files: draft.files.map((file) => ({
|
|
id: file.id,
|
|
name: file.name,
|
|
mimeType: file.mimeType,
|
|
sizeBytes: file.sizeBytes,
|
|
...(file.uploadedAttachmentId && file.uploadEnvironmentId
|
|
? {
|
|
attachmentId: file.uploadedAttachmentId,
|
|
environmentId: file.uploadEnvironmentId,
|
|
}
|
|
: {}),
|
|
})),
|
|
}
|
|
: {}),
|
|
...(draft.terminalContexts.length > 0
|
|
? {
|
|
terminalContexts: draft.terminalContexts.map((context) => ({
|
|
id: context.id,
|
|
threadId: context.threadId,
|
|
createdAt: context.createdAt,
|
|
terminalId: context.terminalId,
|
|
terminalLabel: context.terminalLabel,
|
|
lineStart: context.lineStart,
|
|
lineEnd: context.lineEnd,
|
|
})),
|
|
}
|
|
: {}),
|
|
...(draft.elementContexts.length > 0
|
|
? {
|
|
elementContexts: draft.elementContexts.map((context) => ({
|
|
id: context.id,
|
|
threadId: context.threadId,
|
|
pickedAt: context.pickedAt,
|
|
pageUrl: context.pageUrl,
|
|
pageTitle: context.pageTitle,
|
|
tagName: context.tagName,
|
|
selector: context.selector,
|
|
htmlPreview: context.htmlPreview,
|
|
componentName: context.componentName,
|
|
source: context.source,
|
|
styles: context.styles,
|
|
})),
|
|
}
|
|
: {}),
|
|
...(draft.previewAnnotations.length > 0
|
|
? {
|
|
previewAnnotations: draft.previewAnnotations.map(
|
|
(annotation) => ({ ...annotation }) as DeepMutable<PreviewAnnotationPayload>,
|
|
),
|
|
}
|
|
: {}),
|
|
...(draft.reviewComments.length > 0
|
|
? {
|
|
reviewComments: draft.reviewComments.map((comment) => ({ ...comment })),
|
|
}
|
|
: {}),
|
|
...(hasModelData
|
|
? {
|
|
modelSelectionByProvider: compactModelSelectionByProvider(
|
|
draft.modelSelectionByProvider,
|
|
),
|
|
activeProvider: draft.activeProvider,
|
|
...(draft.modelSelectionExplicit ? { modelSelectionExplicit: true } : {}),
|
|
}
|
|
: {}),
|
|
...(draft.runtimeMode ? { runtimeMode: draft.runtimeMode } : {}),
|
|
...(draft.interactionMode ? { interactionMode: draft.interactionMode } : {}),
|
|
};
|
|
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: persistedDraftThreadsByThreadKey,
|
|
logicalProjectDraftThreadKeyByLogicalProjectKey:
|
|
state.logicalProjectDraftThreadKeyByLogicalProjectKey,
|
|
stickyModelSelectionByProvider: compactModelSelectionByProvider(
|
|
state.stickyModelSelectionByProvider,
|
|
),
|
|
stickyActiveProvider: state.stickyActiveProvider,
|
|
};
|
|
}
|
|
|
|
function normalizeCurrentPersistedComposerDraftStoreState(
|
|
persistedState: unknown,
|
|
): PersistedComposerDraftStoreState {
|
|
if (!persistedState || typeof persistedState !== "object") {
|
|
return EMPTY_PERSISTED_DRAFT_STORE_STATE;
|
|
}
|
|
const normalizedPersistedState = persistedState as LegacyPersistedComposerDraftStoreState;
|
|
const { draftThreadsByThreadKey, logicalProjectDraftThreadKeyByLogicalProjectKey } =
|
|
normalizePersistedDraftThreads(
|
|
normalizedPersistedState.draftThreadsByThreadKey ??
|
|
normalizedPersistedState.draftThreadsByThreadId,
|
|
normalizedPersistedState.logicalProjectDraftThreadKeyByLogicalProjectKey ??
|
|
normalizedPersistedState.projectDraftThreadKeyByProjectKey ??
|
|
normalizedPersistedState.projectDraftThreadIdByProjectKey ??
|
|
normalizedPersistedState.projectDraftThreadIdByProjectId,
|
|
);
|
|
|
|
// Handle both v3 (modelSelectionByProvider) and v2/legacy formats
|
|
let stickyModelSelectionByProvider: Partial<Record<ProviderInstanceId, ModelSelection>> = {};
|
|
let stickyActiveProvider: ProviderInstanceId | null = null;
|
|
if (
|
|
normalizedPersistedState.stickyModelSelectionByProvider &&
|
|
typeof normalizedPersistedState.stickyModelSelectionByProvider === "object"
|
|
) {
|
|
stickyModelSelectionByProvider =
|
|
normalizedPersistedState.stickyModelSelectionByProvider as Partial<
|
|
Record<ProviderInstanceId, ModelSelection>
|
|
>;
|
|
stickyActiveProvider = normalizeProviderInstanceId(
|
|
normalizedPersistedState.stickyActiveProvider,
|
|
);
|
|
} else {
|
|
// Legacy migration path
|
|
const stickyModelOptions =
|
|
normalizeProviderModelOptions(normalizedPersistedState.stickyModelOptions) ?? {};
|
|
const normalizedStickyModelSelection = normalizeModelSelection(
|
|
normalizedPersistedState.stickyModelSelection,
|
|
{
|
|
provider: normalizedPersistedState.stickyProvider ?? "codex",
|
|
model: normalizedPersistedState.stickyModel,
|
|
modelOptions: stickyModelOptions,
|
|
},
|
|
);
|
|
const nextStickyModelOptions = legacyMergeModelSelectionIntoProviderModelOptions(
|
|
normalizedStickyModelSelection,
|
|
stickyModelOptions,
|
|
);
|
|
const stickyModelSelection = legacySyncModelSelectionOptions(
|
|
normalizedStickyModelSelection,
|
|
nextStickyModelOptions,
|
|
);
|
|
stickyModelSelectionByProvider = legacyToModelSelectionByProvider(
|
|
stickyModelSelection,
|
|
nextStickyModelOptions,
|
|
);
|
|
stickyActiveProvider = normalizeProviderInstanceId(normalizedPersistedState.stickyProvider);
|
|
}
|
|
|
|
return {
|
|
draftsByThreadKey: normalizePersistedDraftsByThreadId(
|
|
normalizedPersistedState.draftsByThreadKey ?? normalizedPersistedState.draftsByThreadId,
|
|
draftThreadsByThreadKey,
|
|
),
|
|
draftThreadsByThreadKey,
|
|
logicalProjectDraftThreadKeyByLogicalProjectKey,
|
|
stickyModelSelectionByProvider: compactModelSelectionByProvider(stickyModelSelectionByProvider),
|
|
stickyActiveProvider,
|
|
};
|
|
}
|
|
|
|
function readPersistedAttachmentIdsFromStorage(threadKey: string): string[] {
|
|
if (threadKey.length === 0) {
|
|
return [];
|
|
}
|
|
try {
|
|
const persisted = getLocalStorageItem(
|
|
COMPOSER_DRAFT_STORAGE_KEY,
|
|
PersistedComposerDraftStoreStorage,
|
|
);
|
|
if (!persisted || persisted.version !== COMPOSER_DRAFT_STORAGE_VERSION) {
|
|
return [];
|
|
}
|
|
return (persisted.state.draftsByThreadKey[threadKey]?.attachments ?? []).map(
|
|
(attachment) => attachment.id,
|
|
);
|
|
} catch {
|
|
return [];
|
|
}
|
|
}
|
|
|
|
function verifyPersistedAttachments(
|
|
threadKey: string,
|
|
attachments: PersistedComposerImageAttachment[],
|
|
set: (
|
|
partial:
|
|
| ComposerDraftStoreState
|
|
| Partial<ComposerDraftStoreState>
|
|
| ((
|
|
state: ComposerDraftStoreState,
|
|
) => ComposerDraftStoreState | Partial<ComposerDraftStoreState>),
|
|
replace?: false,
|
|
) => void,
|
|
): void {
|
|
let persistedIdSet = new Set<string>();
|
|
try {
|
|
composerDebouncedStorage.flush();
|
|
persistedIdSet = new Set(readPersistedAttachmentIdsFromStorage(threadKey));
|
|
} catch {
|
|
persistedIdSet = new Set();
|
|
}
|
|
set((state) => {
|
|
const current = state.draftsByThreadKey[threadKey];
|
|
if (!current) {
|
|
return state;
|
|
}
|
|
const imageIdSet = new Set(current.images.map((image) => image.id));
|
|
const persistedAttachments = attachments.filter(
|
|
(attachment) => imageIdSet.has(attachment.id) && persistedIdSet.has(attachment.id),
|
|
);
|
|
const nonPersistedImageIds: string[] = [];
|
|
for (const image of current.images) {
|
|
if (!persistedIdSet.has(image.id)) {
|
|
nonPersistedImageIds.push(image.id);
|
|
}
|
|
}
|
|
const nextDraft: ComposerThreadDraftState = {
|
|
...current,
|
|
persistedAttachments,
|
|
nonPersistedImageIds,
|
|
};
|
|
const nextDraftsByThreadKey = { ...state.draftsByThreadKey };
|
|
if (shouldRemoveDraft(nextDraft)) {
|
|
delete nextDraftsByThreadKey[threadKey];
|
|
} else {
|
|
nextDraftsByThreadKey[threadKey] = nextDraft;
|
|
}
|
|
return { draftsByThreadKey: nextDraftsByThreadKey };
|
|
});
|
|
}
|
|
|
|
function hydratePersistedComposerImageAttachment(
|
|
attachment: PersistedComposerImageAttachment,
|
|
): File | null {
|
|
const commaIndex = attachment.dataUrl.indexOf(",");
|
|
const header = commaIndex === -1 ? attachment.dataUrl : attachment.dataUrl.slice(0, commaIndex);
|
|
const payload = commaIndex === -1 ? "" : attachment.dataUrl.slice(commaIndex + 1);
|
|
if (payload.length === 0) {
|
|
return null;
|
|
}
|
|
try {
|
|
const isBase64 = header.includes(";base64");
|
|
if (!isBase64) {
|
|
const decodedText = decodeURIComponent(payload);
|
|
const inferredMimeType =
|
|
header.startsWith("data:") && header.includes(";")
|
|
? header.slice("data:".length, header.indexOf(";"))
|
|
: attachment.mimeType;
|
|
return new File([decodedText], attachment.name, {
|
|
type: inferredMimeType || attachment.mimeType,
|
|
});
|
|
}
|
|
const binary = atob(payload);
|
|
const bytes = new Uint8Array(binary.length);
|
|
for (let index = 0; index < binary.length; index += 1) {
|
|
bytes[index] = binary.charCodeAt(index);
|
|
}
|
|
return new File([bytes], attachment.name, { type: attachment.mimeType });
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
export function hydrateImagesFromPersisted(
|
|
attachments: ReadonlyArray<PersistedComposerImageAttachment>,
|
|
): ComposerImageAttachment[] {
|
|
return attachments.flatMap((attachment) => {
|
|
const file = hydratePersistedComposerImageAttachment(attachment);
|
|
if (!file) return [];
|
|
|
|
return [
|
|
{
|
|
type: "image" as const,
|
|
id: attachment.id,
|
|
name: attachment.name,
|
|
mimeType: attachment.mimeType,
|
|
sizeBytes: attachment.sizeBytes,
|
|
previewUrl: attachment.dataUrl,
|
|
file,
|
|
} satisfies ComposerImageAttachment,
|
|
];
|
|
});
|
|
}
|
|
|
|
function toHydratedThreadDraft(
|
|
persistedDraft: PersistedComposerThreadDraftState,
|
|
): ComposerThreadDraftState {
|
|
// The persisted draft is already in v3 shape (migration handles older formats)
|
|
const modelSelectionByProvider: Partial<Record<ProviderInstanceId, ModelSelection>> =
|
|
persistedDraft.modelSelectionByProvider ?? {};
|
|
const activeProvider = normalizeProviderInstanceId(persistedDraft.activeProvider) ?? null;
|
|
|
|
return {
|
|
prompt: persistedDraft.prompt,
|
|
images: hydrateImagesFromPersisted(persistedDraft.attachments),
|
|
files:
|
|
persistedDraft.files?.map((file) => ({
|
|
type: "file" as const,
|
|
id: file.id,
|
|
name: file.name,
|
|
mimeType: file.mimeType,
|
|
sizeBytes: file.sizeBytes,
|
|
file: null,
|
|
// A marker without an attachment id hydrates as needs-reattach: no
|
|
// bytes, no server-side upload, only the metadata to tell the user
|
|
// what to attach again.
|
|
...(file.attachmentId !== undefined && file.environmentId !== undefined
|
|
? { uploadedAttachmentId: file.attachmentId, uploadEnvironmentId: file.environmentId }
|
|
: {}),
|
|
})) ?? [],
|
|
nonPersistedImageIds: [],
|
|
persistedAttachments: [...persistedDraft.attachments],
|
|
terminalContexts:
|
|
persistedDraft.terminalContexts?.map((context) => ({
|
|
...context,
|
|
text: "",
|
|
})) ?? [],
|
|
elementContexts:
|
|
persistedDraft.elementContexts?.map((context) => ({
|
|
...context,
|
|
})) ?? [],
|
|
previewAnnotations:
|
|
persistedDraft.previewAnnotations?.map((annotation) => ({ ...annotation })) ?? [],
|
|
reviewComments: persistedDraft.reviewComments?.map((comment) => ({ ...comment })) ?? [],
|
|
modelSelectionByProvider,
|
|
activeProvider,
|
|
...(persistedDraft.modelSelectionExplicit ? { modelSelectionExplicit: true } : {}),
|
|
runtimeMode: persistedDraft.runtimeMode ?? null,
|
|
interactionMode: persistedDraft.interactionMode ?? null,
|
|
};
|
|
}
|
|
|
|
function toHydratedDraftThreadState(
|
|
persistedDraftThread: PersistedDraftThreadState,
|
|
): DraftThreadState {
|
|
return {
|
|
threadId: persistedDraftThread.threadId,
|
|
environmentId: persistedDraftThread.environmentId as EnvironmentId,
|
|
projectId: persistedDraftThread.projectId,
|
|
logicalProjectKey:
|
|
persistedDraftThread.logicalProjectKey ??
|
|
projectDraftKey(
|
|
scopeProjectRef(
|
|
persistedDraftThread.environmentId as EnvironmentId,
|
|
persistedDraftThread.projectId,
|
|
),
|
|
),
|
|
createdAt: persistedDraftThread.createdAt,
|
|
runtimeMode: persistedDraftThread.runtimeMode,
|
|
interactionMode: persistedDraftThread.interactionMode,
|
|
branch: persistedDraftThread.branch,
|
|
worktreePath: persistedDraftThread.worktreePath,
|
|
envMode: persistedDraftThread.envMode,
|
|
startFromOrigin: persistedDraftThread.startFromOrigin,
|
|
...(persistedDraftThread.environmentSelection
|
|
? { environmentSelection: persistedDraftThread.environmentSelection }
|
|
: {}),
|
|
...(persistedDraftThread.loadBalancedEnvironmentId !== undefined
|
|
? {
|
|
loadBalancedEnvironmentId:
|
|
persistedDraftThread.loadBalancedEnvironmentId as EnvironmentId | null,
|
|
}
|
|
: {}),
|
|
promotedTo: persistedDraftThread.promotedTo
|
|
? scopeThreadRef(
|
|
persistedDraftThread.promotedTo.environmentId as EnvironmentId,
|
|
persistedDraftThread.promotedTo.threadId as ThreadId,
|
|
)
|
|
: null,
|
|
};
|
|
}
|
|
|
|
const composerDraftStore = create<ComposerDraftStoreState>()(
|
|
persist(
|
|
(setBase, get) => {
|
|
const set = setBase;
|
|
|
|
return {
|
|
draftsByThreadKey: {},
|
|
draftThreadsByThreadKey: {},
|
|
logicalProjectDraftThreadKeyByLogicalProjectKey: {},
|
|
backgroundSubmissionThreadKeys: {},
|
|
stickyModelSelectionByProvider: {},
|
|
stickyActiveProvider: null,
|
|
getComposerDraft: (target) => getComposerDraftState(get(), target),
|
|
getDraftThreadByLogicalProjectKey: (logicalProjectKey) => {
|
|
return get().getDraftSessionByLogicalProjectKey(logicalProjectKey);
|
|
},
|
|
getDraftSessionByLogicalProjectKey: (logicalProjectKey) => {
|
|
const normalizedLogicalProjectKey = logicalProjectDraftKey(logicalProjectKey);
|
|
if (normalizedLogicalProjectKey.length === 0) {
|
|
return null;
|
|
}
|
|
const draftId =
|
|
get().logicalProjectDraftThreadKeyByLogicalProjectKey[normalizedLogicalProjectKey];
|
|
if (!draftId) {
|
|
return null;
|
|
}
|
|
const draftThread = get().draftThreadsByThreadKey[draftId];
|
|
if (!draftThread || isDraftThreadPromoting(draftThread)) {
|
|
return null;
|
|
}
|
|
return toProjectDraftSession(DraftId.make(draftId), draftThread);
|
|
},
|
|
getDraftThreadByProjectRef: (projectRef) => {
|
|
return get().getDraftSessionByProjectRef(projectRef);
|
|
},
|
|
getDraftSessionByProjectRef: (projectRef) => {
|
|
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;
|
|
}
|
|
if (
|
|
draftThread.projectId === projectRef.projectId &&
|
|
draftThread.environmentId === projectRef.environmentId
|
|
) {
|
|
return toProjectDraftSession(DraftId.make(draftId), draftThread);
|
|
}
|
|
}
|
|
return null;
|
|
},
|
|
getDraftSession: (draftId) => get().draftThreadsByThreadKey[draftId] ?? null,
|
|
getDraftSessionByRef: (threadRef) => {
|
|
for (const draftSession of Object.values(get().draftThreadsByThreadKey)) {
|
|
if (
|
|
draftSession.environmentId === threadRef.environmentId &&
|
|
draftSession.threadId === threadRef.threadId
|
|
) {
|
|
return draftSession;
|
|
}
|
|
}
|
|
return null;
|
|
},
|
|
getDraftThread: (threadRef) => {
|
|
if (typeof threadRef === "string") {
|
|
return get().getDraftSession(DraftId.make(threadRef));
|
|
}
|
|
return get().getDraftSessionByRef(threadRef);
|
|
},
|
|
getDraftThreadByRef: (threadRef) => {
|
|
return get().getDraftSessionByRef(threadRef);
|
|
},
|
|
listDraftThreadKeys: () =>
|
|
Object.values(get().draftThreadsByThreadKey).map((draftThread) =>
|
|
scopedThreadKey(scopeThreadRef(draftThread.environmentId, draftThread.threadId)),
|
|
),
|
|
hasDraftThreadsInEnvironment: (environmentId) =>
|
|
Object.values(get().draftThreadsByThreadKey).some(
|
|
(draftThread) => draftThread.environmentId === environmentId,
|
|
),
|
|
setLogicalProjectDraftThreadId: (logicalProjectKey, projectRef, draftId, options) => {
|
|
const normalizedLogicalProjectKey = logicalProjectDraftKey(logicalProjectKey);
|
|
if (normalizedLogicalProjectKey.length === 0 || draftId.length === 0) {
|
|
return;
|
|
}
|
|
set((state) => {
|
|
const existingThread = state.draftThreadsByThreadKey[draftId];
|
|
const previousThreadKeyForLogicalProject =
|
|
state.logicalProjectDraftThreadKeyByLogicalProjectKey[normalizedLogicalProjectKey];
|
|
const nextDraftThread = createDraftThreadState(
|
|
projectRef,
|
|
options?.threadId ?? existingThread?.threadId ?? ThreadId.make(draftId),
|
|
normalizedLogicalProjectKey,
|
|
existingThread,
|
|
options,
|
|
);
|
|
const hasSameLogicalMapping = previousThreadKeyForLogicalProject === draftId;
|
|
const hasNoStaleMappingsForDraft = Object.entries(
|
|
state.logicalProjectDraftThreadKeyByLogicalProjectKey,
|
|
).every(
|
|
([logicalKey, mappedDraftId]) =>
|
|
mappedDraftId !== draftId || logicalKey === normalizedLogicalProjectKey,
|
|
);
|
|
if (
|
|
hasSameLogicalMapping &&
|
|
hasNoStaleMappingsForDraft &&
|
|
draftThreadsEqual(existingThread, nextDraftThread)
|
|
) {
|
|
return state;
|
|
}
|
|
// A draft session belongs to one logical project at a time. When
|
|
// an open draft is retargeted in place, remove any old mapping
|
|
// for that same draft so the previous project cannot resolve it.
|
|
const nextLogicalProjectDraftThreadKeyByLogicalProjectKey: Record<string, string> =
|
|
Object.fromEntries(
|
|
Object.entries(state.logicalProjectDraftThreadKeyByLogicalProjectKey).filter(
|
|
([logicalKey, mappedDraftId]) =>
|
|
mappedDraftId !== draftId || logicalKey === normalizedLogicalProjectKey,
|
|
),
|
|
);
|
|
nextLogicalProjectDraftThreadKeyByLogicalProjectKey[normalizedLogicalProjectKey] =
|
|
draftId;
|
|
const nextDraftThreadsByThreadKey: Record<string, DraftThreadState> = {
|
|
...state.draftThreadsByThreadKey,
|
|
[draftId]: nextDraftThread,
|
|
};
|
|
const existingDraft = state.draftsByThreadKey[draftId];
|
|
let nextDraftsByThreadKey = state.draftsByThreadKey;
|
|
if (
|
|
existingThread &&
|
|
existingThread.environmentId !== projectRef.environmentId &&
|
|
existingDraft !== undefined
|
|
) {
|
|
const nextDraft = clearStaleFileUploadMetadata(
|
|
existingDraft,
|
|
projectRef.environmentId,
|
|
);
|
|
if (nextDraft !== existingDraft) {
|
|
nextDraftsByThreadKey = {
|
|
...state.draftsByThreadKey,
|
|
[draftId]: nextDraft,
|
|
};
|
|
}
|
|
}
|
|
const previousDraftThread =
|
|
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 &&
|
|
!isComposerThreadKeyInUse(
|
|
nextLogicalProjectDraftThreadKeyByLogicalProjectKey,
|
|
previousThreadKeyForLogicalProject,
|
|
) &&
|
|
!isDraftThreadPromoting(previousDraftThread) &&
|
|
!composerDraftHasUserContent(
|
|
state.draftsByThreadKey[previousThreadKeyForLogicalProject],
|
|
)
|
|
) {
|
|
delete nextDraftThreadsByThreadKey[previousThreadKeyForLogicalProject];
|
|
if (state.draftsByThreadKey[previousThreadKeyForLogicalProject] !== undefined) {
|
|
nextDraftsByThreadKey = { ...nextDraftsByThreadKey };
|
|
delete nextDraftsByThreadKey[previousThreadKeyForLogicalProject];
|
|
}
|
|
}
|
|
return {
|
|
draftsByThreadKey: nextDraftsByThreadKey,
|
|
draftThreadsByThreadKey: nextDraftThreadsByThreadKey,
|
|
logicalProjectDraftThreadKeyByLogicalProjectKey:
|
|
nextLogicalProjectDraftThreadKeyByLogicalProjectKey,
|
|
};
|
|
});
|
|
},
|
|
setProjectDraftThreadId: (projectRef, draftId, options) => {
|
|
get().setLogicalProjectDraftThreadId(
|
|
projectDraftKey(projectRef),
|
|
projectRef,
|
|
draftId,
|
|
options,
|
|
);
|
|
},
|
|
setDraftThreadContext: (threadRef, options) => {
|
|
const threadKey = resolveComposerDraftKey(get(), threadRef) ?? "";
|
|
if (threadKey.length === 0) {
|
|
return;
|
|
}
|
|
set((state) => {
|
|
const existing = state.draftThreadsByThreadKey[threadKey];
|
|
if (!existing) {
|
|
return state;
|
|
}
|
|
const nextProjectRef = options.projectRef ?? {
|
|
environmentId: existing.environmentId,
|
|
projectId: existing.projectId,
|
|
};
|
|
if (
|
|
nextProjectRef.projectId.length === 0 ||
|
|
nextProjectRef.environmentId.length === 0
|
|
) {
|
|
return state;
|
|
}
|
|
// Mirrors createDraftThreadState: a project/environment change
|
|
// drops machine-specific context (branch, worktree path) but
|
|
// keeps the user's env mode and start-from-origin intent.
|
|
const projectChanged =
|
|
nextProjectRef.environmentId !== existing.environmentId ||
|
|
nextProjectRef.projectId !== existing.projectId;
|
|
const nextWorktreePath =
|
|
options.worktreePath === undefined
|
|
? projectChanged
|
|
? null
|
|
: existing.worktreePath
|
|
: (options.worktreePath ?? null);
|
|
const nextBranch =
|
|
options.branch === undefined
|
|
? projectChanged
|
|
? null
|
|
: existing.branch
|
|
: (options.branch ?? null);
|
|
const nextStartFromOrigin =
|
|
options.startFromOrigin === undefined
|
|
? existing.startFromOrigin
|
|
: options.startFromOrigin;
|
|
const environmentSelection =
|
|
options.environmentSelection ??
|
|
(options.branch != null || options.worktreePath != null
|
|
? "manual"
|
|
: existing.environmentSelection);
|
|
const nextDraftThread: DraftThreadState = {
|
|
threadId: existing.threadId,
|
|
environmentId: nextProjectRef.environmentId,
|
|
projectId: nextProjectRef.projectId,
|
|
logicalProjectKey: existing.logicalProjectKey,
|
|
...(environmentSelection ? { environmentSelection } : {}),
|
|
loadBalancedEnvironmentId:
|
|
options.loadBalancedEnvironmentId === undefined
|
|
? projectChanged
|
|
? null
|
|
: (existing.loadBalancedEnvironmentId ?? null)
|
|
: options.loadBalancedEnvironmentId,
|
|
createdAt:
|
|
options.createdAt === undefined
|
|
? existing.createdAt
|
|
: options.createdAt || existing.createdAt,
|
|
runtimeMode: options.runtimeMode ?? existing.runtimeMode,
|
|
interactionMode: options.interactionMode ?? existing.interactionMode,
|
|
branch: nextBranch,
|
|
worktreePath: nextWorktreePath,
|
|
envMode:
|
|
options.envMode ?? (nextWorktreePath ? "worktree" : (existing.envMode ?? "local")),
|
|
startFromOrigin: nextStartFromOrigin,
|
|
promotedTo: existing.promotedTo ?? null,
|
|
};
|
|
const isUnchanged =
|
|
nextDraftThread.environmentId === existing.environmentId &&
|
|
nextDraftThread.projectId === existing.projectId &&
|
|
nextDraftThread.logicalProjectKey === existing.logicalProjectKey &&
|
|
nextDraftThread.environmentSelection === existing.environmentSelection &&
|
|
nextDraftThread.loadBalancedEnvironmentId === existing.loadBalancedEnvironmentId &&
|
|
nextDraftThread.createdAt === existing.createdAt &&
|
|
nextDraftThread.runtimeMode === existing.runtimeMode &&
|
|
nextDraftThread.interactionMode === existing.interactionMode &&
|
|
nextDraftThread.branch === existing.branch &&
|
|
nextDraftThread.worktreePath === existing.worktreePath &&
|
|
nextDraftThread.envMode === existing.envMode &&
|
|
nextDraftThread.startFromOrigin === existing.startFromOrigin &&
|
|
scopedThreadRefsEqual(nextDraftThread.promotedTo, existing.promotedTo);
|
|
if (isUnchanged) {
|
|
return state;
|
|
}
|
|
return {
|
|
draftThreadsByThreadKey: {
|
|
...state.draftThreadsByThreadKey,
|
|
[threadKey]: nextDraftThread,
|
|
},
|
|
};
|
|
});
|
|
},
|
|
clearProjectDraftThreadId: (projectRef) => {
|
|
set((state) => {
|
|
// 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;
|
|
}
|
|
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) => {
|
|
const threadKey = resolveComposerDraftKey(get(), threadRef) ?? "";
|
|
if (threadKey.length === 0) {
|
|
return;
|
|
}
|
|
set((state) => {
|
|
const draftThread = state.draftThreadsByThreadKey[threadKey];
|
|
if (
|
|
!draftThread ||
|
|
draftThread.projectId !== projectRef.projectId ||
|
|
draftThread.environmentId !== projectRef.environmentId
|
|
) {
|
|
return state;
|
|
}
|
|
return removeDraftThreadReferences(state, threadKey);
|
|
});
|
|
},
|
|
markDraftThreadPromoting: (threadRef, promotedTo) => {
|
|
const threadKey = resolveComposerDraftKey(get(), threadRef);
|
|
if (!threadKey) {
|
|
return;
|
|
}
|
|
set((state) => {
|
|
const existing = state.draftThreadsByThreadKey[threadKey];
|
|
if (!existing) {
|
|
return state;
|
|
}
|
|
const nextPromotedTo =
|
|
promotedTo ?? scopeThreadRef(existing.environmentId, existing.threadId);
|
|
if (scopedThreadRefsEqual(existing.promotedTo, nextPromotedTo)) {
|
|
return state;
|
|
}
|
|
return {
|
|
draftThreadsByThreadKey: {
|
|
...state.draftThreadsByThreadKey,
|
|
[threadKey]: {
|
|
...existing,
|
|
promotedTo: nextPromotedTo,
|
|
},
|
|
},
|
|
};
|
|
});
|
|
},
|
|
finalizePromotedDraftThread: (threadRef) => {
|
|
const threadKey = resolveComposerDraftKey(get(), threadRef) ?? "";
|
|
if (threadKey.length === 0) {
|
|
return;
|
|
}
|
|
set((state) => {
|
|
const existing = state.draftThreadsByThreadKey[threadKey];
|
|
if (!existing || !isDraftThreadPromoting(existing)) {
|
|
return state;
|
|
}
|
|
return removeDraftThreadReferences(state, threadKey, existing.promotedTo ?? undefined);
|
|
});
|
|
},
|
|
clearDraftThread: (threadRef) => {
|
|
const threadKey = resolveComposerDraftKey(get(), threadRef) ?? "";
|
|
if (threadKey.length === 0) {
|
|
return;
|
|
}
|
|
set((state) => {
|
|
const hasDraftThread = state.draftThreadsByThreadKey[threadKey] !== undefined;
|
|
const hasLogicalProjectMapping = Object.values(
|
|
state.logicalProjectDraftThreadKeyByLogicalProjectKey,
|
|
).includes(threadKey);
|
|
const hasComposerDraft = state.draftsByThreadKey[threadKey] !== undefined;
|
|
if (!hasDraftThread && !hasLogicalProjectMapping && !hasComposerDraft) {
|
|
return state;
|
|
}
|
|
return removeDraftThreadReferences(state, threadKey);
|
|
});
|
|
},
|
|
setStickyModelSelection: (modelSelection) => {
|
|
const normalized = normalizeModelSelection(modelSelection);
|
|
set((state) => {
|
|
if (!normalized) {
|
|
return state;
|
|
}
|
|
const nextMap: Partial<Record<ProviderInstanceId, ModelSelection>> = {
|
|
...state.stickyModelSelectionByProvider,
|
|
[normalized.instanceId]: normalized,
|
|
};
|
|
if (Equal.equals(state.stickyModelSelectionByProvider, nextMap)) {
|
|
return state.stickyActiveProvider === normalized.instanceId
|
|
? state
|
|
: { stickyActiveProvider: normalized.instanceId };
|
|
}
|
|
return {
|
|
stickyModelSelectionByProvider: nextMap,
|
|
stickyActiveProvider: normalized.instanceId,
|
|
};
|
|
});
|
|
},
|
|
applyStickyState: (threadRef) => {
|
|
const threadKey = resolveComposerDraftKey(get(), threadRef) ?? "";
|
|
if (threadKey.length === 0) {
|
|
return;
|
|
}
|
|
set((state) => {
|
|
const stickyMap = state.stickyModelSelectionByProvider;
|
|
const stickyActiveProvider = state.stickyActiveProvider;
|
|
const existing = state.draftsByThreadKey[threadKey];
|
|
const base = existing ?? createEmptyThreadDraft();
|
|
const nextMap = compactModelSelectionByProvider(stickyMap);
|
|
if (
|
|
Equal.equals(base.modelSelectionByProvider, nextMap) &&
|
|
base.activeProvider === stickyActiveProvider &&
|
|
base.modelSelectionExplicit === undefined
|
|
) {
|
|
return state;
|
|
}
|
|
const { modelSelectionExplicit: _modelSelectionExplicit, ...retained } = base;
|
|
const nextDraft: ComposerThreadDraftState = {
|
|
...retained,
|
|
modelSelectionByProvider: nextMap,
|
|
activeProvider: stickyActiveProvider,
|
|
};
|
|
const nextDraftsByThreadKey = { ...state.draftsByThreadKey };
|
|
if (shouldRemoveDraft(nextDraft)) {
|
|
delete nextDraftsByThreadKey[threadKey];
|
|
} else {
|
|
nextDraftsByThreadKey[threadKey] = nextDraft;
|
|
}
|
|
return { draftsByThreadKey: nextDraftsByThreadKey };
|
|
});
|
|
},
|
|
setPrompt: (threadRef, prompt) => {
|
|
const threadKey = resolveComposerDraftKey(get(), threadRef) ?? "";
|
|
if (threadKey.length === 0) {
|
|
return;
|
|
}
|
|
set((state) => {
|
|
const existing = state.draftsByThreadKey[threadKey] ?? createEmptyThreadDraft();
|
|
const nextDraft: ComposerThreadDraftState = {
|
|
...existing,
|
|
prompt,
|
|
};
|
|
const nextDraftsByThreadKey = { ...state.draftsByThreadKey };
|
|
if (shouldRemoveDraft(nextDraft)) {
|
|
delete nextDraftsByThreadKey[threadKey];
|
|
} else {
|
|
nextDraftsByThreadKey[threadKey] = nextDraft;
|
|
}
|
|
return { draftsByThreadKey: nextDraftsByThreadKey };
|
|
});
|
|
},
|
|
setTerminalContexts: (threadRef, contexts) => {
|
|
const threadKey = resolveComposerDraftKey(get(), threadRef);
|
|
const threadId = resolveComposerThreadId(get(), threadRef);
|
|
if (!threadKey || !threadId) {
|
|
return;
|
|
}
|
|
const normalizedContexts = normalizeTerminalContextsForThread(threadId, contexts);
|
|
set((state) => {
|
|
const existing = state.draftsByThreadKey[threadKey] ?? createEmptyThreadDraft();
|
|
const nextDraft: ComposerThreadDraftState = {
|
|
...existing,
|
|
prompt: ensureInlineTerminalContextPlaceholders(
|
|
existing.prompt,
|
|
normalizedContexts.length,
|
|
),
|
|
terminalContexts: normalizedContexts,
|
|
};
|
|
const nextDraftsByThreadKey = { ...state.draftsByThreadKey };
|
|
if (shouldRemoveDraft(nextDraft)) {
|
|
delete nextDraftsByThreadKey[threadKey];
|
|
} else {
|
|
nextDraftsByThreadKey[threadKey] = nextDraft;
|
|
}
|
|
return { draftsByThreadKey: nextDraftsByThreadKey };
|
|
});
|
|
},
|
|
setModelSelection: (threadRef, modelSelection, opts) => {
|
|
const threadKey = resolveComposerDraftKey(get(), threadRef) ?? "";
|
|
if (threadKey.length === 0) {
|
|
return;
|
|
}
|
|
const normalized = normalizeModelSelection(modelSelection);
|
|
set((state) => {
|
|
const existing = state.draftsByThreadKey[threadKey];
|
|
if (!existing && normalized === null) {
|
|
return state;
|
|
}
|
|
const base = existing ?? createEmptyThreadDraft();
|
|
const nextMap = { ...base.modelSelectionByProvider };
|
|
if (normalized) {
|
|
const current = nextMap[normalized.instanceId];
|
|
if (normalized.options !== undefined || opts?.replaceOptions) {
|
|
// Explicit options provided (or the caller passed a complete
|
|
// snapshot whose absent options mean "no options") → use the
|
|
// selection as-is.
|
|
nextMap[normalized.instanceId] = normalized as ModelSelection;
|
|
} else {
|
|
// No options in selection → preserve existing options, update provider+model
|
|
nextMap[normalized.instanceId] = createModelSelection(
|
|
normalized.instanceId,
|
|
normalized.model,
|
|
current?.options,
|
|
);
|
|
}
|
|
}
|
|
const nextActiveProvider = normalized?.instanceId ?? base.activeProvider;
|
|
if (
|
|
Equal.equals(base.modelSelectionByProvider, nextMap) &&
|
|
base.activeProvider === nextActiveProvider &&
|
|
(base.modelSelectionExplicit ?? false) === (opts?.explicit === true)
|
|
) {
|
|
return state;
|
|
}
|
|
// Last writer defines intent: picker writes mark the selection
|
|
// explicit; seeding writes leave it unset so future seeds can
|
|
// replace it.
|
|
const { modelSelectionExplicit: _previousExplicit, ...restBase } = base;
|
|
const nextDraft: ComposerThreadDraftState = {
|
|
...restBase,
|
|
modelSelectionByProvider: nextMap,
|
|
activeProvider: nextActiveProvider,
|
|
...(opts?.explicit === true ? { modelSelectionExplicit: true as const } : {}),
|
|
};
|
|
const nextDraftsByThreadKey = { ...state.draftsByThreadKey };
|
|
if (shouldRemoveDraft(nextDraft)) {
|
|
delete nextDraftsByThreadKey[threadKey];
|
|
} else {
|
|
nextDraftsByThreadKey[threadKey] = nextDraft;
|
|
}
|
|
return { draftsByThreadKey: nextDraftsByThreadKey };
|
|
});
|
|
},
|
|
setModelOptions: (threadRef, modelOptions) => {
|
|
const threadKey = resolveComposerDraftKey(get(), threadRef) ?? "";
|
|
if (threadKey.length === 0) {
|
|
return;
|
|
}
|
|
set((state) => {
|
|
const existing = state.draftsByThreadKey[threadKey];
|
|
if (!existing && (!modelOptions || Object.keys(modelOptions).length === 0)) {
|
|
return state;
|
|
}
|
|
const base = existing ?? createEmptyThreadDraft();
|
|
const nextMap = { ...base.modelSelectionByProvider };
|
|
for (const provider of ["codex", "claudeAgent", "cursor", "opencode"] as const) {
|
|
if (!modelOptions || !(provider in modelOptions)) continue;
|
|
const opts = modelOptions[provider];
|
|
const driverKind = ProviderDriverKind.make(provider);
|
|
const instanceKey = defaultInstanceIdForDriver(driverKind);
|
|
const current = nextMap[instanceKey];
|
|
if (opts && opts.length > 0) {
|
|
nextMap[instanceKey] = createModelSelection(
|
|
instanceKey,
|
|
current?.model ?? DEFAULT_MODEL_BY_PROVIDER[driverKind] ?? DEFAULT_MODEL,
|
|
opts,
|
|
);
|
|
} else if (current?.options) {
|
|
const { options: _, ...rest } = current;
|
|
nextMap[instanceKey] = rest as ModelSelection;
|
|
}
|
|
}
|
|
if (Equal.equals(base.modelSelectionByProvider, nextMap)) {
|
|
return state;
|
|
}
|
|
const nextDraft: ComposerThreadDraftState = {
|
|
...base,
|
|
modelSelectionByProvider: nextMap,
|
|
};
|
|
const nextDraftsByThreadKey = { ...state.draftsByThreadKey };
|
|
if (shouldRemoveDraft(nextDraft)) {
|
|
delete nextDraftsByThreadKey[threadKey];
|
|
} else {
|
|
nextDraftsByThreadKey[threadKey] = nextDraft;
|
|
}
|
|
return { draftsByThreadKey: nextDraftsByThreadKey };
|
|
});
|
|
},
|
|
setProviderModelOptions: (threadRef, provider, nextProviderOptions, options) => {
|
|
const threadKey = resolveComposerDraftKey(get(), threadRef) ?? "";
|
|
if (threadKey.length === 0) {
|
|
return;
|
|
}
|
|
const normalizedProvider = normalizeProviderDriverKind(provider);
|
|
if (normalizedProvider === null) {
|
|
return;
|
|
}
|
|
const instanceKey = options?.instanceId ?? defaultInstanceIdForDriver(normalizedProvider);
|
|
const fallbackModel =
|
|
normalizeModelSlug(options?.model, normalizedProvider) ??
|
|
DEFAULT_MODEL_BY_PROVIDER[normalizedProvider] ??
|
|
DEFAULT_MODEL;
|
|
const providerOpts =
|
|
nextProviderOptions && nextProviderOptions.length > 0 ? nextProviderOptions : undefined;
|
|
|
|
set((state) => {
|
|
const existing = state.draftsByThreadKey[threadKey];
|
|
const base = existing ?? createEmptyThreadDraft();
|
|
|
|
// Update the map entry for this provider
|
|
const nextMap = { ...base.modelSelectionByProvider };
|
|
const currentForProvider = nextMap[instanceKey];
|
|
if (providerOpts) {
|
|
nextMap[instanceKey] = createModelSelection(
|
|
instanceKey,
|
|
currentForProvider?.model ?? fallbackModel,
|
|
providerOpts,
|
|
);
|
|
} else if (currentForProvider && (currentForProvider.options?.length ?? 0) > 0) {
|
|
const { options: _, ...rest } = currentForProvider;
|
|
nextMap[instanceKey] = rest as ModelSelection;
|
|
}
|
|
|
|
// Handle sticky persistence
|
|
let nextStickyMap = state.stickyModelSelectionByProvider;
|
|
let nextStickyActiveProvider = state.stickyActiveProvider;
|
|
if (options?.persistSticky === true) {
|
|
nextStickyMap = { ...state.stickyModelSelectionByProvider };
|
|
const stickyBase =
|
|
nextStickyMap[instanceKey] ??
|
|
base.modelSelectionByProvider[instanceKey] ??
|
|
createModelSelection(instanceKey, fallbackModel);
|
|
if (providerOpts) {
|
|
nextStickyMap[instanceKey] = createModelSelection(
|
|
instanceKey,
|
|
stickyBase.model,
|
|
providerOpts,
|
|
);
|
|
} else if ((stickyBase.options?.length ?? 0) > 0) {
|
|
const { options: _, ...rest } = stickyBase;
|
|
nextStickyMap[instanceKey] = rest as ModelSelection;
|
|
}
|
|
nextStickyActiveProvider = options.instanceId
|
|
? instanceKey
|
|
: (base.activeProvider ?? instanceKey);
|
|
}
|
|
|
|
if (
|
|
Equal.equals(base.modelSelectionByProvider, nextMap) &&
|
|
Equal.equals(state.stickyModelSelectionByProvider, nextStickyMap) &&
|
|
state.stickyActiveProvider === nextStickyActiveProvider
|
|
) {
|
|
return state;
|
|
}
|
|
|
|
// Trait edits are user-driven intent: mark the selection explicit
|
|
// so later seeds cannot silently replace the chosen options.
|
|
const { modelSelectionExplicit: _previousExplicit, ...restBase } = base;
|
|
const nextDraft: ComposerThreadDraftState = {
|
|
...restBase,
|
|
...(options?.instanceId ? { activeProvider: instanceKey } : {}),
|
|
modelSelectionByProvider: nextMap,
|
|
modelSelectionExplicit: true,
|
|
};
|
|
const nextDraftsByThreadKey = { ...state.draftsByThreadKey };
|
|
if (shouldRemoveDraft(nextDraft)) {
|
|
delete nextDraftsByThreadKey[threadKey];
|
|
} else {
|
|
nextDraftsByThreadKey[threadKey] = nextDraft;
|
|
}
|
|
|
|
return {
|
|
draftsByThreadKey: nextDraftsByThreadKey,
|
|
...(options?.persistSticky === true
|
|
? {
|
|
stickyModelSelectionByProvider: nextStickyMap,
|
|
stickyActiveProvider: nextStickyActiveProvider,
|
|
}
|
|
: {}),
|
|
};
|
|
});
|
|
},
|
|
setRuntimeMode: (threadRef, runtimeMode) => {
|
|
const threadKey = resolveComposerDraftKey(get(), threadRef) ?? "";
|
|
if (threadKey.length === 0) {
|
|
return;
|
|
}
|
|
const nextRuntimeMode = isRuntimeMode(runtimeMode) ? runtimeMode : null;
|
|
set((state) => {
|
|
const existing = state.draftsByThreadKey[threadKey];
|
|
if (!existing && nextRuntimeMode === null) {
|
|
return state;
|
|
}
|
|
const base = existing ?? createEmptyThreadDraft();
|
|
if (base.runtimeMode === nextRuntimeMode) {
|
|
return state;
|
|
}
|
|
const nextDraft: ComposerThreadDraftState = {
|
|
...base,
|
|
runtimeMode: nextRuntimeMode,
|
|
};
|
|
const nextDraftsByThreadKey = { ...state.draftsByThreadKey };
|
|
if (shouldRemoveDraft(nextDraft)) {
|
|
delete nextDraftsByThreadKey[threadKey];
|
|
} else {
|
|
nextDraftsByThreadKey[threadKey] = nextDraft;
|
|
}
|
|
return { draftsByThreadKey: nextDraftsByThreadKey };
|
|
});
|
|
},
|
|
setInteractionMode: (threadRef, interactionMode) => {
|
|
const threadKey = resolveComposerDraftKey(get(), threadRef) ?? "";
|
|
if (threadKey.length === 0) {
|
|
return;
|
|
}
|
|
const nextInteractionMode =
|
|
interactionMode === "plan" || interactionMode === "default" ? interactionMode : null;
|
|
set((state) => {
|
|
const existing = state.draftsByThreadKey[threadKey];
|
|
if (!existing && nextInteractionMode === null) {
|
|
return state;
|
|
}
|
|
const base = existing ?? createEmptyThreadDraft();
|
|
if (base.interactionMode === nextInteractionMode) {
|
|
return state;
|
|
}
|
|
const nextDraft: ComposerThreadDraftState = {
|
|
...base,
|
|
interactionMode: nextInteractionMode,
|
|
};
|
|
const nextDraftsByThreadKey = { ...state.draftsByThreadKey };
|
|
if (shouldRemoveDraft(nextDraft)) {
|
|
delete nextDraftsByThreadKey[threadKey];
|
|
} else {
|
|
nextDraftsByThreadKey[threadKey] = nextDraft;
|
|
}
|
|
return { draftsByThreadKey: nextDraftsByThreadKey };
|
|
});
|
|
},
|
|
addImage: (threadRef, image) => {
|
|
const threadKey = resolveComposerDraftKey(get(), threadRef);
|
|
const threadId = resolveComposerThreadId(get(), threadRef);
|
|
if (!threadKey || !threadId) {
|
|
return;
|
|
}
|
|
get().addImages(typeof threadRef === "string" ? DraftId.make(threadKey) : threadRef, [
|
|
image,
|
|
]);
|
|
},
|
|
addImages: (threadRef, images) => {
|
|
const threadKey = resolveComposerDraftKey(get(), threadRef) ?? "";
|
|
if (threadKey.length === 0 || images.length === 0) {
|
|
return;
|
|
}
|
|
set((state) => {
|
|
const existing = state.draftsByThreadKey[threadKey] ?? createEmptyThreadDraft();
|
|
const existingIds = new Set(existing.images.map((image) => image.id));
|
|
const existingDedupKeys = new Set(
|
|
existing.images.map((image) => composerImageDedupKey(image)),
|
|
);
|
|
const acceptedPreviewUrls = new Set(existing.images.map((image) => image.previewUrl));
|
|
const dedupedIncoming: ComposerImageAttachment[] = [];
|
|
for (const image of images) {
|
|
const dedupKey = composerImageDedupKey(image);
|
|
if (existingIds.has(image.id) || existingDedupKeys.has(dedupKey)) {
|
|
// Avoid revoking a blob URL that's still referenced by an accepted image.
|
|
if (!acceptedPreviewUrls.has(image.previewUrl)) {
|
|
revokeObjectPreviewUrl(image.previewUrl);
|
|
}
|
|
continue;
|
|
}
|
|
if (
|
|
existing.images.length + existing.files.length + dedupedIncoming.length >=
|
|
PROVIDER_SEND_TURN_MAX_ATTACHMENTS
|
|
) {
|
|
if (!acceptedPreviewUrls.has(image.previewUrl)) {
|
|
revokeObjectPreviewUrl(image.previewUrl);
|
|
}
|
|
continue;
|
|
}
|
|
dedupedIncoming.push(image);
|
|
existingIds.add(image.id);
|
|
existingDedupKeys.add(dedupKey);
|
|
acceptedPreviewUrls.add(image.previewUrl);
|
|
}
|
|
if (dedupedIncoming.length === 0) {
|
|
return state;
|
|
}
|
|
return {
|
|
draftsByThreadKey: {
|
|
...state.draftsByThreadKey,
|
|
[threadKey]: {
|
|
...existing,
|
|
images: [...existing.images, ...dedupedIncoming],
|
|
},
|
|
},
|
|
};
|
|
});
|
|
},
|
|
removeImage: (threadRef, imageId) => {
|
|
const threadKey = resolveComposerDraftKey(get(), threadRef) ?? "";
|
|
if (threadKey.length === 0) {
|
|
return;
|
|
}
|
|
const existing = get().draftsByThreadKey[threadKey];
|
|
if (!existing) {
|
|
return;
|
|
}
|
|
const removedImage = existing.images.find((image) => image.id === imageId);
|
|
if (removedImage) {
|
|
revokeObjectPreviewUrl(removedImage.previewUrl);
|
|
}
|
|
set((state) => {
|
|
const current = state.draftsByThreadKey[threadKey];
|
|
if (!current) {
|
|
return state;
|
|
}
|
|
const nextDraft: ComposerThreadDraftState = {
|
|
...current,
|
|
images: current.images.filter((image) => image.id !== imageId),
|
|
nonPersistedImageIds: current.nonPersistedImageIds.filter((id) => id !== imageId),
|
|
persistedAttachments: current.persistedAttachments.filter(
|
|
(attachment) => attachment.id !== imageId,
|
|
),
|
|
};
|
|
const nextDraftsByThreadKey = { ...state.draftsByThreadKey };
|
|
if (shouldRemoveDraft(nextDraft)) {
|
|
delete nextDraftsByThreadKey[threadKey];
|
|
} else {
|
|
nextDraftsByThreadKey[threadKey] = nextDraft;
|
|
}
|
|
return { draftsByThreadKey: nextDraftsByThreadKey };
|
|
});
|
|
},
|
|
addFiles: (threadRef, files) => {
|
|
const threadKey = resolveComposerDraftKey(get(), threadRef) ?? "";
|
|
if (threadKey.length === 0 || files.length === 0) {
|
|
return;
|
|
}
|
|
set((state) => {
|
|
const existing = state.draftsByThreadKey[threadKey] ?? createEmptyThreadDraft();
|
|
const knownIds = new Set(existing.files.map((file) => file.id));
|
|
const knownFiles = new Map<string, ComposerFileAttachment>(
|
|
existing.files.map((file) => [composerFileDedupKey(file), file]),
|
|
);
|
|
const accepted: ComposerFileAttachment[] = [];
|
|
// Needs-reattach markers replaced in place by a re-pick, keyed by
|
|
// the marker's id.
|
|
const replacements = new Map<string, ComposerFileAttachment>();
|
|
for (const file of files) {
|
|
const key = composerFileDedupKey(file);
|
|
if (knownIds.has(file.id)) {
|
|
continue;
|
|
}
|
|
const duplicate =
|
|
knownFiles.get(key) ??
|
|
existing.files.find(
|
|
(candidate) =>
|
|
composerFileNeedsReattach(candidate) &&
|
|
!replacements.has(candidate.id) &&
|
|
composerFileMatchesReattachMarker(candidate, file),
|
|
);
|
|
if (duplicate) {
|
|
// A needs-reattach marker is not a usable duplicate. Replace
|
|
// it so the upload restarts.
|
|
if (composerFileNeedsReattach(duplicate) && !replacements.has(duplicate.id)) {
|
|
replacements.set(duplicate.id, file);
|
|
knownIds.add(file.id);
|
|
knownFiles.set(key, file);
|
|
}
|
|
continue;
|
|
}
|
|
if (
|
|
existing.images.length + existing.files.length + accepted.length >=
|
|
PROVIDER_SEND_TURN_MAX_ATTACHMENTS
|
|
) {
|
|
break;
|
|
}
|
|
accepted.push(file);
|
|
knownIds.add(file.id);
|
|
knownFiles.set(key, file);
|
|
}
|
|
if (accepted.length === 0 && replacements.size === 0) {
|
|
return state;
|
|
}
|
|
const retained = existing.files.map((file) => replacements.get(file.id) ?? file);
|
|
return {
|
|
draftsByThreadKey: {
|
|
...state.draftsByThreadKey,
|
|
[threadKey]: { ...existing, files: [...retained, ...accepted] },
|
|
},
|
|
};
|
|
});
|
|
},
|
|
removeFile: (threadRef, fileId) => {
|
|
const threadKey = resolveComposerDraftKey(get(), threadRef) ?? "";
|
|
if (threadKey.length === 0) {
|
|
return;
|
|
}
|
|
set((state) => {
|
|
const current = state.draftsByThreadKey[threadKey];
|
|
if (!current?.files.some((file) => file.id === fileId)) {
|
|
return state;
|
|
}
|
|
const nextDraft = {
|
|
...current,
|
|
files: current.files.filter((file) => file.id !== fileId),
|
|
} satisfies ComposerThreadDraftState;
|
|
const nextDraftsByThreadKey = { ...state.draftsByThreadKey };
|
|
if (shouldRemoveDraft(nextDraft)) {
|
|
delete nextDraftsByThreadKey[threadKey];
|
|
} else {
|
|
nextDraftsByThreadKey[threadKey] = nextDraft;
|
|
}
|
|
return { draftsByThreadKey: nextDraftsByThreadKey };
|
|
});
|
|
},
|
|
setFileUpload: (threadRef, fileId, environmentId, attachmentId) => {
|
|
const threadKey = resolveComposerDraftKey(get(), threadRef) ?? "";
|
|
if (threadKey.length === 0) {
|
|
return;
|
|
}
|
|
set((state) => {
|
|
const current = state.draftsByThreadKey[threadKey];
|
|
const file = current?.files.find((entry) => entry.id === fileId);
|
|
if (
|
|
!current ||
|
|
!file ||
|
|
(file.uploadEnvironmentId === environmentId &&
|
|
file.uploadedAttachmentId === attachmentId)
|
|
) {
|
|
return state;
|
|
}
|
|
return {
|
|
draftsByThreadKey: {
|
|
...state.draftsByThreadKey,
|
|
[threadKey]: {
|
|
...current,
|
|
files: current.files.map((entry) =>
|
|
entry.id === fileId
|
|
? {
|
|
...entry,
|
|
uploadedAttachmentId: attachmentId,
|
|
uploadEnvironmentId: environmentId,
|
|
}
|
|
: entry,
|
|
),
|
|
},
|
|
},
|
|
};
|
|
});
|
|
},
|
|
markFileUploadMissing: (threadRef, fileId, environmentId, attachmentId) => {
|
|
const threadKey = resolveComposerDraftKey(get(), threadRef) ?? "";
|
|
if (threadKey.length === 0) {
|
|
return false;
|
|
}
|
|
let markedMissing = false;
|
|
set((state) => {
|
|
const current = state.draftsByThreadKey[threadKey];
|
|
const file = current?.files.find((entry) => entry.id === fileId);
|
|
if (
|
|
!current ||
|
|
!file ||
|
|
file.file !== null ||
|
|
file.uploadEnvironmentId !== environmentId ||
|
|
file.uploadedAttachmentId !== attachmentId
|
|
) {
|
|
return state;
|
|
}
|
|
markedMissing = true;
|
|
return {
|
|
draftsByThreadKey: {
|
|
...state.draftsByThreadKey,
|
|
[threadKey]: {
|
|
...current,
|
|
files: current.files.map((entry) => {
|
|
if (entry.id !== fileId) {
|
|
return entry;
|
|
}
|
|
const marker = { ...entry };
|
|
delete marker.uploadedAttachmentId;
|
|
delete marker.uploadEnvironmentId;
|
|
return marker;
|
|
}),
|
|
},
|
|
},
|
|
};
|
|
});
|
|
return markedMissing;
|
|
},
|
|
insertTerminalContext: (threadRef, prompt, context, index) => {
|
|
const threadKey = resolveComposerDraftKey(get(), threadRef);
|
|
const threadId = resolveComposerThreadId(get(), threadRef);
|
|
if (!threadKey || !threadId) {
|
|
return false;
|
|
}
|
|
let inserted = false;
|
|
set((state) => {
|
|
const existing = state.draftsByThreadKey[threadKey] ?? createEmptyThreadDraft();
|
|
const normalizedContext = normalizeTerminalContextForThread(threadId, context);
|
|
if (!normalizedContext) {
|
|
return state;
|
|
}
|
|
const dedupKey = terminalContextDedupKey(normalizedContext);
|
|
if (
|
|
existing.terminalContexts.some((entry) => entry.id === normalizedContext.id) ||
|
|
existing.terminalContexts.some((entry) => terminalContextDedupKey(entry) === dedupKey)
|
|
) {
|
|
return state;
|
|
}
|
|
inserted = true;
|
|
const boundedIndex = Math.max(0, Math.min(existing.terminalContexts.length, index));
|
|
const nextDraft: ComposerThreadDraftState = {
|
|
...existing,
|
|
prompt,
|
|
terminalContexts: [
|
|
...existing.terminalContexts.slice(0, boundedIndex),
|
|
normalizedContext,
|
|
...existing.terminalContexts.slice(boundedIndex),
|
|
],
|
|
};
|
|
return {
|
|
draftsByThreadKey: {
|
|
...state.draftsByThreadKey,
|
|
[threadKey]: nextDraft,
|
|
},
|
|
};
|
|
});
|
|
return inserted;
|
|
},
|
|
addTerminalContext: (threadRef, context) => {
|
|
const threadKey = resolveComposerDraftKey(get(), threadRef);
|
|
const threadId = resolveComposerThreadId(get(), threadRef);
|
|
if (!threadKey || !threadId) {
|
|
return;
|
|
}
|
|
get().addTerminalContexts(
|
|
typeof threadRef === "string" ? DraftId.make(threadKey) : threadRef,
|
|
[context],
|
|
);
|
|
},
|
|
addTerminalContexts: (threadRef, contexts) => {
|
|
const threadKey = resolveComposerDraftKey(get(), threadRef);
|
|
const threadId = resolveComposerThreadId(get(), threadRef);
|
|
if (!threadKey || !threadId || contexts.length === 0) {
|
|
return;
|
|
}
|
|
set((state) => {
|
|
const existing = state.draftsByThreadKey[threadKey] ?? createEmptyThreadDraft();
|
|
const acceptedContexts = normalizeTerminalContextsForThread(threadId, [
|
|
...existing.terminalContexts,
|
|
...contexts,
|
|
]).slice(existing.terminalContexts.length);
|
|
if (acceptedContexts.length === 0) {
|
|
return state;
|
|
}
|
|
return {
|
|
draftsByThreadKey: {
|
|
...state.draftsByThreadKey,
|
|
[threadKey]: {
|
|
...existing,
|
|
prompt: ensureInlineTerminalContextPlaceholders(
|
|
existing.prompt,
|
|
existing.terminalContexts.length + acceptedContexts.length,
|
|
),
|
|
terminalContexts: [...existing.terminalContexts, ...acceptedContexts],
|
|
},
|
|
},
|
|
};
|
|
});
|
|
},
|
|
removeTerminalContext: (threadRef, contextId) => {
|
|
const threadKey = resolveComposerDraftKey(get(), threadRef) ?? "";
|
|
if (threadKey.length === 0 || contextId.length === 0) {
|
|
return;
|
|
}
|
|
set((state) => {
|
|
const current = state.draftsByThreadKey[threadKey];
|
|
if (!current) {
|
|
return state;
|
|
}
|
|
const nextDraft: ComposerThreadDraftState = {
|
|
...current,
|
|
terminalContexts: current.terminalContexts.filter(
|
|
(context) => context.id !== contextId,
|
|
),
|
|
};
|
|
const nextDraftsByThreadKey = { ...state.draftsByThreadKey };
|
|
if (shouldRemoveDraft(nextDraft)) {
|
|
delete nextDraftsByThreadKey[threadKey];
|
|
} else {
|
|
nextDraftsByThreadKey[threadKey] = nextDraft;
|
|
}
|
|
return { draftsByThreadKey: nextDraftsByThreadKey };
|
|
});
|
|
},
|
|
clearTerminalContexts: (threadRef) => {
|
|
const threadKey = resolveComposerDraftKey(get(), threadRef) ?? "";
|
|
if (threadKey.length === 0) {
|
|
return;
|
|
}
|
|
set((state) => {
|
|
const current = state.draftsByThreadKey[threadKey];
|
|
if (!current || current.terminalContexts.length === 0) {
|
|
return state;
|
|
}
|
|
const nextDraft: ComposerThreadDraftState = {
|
|
...current,
|
|
terminalContexts: [],
|
|
};
|
|
const nextDraftsByThreadKey = { ...state.draftsByThreadKey };
|
|
if (shouldRemoveDraft(nextDraft)) {
|
|
delete nextDraftsByThreadKey[threadKey];
|
|
} else {
|
|
nextDraftsByThreadKey[threadKey] = nextDraft;
|
|
}
|
|
return { draftsByThreadKey: nextDraftsByThreadKey };
|
|
});
|
|
},
|
|
addElementContext: (threadRef, selection) => {
|
|
const threadKey = resolveComposerDraftKey(get(), threadRef);
|
|
const threadId = resolveComposerThreadId(get(), threadRef);
|
|
if (!threadKey || !threadId) return false;
|
|
let accepted = false;
|
|
set((state) => {
|
|
const existing = state.draftsByThreadKey[threadKey] ?? createEmptyThreadDraft();
|
|
const dedupKey = elementContextDedupKey(selection);
|
|
if (
|
|
existing.elementContexts.some((entry) => elementContextDedupKey(entry) === dedupKey)
|
|
) {
|
|
return state;
|
|
}
|
|
accepted = true;
|
|
const draft: ElementContextDraft = {
|
|
...selection,
|
|
id: newElementContextId(),
|
|
threadId,
|
|
pickedAt: new Date().toISOString(),
|
|
};
|
|
return {
|
|
draftsByThreadKey: {
|
|
...state.draftsByThreadKey,
|
|
[threadKey]: {
|
|
...existing,
|
|
elementContexts: [...existing.elementContexts, draft],
|
|
},
|
|
},
|
|
};
|
|
});
|
|
return accepted;
|
|
},
|
|
setElementContexts: (threadRef, contexts) => {
|
|
const threadKey = resolveComposerDraftKey(get(), threadRef);
|
|
if (!threadKey) return;
|
|
set((state) => {
|
|
const existing = state.draftsByThreadKey[threadKey] ?? createEmptyThreadDraft();
|
|
const nextDraft: ComposerThreadDraftState = {
|
|
...existing,
|
|
elementContexts: [...contexts],
|
|
};
|
|
const nextDraftsByThreadKey = { ...state.draftsByThreadKey };
|
|
if (shouldRemoveDraft(nextDraft)) {
|
|
delete nextDraftsByThreadKey[threadKey];
|
|
} else {
|
|
nextDraftsByThreadKey[threadKey] = nextDraft;
|
|
}
|
|
return { draftsByThreadKey: nextDraftsByThreadKey };
|
|
});
|
|
},
|
|
removeElementContext: (threadRef, contextId) => {
|
|
const threadKey = resolveComposerDraftKey(get(), threadRef) ?? "";
|
|
if (threadKey.length === 0 || contextId.length === 0) return;
|
|
set((state) => {
|
|
const current = state.draftsByThreadKey[threadKey];
|
|
if (!current) return state;
|
|
const filtered = current.elementContexts.filter((entry) => entry.id !== contextId);
|
|
if (filtered.length === current.elementContexts.length) return state;
|
|
const nextDraft: ComposerThreadDraftState = {
|
|
...current,
|
|
elementContexts: filtered,
|
|
};
|
|
const nextDraftsByThreadKey = { ...state.draftsByThreadKey };
|
|
if (shouldRemoveDraft(nextDraft)) {
|
|
delete nextDraftsByThreadKey[threadKey];
|
|
} else {
|
|
nextDraftsByThreadKey[threadKey] = nextDraft;
|
|
}
|
|
return { draftsByThreadKey: nextDraftsByThreadKey };
|
|
});
|
|
},
|
|
clearElementContexts: (threadRef) => {
|
|
const threadKey = resolveComposerDraftKey(get(), threadRef) ?? "";
|
|
if (threadKey.length === 0) return;
|
|
set((state) => {
|
|
const current = state.draftsByThreadKey[threadKey];
|
|
if (!current || current.elementContexts.length === 0) return state;
|
|
const nextDraft: ComposerThreadDraftState = {
|
|
...current,
|
|
elementContexts: [],
|
|
};
|
|
const nextDraftsByThreadKey = { ...state.draftsByThreadKey };
|
|
if (shouldRemoveDraft(nextDraft)) {
|
|
delete nextDraftsByThreadKey[threadKey];
|
|
} else {
|
|
nextDraftsByThreadKey[threadKey] = nextDraft;
|
|
}
|
|
return { draftsByThreadKey: nextDraftsByThreadKey };
|
|
});
|
|
},
|
|
addPreviewAnnotation: (threadRef, annotation) => {
|
|
const threadKey = resolveComposerDraftKey(get(), threadRef);
|
|
if (!threadKey) return;
|
|
set((state) => {
|
|
const existing = state.draftsByThreadKey[threadKey] ?? createEmptyThreadDraft();
|
|
const nextAnnotations = existing.previewAnnotations.filter(
|
|
(entry) => entry.id !== annotation.id,
|
|
);
|
|
const compactAnnotation: PreviewAnnotationPayload = {
|
|
...annotation,
|
|
screenshot: annotation.screenshot ? { ...annotation.screenshot, dataUrl: "" } : null,
|
|
};
|
|
return {
|
|
draftsByThreadKey: {
|
|
...state.draftsByThreadKey,
|
|
[threadKey]: {
|
|
...existing,
|
|
previewAnnotations: [...nextAnnotations, compactAnnotation],
|
|
},
|
|
},
|
|
};
|
|
});
|
|
},
|
|
setPreviewAnnotations: (threadRef, annotations) => {
|
|
const threadKey = resolveComposerDraftKey(get(), threadRef);
|
|
if (!threadKey) return;
|
|
set((state) => {
|
|
const existing = state.draftsByThreadKey[threadKey] ?? createEmptyThreadDraft();
|
|
return {
|
|
draftsByThreadKey: {
|
|
...state.draftsByThreadKey,
|
|
[threadKey]: { ...existing, previewAnnotations: [...annotations] },
|
|
},
|
|
};
|
|
});
|
|
},
|
|
removePreviewAnnotation: (threadRef, annotationId) => {
|
|
const threadKey = resolveComposerDraftKey(get(), threadRef);
|
|
if (!threadKey || !annotationId) return;
|
|
set((state) => {
|
|
const current = state.draftsByThreadKey[threadKey];
|
|
if (!current) return state;
|
|
const previewAnnotations = current.previewAnnotations.filter(
|
|
(entry) => entry.id !== annotationId,
|
|
);
|
|
if (previewAnnotations.length === current.previewAnnotations.length) return state;
|
|
const nextDraft = {
|
|
...current,
|
|
previewAnnotations,
|
|
images: current.images.filter((image) => image.id !== annotationId),
|
|
persistedAttachments: current.persistedAttachments.filter(
|
|
(image) => image.id !== annotationId,
|
|
),
|
|
nonPersistedImageIds: current.nonPersistedImageIds.filter(
|
|
(imageId) => imageId !== annotationId,
|
|
),
|
|
};
|
|
const nextDraftsByThreadKey = { ...state.draftsByThreadKey };
|
|
if (shouldRemoveDraft(nextDraft)) delete nextDraftsByThreadKey[threadKey];
|
|
else nextDraftsByThreadKey[threadKey] = nextDraft;
|
|
return { draftsByThreadKey: nextDraftsByThreadKey };
|
|
});
|
|
},
|
|
addReviewComment: (threadRef, comment) => {
|
|
const threadKey = resolveComposerDraftKey(get(), threadRef);
|
|
if (!threadKey || !isReviewCommentContext(comment)) return;
|
|
set((state) => {
|
|
const existing = state.draftsByThreadKey[threadKey] ?? createEmptyThreadDraft();
|
|
const reviewComments = existing.reviewComments.filter(
|
|
(entry) => entry.id !== comment.id,
|
|
);
|
|
return {
|
|
draftsByThreadKey: {
|
|
...state.draftsByThreadKey,
|
|
[threadKey]: {
|
|
...existing,
|
|
reviewComments: [...reviewComments, { ...comment }],
|
|
},
|
|
},
|
|
};
|
|
});
|
|
},
|
|
setReviewComments: (threadRef, comments) => {
|
|
const threadKey = resolveComposerDraftKey(get(), threadRef);
|
|
if (!threadKey) return;
|
|
const reviewComments = comments
|
|
.filter(isReviewCommentContext)
|
|
.map((comment) => ({ ...comment }));
|
|
set((state) => {
|
|
const existing = state.draftsByThreadKey[threadKey] ?? createEmptyThreadDraft();
|
|
const nextDraft = { ...existing, reviewComments };
|
|
const nextDraftsByThreadKey = { ...state.draftsByThreadKey };
|
|
if (shouldRemoveDraft(nextDraft)) delete nextDraftsByThreadKey[threadKey];
|
|
else nextDraftsByThreadKey[threadKey] = nextDraft;
|
|
return { draftsByThreadKey: nextDraftsByThreadKey };
|
|
});
|
|
},
|
|
removeReviewComment: (threadRef, commentId) => {
|
|
const threadKey = resolveComposerDraftKey(get(), threadRef);
|
|
if (!threadKey || !commentId) return;
|
|
set((state) => {
|
|
const current = state.draftsByThreadKey[threadKey];
|
|
if (!current) return state;
|
|
const reviewComments = current.reviewComments.filter((entry) => entry.id !== commentId);
|
|
if (reviewComments.length === current.reviewComments.length) return state;
|
|
const nextDraft = { ...current, reviewComments };
|
|
const nextDraftsByThreadKey = { ...state.draftsByThreadKey };
|
|
if (shouldRemoveDraft(nextDraft)) delete nextDraftsByThreadKey[threadKey];
|
|
else nextDraftsByThreadKey[threadKey] = nextDraft;
|
|
return { draftsByThreadKey: nextDraftsByThreadKey };
|
|
});
|
|
},
|
|
clearPersistedAttachments: (threadRef) => {
|
|
const threadKey = resolveComposerDraftKey(get(), threadRef) ?? "";
|
|
if (threadKey.length === 0) {
|
|
return;
|
|
}
|
|
set((state) => {
|
|
const current = state.draftsByThreadKey[threadKey];
|
|
if (!current) {
|
|
return state;
|
|
}
|
|
const nextDraft: ComposerThreadDraftState = {
|
|
...current,
|
|
persistedAttachments: [],
|
|
nonPersistedImageIds: [],
|
|
};
|
|
const nextDraftsByThreadKey = { ...state.draftsByThreadKey };
|
|
if (shouldRemoveDraft(nextDraft)) {
|
|
delete nextDraftsByThreadKey[threadKey];
|
|
} else {
|
|
nextDraftsByThreadKey[threadKey] = nextDraft;
|
|
}
|
|
return { draftsByThreadKey: nextDraftsByThreadKey };
|
|
});
|
|
},
|
|
syncPersistedAttachments: (threadRef, attachments) => {
|
|
const threadKey = resolveComposerDraftKey(get(), threadRef);
|
|
if (!threadKey) {
|
|
return;
|
|
}
|
|
const attachmentIdSet = new Set(attachments.map((attachment) => attachment.id));
|
|
set((state) => {
|
|
const current = state.draftsByThreadKey[threadKey];
|
|
if (!current) {
|
|
return state;
|
|
}
|
|
const nextDraft: ComposerThreadDraftState = {
|
|
...current,
|
|
// Stage attempted attachments so persist middleware can try writing them.
|
|
persistedAttachments: attachments,
|
|
nonPersistedImageIds: current.nonPersistedImageIds.filter(
|
|
(id) => !attachmentIdSet.has(id),
|
|
),
|
|
};
|
|
const nextDraftsByThreadKey = { ...state.draftsByThreadKey };
|
|
if (shouldRemoveDraft(nextDraft)) {
|
|
delete nextDraftsByThreadKey[threadKey];
|
|
} else {
|
|
nextDraftsByThreadKey[threadKey] = nextDraft;
|
|
}
|
|
return { draftsByThreadKey: nextDraftsByThreadKey };
|
|
});
|
|
Promise.resolve().then(() => {
|
|
verifyPersistedAttachments(threadKey, attachments, set);
|
|
});
|
|
},
|
|
clearComposerContent: (threadRef) => {
|
|
const threadKey = resolveComposerDraftKey(get(), threadRef) ?? "";
|
|
if (threadKey.length === 0) {
|
|
return;
|
|
}
|
|
set((state) => {
|
|
const current = state.draftsByThreadKey[threadKey];
|
|
if (!current) {
|
|
return state;
|
|
}
|
|
const nextDraft: ComposerThreadDraftState = {
|
|
...current,
|
|
prompt: "",
|
|
images: [],
|
|
files: [],
|
|
nonPersistedImageIds: [],
|
|
persistedAttachments: [],
|
|
terminalContexts: [],
|
|
elementContexts: [],
|
|
previewAnnotations: [],
|
|
reviewComments: [],
|
|
};
|
|
const nextDraftsByThreadKey = { ...state.draftsByThreadKey };
|
|
if (shouldRemoveDraft(nextDraft)) {
|
|
delete nextDraftsByThreadKey[threadKey];
|
|
} else {
|
|
nextDraftsByThreadKey[threadKey] = nextDraft;
|
|
}
|
|
return { draftsByThreadKey: nextDraftsByThreadKey };
|
|
});
|
|
},
|
|
clearComposerPromptAndImages: (threadRef) => {
|
|
const threadKey = resolveComposerDraftKey(get(), threadRef) ?? "";
|
|
if (threadKey.length === 0) {
|
|
return;
|
|
}
|
|
set((state) => {
|
|
const current = state.draftsByThreadKey[threadKey];
|
|
if (!current) {
|
|
return state;
|
|
}
|
|
for (const image of current.images) {
|
|
revokeObjectPreviewUrl(image.previewUrl);
|
|
}
|
|
const nextDraft: ComposerThreadDraftState = {
|
|
...current,
|
|
prompt: ensureInlineTerminalContextPlaceholders("", current.terminalContexts.length),
|
|
images: [],
|
|
files: [],
|
|
nonPersistedImageIds: [],
|
|
persistedAttachments: [],
|
|
};
|
|
const nextDraftsByThreadKey = { ...state.draftsByThreadKey };
|
|
if (shouldRemoveDraft(nextDraft)) {
|
|
delete nextDraftsByThreadKey[threadKey];
|
|
} else {
|
|
nextDraftsByThreadKey[threadKey] = nextDraft;
|
|
}
|
|
return { draftsByThreadKey: nextDraftsByThreadKey };
|
|
});
|
|
},
|
|
};
|
|
},
|
|
{
|
|
name: COMPOSER_DRAFT_STORAGE_KEY,
|
|
version: COMPOSER_DRAFT_STORAGE_VERSION,
|
|
storage: composerPersistStorage,
|
|
migrate: migratePersistedComposerDraftStoreState,
|
|
// Defer the draft walk and serialization until the storage write flushes.
|
|
partialize: (state): ComposerPersistState => ({ capturedState: state }),
|
|
merge: (persistedState, currentState) => {
|
|
const normalizedPersisted =
|
|
normalizeCurrentPersistedComposerDraftStoreState(persistedState);
|
|
const draftsByThreadKey = Object.fromEntries(
|
|
Object.entries(normalizedPersisted.draftsByThreadKey).map(([threadKey, draft]) => [
|
|
threadKey,
|
|
toHydratedThreadDraft(draft),
|
|
]),
|
|
);
|
|
const draftThreadsByThreadKey = Object.fromEntries(
|
|
Object.entries(normalizedPersisted.draftThreadsByThreadKey).map(
|
|
([threadKey, draftThread]) => [threadKey, toHydratedDraftThreadState(draftThread)],
|
|
),
|
|
) as Record<string, DraftThreadState>;
|
|
return {
|
|
...currentState,
|
|
draftsByThreadKey,
|
|
draftThreadsByThreadKey,
|
|
logicalProjectDraftThreadKeyByLogicalProjectKey:
|
|
normalizedPersisted.logicalProjectDraftThreadKeyByLogicalProjectKey,
|
|
stickyModelSelectionByProvider: normalizedPersisted.stickyModelSelectionByProvider ?? {},
|
|
stickyActiveProvider: normalizedPersisted.stickyActiveProvider ?? null,
|
|
};
|
|
},
|
|
},
|
|
),
|
|
);
|
|
|
|
export const useComposerDraftStore = composerDraftStore;
|
|
|
|
export function beginBackgroundDraftSubmissionByRef(threadRef: ScopedThreadRef): void {
|
|
const threadKey = scopedThreadKey(threadRef);
|
|
useComposerDraftStore.setState((state) => {
|
|
if (state.backgroundSubmissionThreadKeys[threadKey]) {
|
|
return state;
|
|
}
|
|
return {
|
|
backgroundSubmissionThreadKeys: {
|
|
...state.backgroundSubmissionThreadKeys,
|
|
[threadKey]: true,
|
|
},
|
|
};
|
|
});
|
|
}
|
|
|
|
export function clearBackgroundDraftSubmissionByRef(threadRef: ScopedThreadRef): void {
|
|
const threadKey = scopedThreadKey(threadRef);
|
|
useComposerDraftStore.setState((state) => {
|
|
if (!state.backgroundSubmissionThreadKeys[threadKey]) {
|
|
return state;
|
|
}
|
|
const backgroundSubmissionThreadKeys = { ...state.backgroundSubmissionThreadKeys };
|
|
delete backgroundSubmissionThreadKeys[threadKey];
|
|
return { backgroundSubmissionThreadKeys };
|
|
});
|
|
}
|
|
|
|
export function useBackgroundDraftSubmissionPending(threadRef: ScopedThreadRef | null): boolean {
|
|
const threadKey = threadRef ? scopedThreadKey(threadRef) : null;
|
|
return useComposerDraftStore(
|
|
(state) => threadKey !== null && state.backgroundSubmissionThreadKeys[threadKey] === true,
|
|
);
|
|
}
|
|
|
|
export function clearComposerDraftsEnvironment(environmentId: EnvironmentId): void {
|
|
useComposerDraftStore.setState((state) => {
|
|
const removedThreadKeys = new Set<string>();
|
|
|
|
for (const [threadKey, draftThread] of Object.entries(state.draftThreadsByThreadKey)) {
|
|
if (draftThread.environmentId === environmentId) {
|
|
removedThreadKeys.add(threadKey);
|
|
}
|
|
}
|
|
for (const threadKey of Object.keys(state.draftsByThreadKey)) {
|
|
if (parseScopedThreadKey(threadKey)?.environmentId === environmentId) {
|
|
removedThreadKeys.add(threadKey);
|
|
}
|
|
}
|
|
for (const [logicalProjectKey, threadKey] of Object.entries(
|
|
state.logicalProjectDraftThreadKeyByLogicalProjectKey,
|
|
)) {
|
|
if (parseScopedProjectKey(logicalProjectKey)?.environmentId === environmentId) {
|
|
removedThreadKeys.add(threadKey);
|
|
}
|
|
}
|
|
|
|
const nextLogicalMappings = Object.fromEntries(
|
|
Object.entries(state.logicalProjectDraftThreadKeyByLogicalProjectKey).filter(
|
|
([logicalProjectKey, threadKey]) =>
|
|
parseScopedProjectKey(logicalProjectKey)?.environmentId !== environmentId &&
|
|
!removedThreadKeys.has(threadKey),
|
|
),
|
|
) as Record<string, string>;
|
|
const nextDraftThreads = Object.fromEntries(
|
|
Object.entries(state.draftThreadsByThreadKey).filter(
|
|
([threadKey, draftThread]) =>
|
|
draftThread.environmentId !== environmentId && !removedThreadKeys.has(threadKey),
|
|
),
|
|
) as Record<string, DraftThreadState>;
|
|
const nextDrafts = Object.fromEntries(
|
|
Object.entries(state.draftsByThreadKey).filter(([threadKey, draft]) => {
|
|
if (!removedThreadKeys.has(threadKey)) {
|
|
return true;
|
|
}
|
|
revokeDraftThreadPreviewUrls(draft);
|
|
return false;
|
|
}),
|
|
) as Record<string, ComposerThreadDraftState>;
|
|
const nextBackgroundSubmissionThreadKeys = Object.fromEntries(
|
|
Object.entries(state.backgroundSubmissionThreadKeys).filter(
|
|
([threadKey]) => parseScopedThreadKey(threadKey)?.environmentId !== environmentId,
|
|
),
|
|
) as Record<string, true>;
|
|
|
|
return {
|
|
draftsByThreadKey: nextDrafts,
|
|
draftThreadsByThreadKey: nextDraftThreads,
|
|
logicalProjectDraftThreadKeyByLogicalProjectKey: nextLogicalMappings,
|
|
backgroundSubmissionThreadKeys: nextBackgroundSubmissionThreadKeys,
|
|
};
|
|
});
|
|
composerDebouncedStorage.flush();
|
|
}
|
|
|
|
export function useComposerThreadDraft(threadRef: ComposerThreadTarget): ComposerThreadDraftState {
|
|
return useComposerDraftStore((state) => {
|
|
return getComposerDraftState(state, threadRef) ?? EMPTY_THREAD_DRAFT;
|
|
});
|
|
}
|
|
|
|
/**
|
|
* True when a real thread's composer holds unsent user content. Selects a
|
|
* boolean so the sidebar row that reads it re-renders only when the draft
|
|
* appears or disappears, not on every keystroke.
|
|
*/
|
|
export function useThreadHasUnsentDraft(threadRef: ScopedThreadRef): boolean {
|
|
return useComposerDraftStore((state) =>
|
|
composerDraftHasUserContent(getComposerDraftState(state, threadRef)),
|
|
);
|
|
}
|
|
|
|
function useComposerDraftModelState(threadRef: ComposerThreadTarget): ComposerDraftModelState {
|
|
return useComposerDraftStore(
|
|
useShallow((state) => {
|
|
const draft = getComposerDraftState(state, threadRef);
|
|
return draft
|
|
? {
|
|
activeProvider: draft.activeProvider,
|
|
modelSelectionByProvider: draft.modelSelectionByProvider,
|
|
}
|
|
: EMPTY_COMPOSER_DRAFT_MODEL_STATE;
|
|
}),
|
|
);
|
|
}
|
|
|
|
export function useEffectiveComposerModelState(input: {
|
|
threadRef?: ComposerThreadTarget;
|
|
draftId?: DraftId;
|
|
providers: ReadonlyArray<ServerProvider>;
|
|
selectedProvider: ProviderDriverKind;
|
|
/**
|
|
* When supplied, the draft's saved selection for this instance takes
|
|
* precedence over the driver-kind bucket — so a custom `codex_personal`
|
|
* instance reads its own model, not the default Codex's.
|
|
*/
|
|
selectedInstanceId?: ProviderInstanceId | null | undefined;
|
|
threadModelSelection: ModelSelection | null | undefined;
|
|
projectModelSelection: ModelSelection | null | undefined;
|
|
settings: UnifiedSettings;
|
|
}): EffectiveComposerModelState {
|
|
const draft = useComposerDraftModelState(input.threadRef ?? input.draftId ?? DraftId.make(""));
|
|
|
|
return useMemo(
|
|
() =>
|
|
deriveEffectiveComposerModelState({
|
|
draft,
|
|
providers: input.providers,
|
|
selectedProvider: input.selectedProvider,
|
|
selectedInstanceId: input.selectedInstanceId,
|
|
threadModelSelection: input.threadModelSelection,
|
|
projectModelSelection: input.projectModelSelection,
|
|
settings: input.settings,
|
|
}),
|
|
[
|
|
draft,
|
|
input.providers,
|
|
input.settings,
|
|
input.projectModelSelection,
|
|
input.selectedInstanceId,
|
|
input.selectedProvider,
|
|
input.threadModelSelection,
|
|
],
|
|
);
|
|
}
|
|
|
|
export function markPromotedDraftThreadByRef(threadRef: ScopedThreadRef): void {
|
|
const draftStore = useComposerDraftStore.getState();
|
|
for (const [draftId, draftThread] of Object.entries(draftStore.draftThreadsByThreadKey)) {
|
|
if (
|
|
draftThread.environmentId === threadRef.environmentId &&
|
|
draftThread.threadId === threadRef.threadId
|
|
) {
|
|
draftStore.markDraftThreadPromoting(DraftId.make(draftId), threadRef);
|
|
}
|
|
}
|
|
}
|
|
|
|
export function finalizePromotedDraftThreadByRef(threadRef: ScopedThreadRef): void {
|
|
const draftStore = useComposerDraftStore.getState();
|
|
for (const [draftId, draftThread] of Object.entries(draftStore.draftThreadsByThreadKey)) {
|
|
const promotedRef = draftThread.promotedTo;
|
|
const matches = promotedRef
|
|
? promotedRef.environmentId === threadRef.environmentId &&
|
|
promotedRef.threadId === threadRef.threadId
|
|
: draftThread.environmentId === threadRef.environmentId &&
|
|
draftThread.threadId === threadRef.threadId;
|
|
if (matches) {
|
|
const target = DraftId.make(draftId);
|
|
draftStore.markDraftThreadPromoting(target, threadRef);
|
|
draftStore.finalizePromotedDraftThread(target);
|
|
}
|
|
}
|
|
clearBackgroundDraftSubmissionByRef(threadRef);
|
|
}
|