Skip to content

The agent that grows with you

33.4 KB
Raw Blame
import { randomUuid } from '@hermes/shared'
import { atom } from 'nanostores'

import type { HermesStagedUpload } from '@/global'
import { deriveDraftTitle } from '@/lib/draft-title'
import { triggerHaptic } from '@/lib/haptics'
import { persistString, storedString } from '@/lib/storage'

import {
  adoptLegacyEdits,
  compactDraftStash,
  DRAFT_STASH_STORAGE_KEY,
  hasDraftStash,
  healLegacyMirror,
  newerEntry,
  nextStashStamp,
  readDraftStash,
  readLegacyDrafts,
  type StashEntries,
  type StashEntry,
  writeDraftStash
} from './composer-draft-stash'
import { recordDislike, recordFriction } from './desktop-metrics'

/** Release blob: chip previews created for OS image drops (see #63682). */
export function revokeAttachmentPreviewUrl(url?: string | null) {
  if (url?.startsWith('blob:')) {
    try {
      URL.revokeObjectURL(url)
    } catch {
      // Best-effort — a revoked/invalid URL must not break chip removal.
    }
  }
}

/** Revoke blob: previews for attachments whose consumer was discarded. */
export function revokeAttachmentPreviewUrls(attachments: readonly ComposerAttachment[]) {
  for (const attachment of attachments) {
    revokeAttachmentPreviewUrl(attachment.previewUrl)
  }
}

/**
 * Revoke blob: previews from `previous` that are not retained by `next`.
 * Used when a queued/optimistic snapshot is replaced or dropped.
 */
export function revokeDiscardedAttachmentPreviews(
  previous: readonly ComposerAttachment[],
  next: readonly ComposerAttachment[] = []
) {
  const retained = new Set(
    next.map(attachment => attachment.previewUrl).filter((url): url is string => !!url?.startsWith('blob:'))
  )

  for (const attachment of previous) {
    const url = attachment.previewUrl

    if (url?.startsWith('blob:') && !retained.has(url)) {
      revokeAttachmentPreviewUrl(url)
    }
  }
}

export interface ClearAttachmentsOptions {
  /**
   * When true, leave blob: preview URLs alive for a submitted/queued snapshot
   * that still references them. Caller must revoke when that consumer is
   * discarded or replaced (see #63682 / PR review on #66546).
   */
  retainPreviewUrls?: boolean
}

export interface ComposerAttachment {
  id: string
  /** Renderer-lifetime identity for one attachment occurrence. Unlike `id`,
   * which is content/path-derived, this survives draft cloning but changes
   * when the user removes and re-adds the same attachment. */
  occurrenceId?: string
  kind: 'file' | 'folder' | 'image' | 'terminal' | 'url'
  label: string
  detail?: string
  refText?: string
  /** Legacy/on-demand full source. New local image chips omit this and read
   * `path` only when the lightbox opens, avoiding retained multi-MB base64. */
  previewUrl?: string
  /** Downscaled data URL for the attachment card and optimistic bubble only. */
  thumbnailUrl?: string
  path?: string
  /** Ownership of browser-staged bytes; survives failed uploads and draft clones. */
  stagedUpload?: HermesStagedUpload
  /** Validated MIME returned by canonical owner staging. */
  mime?: string
  /** Bounded source text from a Hermes-generated large paste, sent only to the title path. */
  titlePreview?: string
  attachedSessionId?: string
  /** Set while the file/image bytes are being staged into the session
   * workspace (remote upload or local stage), and 'error' if that failed.
   * Drives the spinner / error state on the composer attachment card. */
  uploadState?: 'uploading' | 'error'
}

export type ComposerAttachmentPatch = Partial<Omit<ComposerAttachment, 'id' | 'occurrenceId'>>

export const $composerDraft = atom('')
export const $composerAttachments = atom<ComposerAttachment[]>([])
export const $composerTerminalSelections = atom<Record<string, string>>({})

// Latched because opening a fresh session may remount the main composer before
// it can start voice. Session-tile composers deliberately never consume this.
export const $voiceConversationStartRequest = atom(0)
let nextVoiceStartRequest = 0
let handledVoiceStartRequest = 0
export const createComposerAttachmentOccurrenceId = (): string => randomUuid()

export const requestVoiceConversationStart = (): void => $voiceConversationStartRequest.set(++nextVoiceStartRequest)

export const takeVoiceConversationStart = (current: number): boolean => {
  if (current <= handledVoiceStartRequest) {
    return false
  }

  handledVoiceStartRequest = current

  return true
}

// ---------------------------------------------------------------------------
// Composer scopes — one live attachment set PER MOUNTED COMPOSER. The main
// chat's scope wraps the module-level atom above (all existing readers keep
// working); each session tile creates its own so two composers on screen
// never share chips. Draft text needs no scope: it lives in each ChatBar's
// DOM + draftRef and stashes per session key already.
// ---------------------------------------------------------------------------

export interface ComposerAttachmentScope {
  $attachments: ReturnType<typeof atom<ComposerAttachment[]>>
  add(attachment: ComposerAttachment): void
  clear(options?: ClearAttachmentsOptions): void
  remove(id: string): ComposerAttachment | null
  removeOccurrences(attachments: readonly ComposerAttachment[]): void
  setUploadState(id: string, uploadState?: ComposerAttachment['uploadState']): void
  update(attachment: ComposerAttachment): boolean
  updateIfCurrent(expected: ComposerAttachment, patch: ComposerAttachmentPatch): boolean
}

function attachmentOccurrenceIndex(attachments: ComposerAttachment[], expected: ComposerAttachment): number {
  return attachments.findIndex(item =>
    expected.occurrenceId === undefined
      ? item === expected
      : item.id === expected.id && item.occurrenceId === expected.occurrenceId
  )
}

export function createComposerAttachmentScope($attachments = atom<ComposerAttachment[]>([])): ComposerAttachmentScope {
  return {
    $attachments,
    add(attachment) {
      const previous = $attachments.get()
      const next = upsertAttachment(previous, attachment)
      $attachments.set(next)

      if (next.length > previous.length && attachment.kind !== 'url') {
        triggerHaptic('selection')
      }
    },
    clear(options) {
      if (!options?.retainPreviewUrls) {
        revokeAttachmentPreviewUrls($attachments.get())
      }

      $attachments.set([])
    },
    remove(id) {
      const current = $attachments.get()
      const removed = current.find(attachment => attachment.id === id) || null
      $attachments.set(current.filter(attachment => attachment.id !== id))
      revokeAttachmentPreviewUrl(removed?.previewUrl)

      return removed
    },
    removeOccurrences(attachments) {
      const current = $attachments.get()

      const submittedOccurrences = new Set(
        attachments
          .filter(attachment => attachment.occurrenceId !== undefined)
          .map(attachment => `${attachment.id}\u0000${attachment.occurrenceId}`)
      )

      const submittedLegacy = new Set(attachments.filter(attachment => attachment.occurrenceId === undefined))

      const next = current.filter(attachment =>
        attachment.occurrenceId === undefined
          ? !submittedLegacy.has(attachment)
          : !submittedOccurrences.has(`${attachment.id}\u0000${attachment.occurrenceId}`)
      )

      // Preserve clear()'s notification semantics even when no captured
      // occurrence remains. Some composer consumers settle local state on the
      // successful-submit store emission.
      $attachments.set(next)
    },
    setUploadState(id, uploadState) {
      const current = $attachments.get()
      const index = current.findIndex(attachment => attachment.id === id)

      if (index < 0) {
        return
      }

      const next = [...current]
      next[index] = { ...next[index]!, uploadState }
      $attachments.set(next)
    },
    update(attachment) {
      const current = $attachments.get()
      const index = current.findIndex(item => item.id === attachment.id)

      if (index < 0) {
        return false
      }

      const previous = current[index]
      const next = [...current]
      next[index] = attachment
      $attachments.set(next)

      if (previous?.previewUrl && previous.previewUrl !== attachment.previewUrl) {
        revokeAttachmentPreviewUrl(previous.previewUrl)
      }

      return true
    },
    updateIfCurrent(expected, patch) {
      const current = $attachments.get()
      const index = attachmentOccurrenceIndex(current, expected)

      if (index < 0) {
        return false
      }

      const next = [...current]
      next[index] = { ...next[index]!, ...patch }
      $attachments.set(next)

      return true
    }
  }
}

/** The main chat's scope — the module-level atom, so every existing
 *  `$composerAttachments` reader/writer IS this scope. */
export const mainComposerScope = createComposerAttachmentScope($composerAttachments)

// Per-thread draft stash for the decoupled composer. Session lifecycle never
// touches this — only ChatBar's scope swap reads/writes it. Text mirrors to
// localStorage; attachments are memory-only (blobs, upload state).
export const SESSION_DRAFTS_STORAGE_KEY = 'hermes:composer-drafts:v3'

export const NEW_SESSION_DRAFT_KEY = '__new__'
const MAX_PERSISTED_DRAFTS = 50
const EMPTY_SESSION_DRAFT: SessionDraft = { attachments: [], text: '' }

export interface SessionDraft {
  attachments: ComposerAttachment[]
  text: string
}

// Stable only for the lifetime of the current sessionless chat (#66662). The
// legacy behavior mapped every unsaved chat onto the single NEW_SESSION_DRAFT_KEY
// bucket, so a second New Chat inherited the first one's unsent text. Persisting
// the key (rather than just its text) lets a reload restore that exact fresh
// draft; starting another new chat rotates the key so abandoned unsent drafts
// cannot bleed into the next lifecycle.
const FRESH_DRAFT_STORAGE_KEY = 'hermes.desktop.freshDraftKey'

const createFreshDraftKey = (): string => `__new__:${randomUuid()}`

export const $freshDraftKey = atom<string>(storedString(FRESH_DRAFT_STORAGE_KEY) ?? NEW_SESSION_DRAFT_KEY)

export const freshDraftScope = (): string => $freshDraftKey.get()

export const rotateFreshDraftKey = (): string => {
  const key = createFreshDraftKey()
  $freshDraftKey.set(key)
  persistString(FRESH_DRAFT_STORAGE_KEY, key)

  return key
}

// A draft key belongs to a fresh-chat lifecycle when it is the legacy shared
// bucket or one of its per-instance successors (`__new__:<uuid>`, #66662).
export const isFreshDraftScope = (key: string | null | undefined): boolean =>
  typeof key === 'string' &&
  (key === NEW_SESSION_DRAFT_KEY ||
    (key.startsWith(NEW_SESSION_DRAFT_KEY) && key.length > NEW_SESSION_DRAFT_KEY.length))

// A null/empty scope IS the current fresh-chat lifecycle — resolve it to that
// lifecycle's own key so every stash/read/migrate consumer below addresses the
// active fresh bucket instead of the shared legacy one.
export const draftKey = (scope: string | null | undefined) => scope?.trim() || freshDraftScope()

/** Inline "Restored your unsent message" notice for the fresh draft (see
 *  `adoptGoneSessionDraft`). `null` = nothing to show. */
export interface RestoredDraftNotice {
  /** The dead stored-session key the text came from. */
  fromKey: string
  /** The text as restored — Undo only applies while the draft still equals it. */
  text: string
}

export const $restoredDraftNotice = atom<RestoredDraftNotice | null>(null)

const cloneDraft = (draft: SessionDraft): SessionDraft => ({
  attachments: draft.attachments.map(attachment => ({ ...attachment })),
  text: draft.text
})

// What this window last read from or wrote to the shared stash, cleared
// markers included. A reload applies only entries newer than this, and a write
// puts back any entry here that storage has since lost to a stale writer.
// The pre-v4 list seeds it before any window has written v4; after that only
// what an older build changed in that list since this build wrote it counts.
let persistedDrafts: StashEntries = hasDraftStash() ? readDraftStash() : readLegacyDrafts(SESSION_DRAFTS_STORAGE_KEY)

if (typeof window !== 'undefined' && hasDraftStash()) {
  const adopted = adoptLegacyEdits(persistedDrafts, SESSION_DRAFTS_STORAGE_KEY, Date.now())

  if (adopted) {
    persistedDrafts = compactDraftStash(adopted, MAX_PERSISTED_DRAFTS, Date.now())
    writeDraftStash(persistedDrafts, SESSION_DRAFTS_STORAGE_KEY)
  } else {
    // A list another window left one write behind: rewrite it before its receipt expires.
    healLegacyMirror(SESSION_DRAFTS_STORAGE_KEY)
  }
}

const draftsBySession = new Map<string, SessionDraft>(
  [...persistedDrafts]
    .filter((entry): entry is [string, StashEntry & { text: string }] => entry[1].text !== null)
    .map(([key, { text }]) => [key, { attachments: [], text }])
)

/**
 * Patch one asynchronous attachment occurrence wherever the main composer owns
 * it. During a session switch the occurrence moves from the live atom into the
 * per-session in-memory draft stash; a preview may finish on either side of
 * that handoff. Updating both stores is safe because occurrence ids are unique,
 * and merging into the latest object preserves concurrent staging metadata.
 */
export function patchMainComposerAttachmentOccurrence(
  expected: ComposerAttachment,
  patch: ComposerAttachmentPatch
): boolean {
  let updated = mainComposerScope.updateIfCurrent(expected, patch)

  for (const [key, draft] of draftsBySession) {
    const index = attachmentOccurrenceIndex(draft.attachments, expected)

    if (index < 0) {
      continue
    }

    const attachments = [...draft.attachments]
    attachments[index] = { ...attachments[index]!, ...patch }
    draftsBySession.set(key, { ...draft, attachments })
    updated = true
  }

  return updated
}

/**
 * What each unsent draft would be called, keyed the same way its text is.
 *
 * A draft has no session to carry a title, so the tab showing it reads this
 * instead of the "New session" placeholder. Written from `stashSessionDraft`,
 * the one funnel every composer's text already flows through — the debounce
 * that persists a draft is the same beat that renames its tab, so typing costs
 * nothing extra. Only tabs showing a draft subscribe, and each selects its own
 * key, so a rename repaints one label rather than the strip.
 *
 * Seeded from the persisted texts: a draft left open across a restart comes
 * back already named.
 */
export const $draftTitles = atom<Record<string, string>>(
  Object.fromEntries(
    [...draftsBySession].map(([key, draft]) => [key, deriveDraftTitle(draft.text)]).filter(([, title]) => title)
  )
)

/** Read one draft's title out of the map — for a `useStoreSelector`, so a tab
 *  repaints on its OWN rename rather than on every draft's. */
export const draftTitleIn = (titles: Record<string, string>, scope: string | null | undefined): string =>
  titles[draftKey(scope)] ?? ''

export const draftTitleFor = (scope: string | null | undefined): string => draftTitleIn($draftTitles.get(), scope)

function publishDraftTitle(key: string, title: string): void {
  const current = $draftTitles.get()

  if ((current[key] ?? '') === title) {
    return
  }

  const next = { ...current }

  if (title) {
    next[key] = title
  } else {
    delete next[key]
  }

  $draftTitles.set(next)
}

/**
 * Re-read the persisted drafts written by ANOTHER window into this one's map.
 *
 * Drafts are per-renderer state backed by shared localStorage, and the map
 * above is read exactly once at module load. Two windows on the same session
 * (HUD mode ⇄ the app window) therefore diverge the moment either one types:
 * whichever window mounted first keeps its stale copy forever, so text typed
 * in the HUD is simply gone when you return to the app.
 *
 * Merge, don't clobber: only entries saved after this window's own copy move,
 * and attachments (memory-only, so no other window can have seen or sent them)
 * stay put. An image-only draft is still a draft. An entry this window saved
 * later than storage now shows was overwritten from another window's stale
 * copy, so it is written back rather than taken as sent elsewhere.
 */
export function reloadPersistedDrafts(): void {
  syncPersistedDrafts()
}

function applyStoredDraft(key: string, entry: StashEntry): void {
  const attachments = draftsBySession.get(key)?.attachments ?? []

  if (entry.text !== null) {
    draftsBySession.set(key, { attachments, text: entry.text })
  } else if (attachments.length > 0) {
    draftsBySession.set(key, { attachments, text: '' })
  } else {
    draftsBySession.delete(key)
  }

  publishDraftTitle(key, deriveDraftTitle(entry.text ?? ''))
}

/** Merge storage with this window's copy (plus `local`, this window's new save) and write back what storage lacks. */
function syncPersistedDrafts(local?: { key: string; text: string | null }): void {
  const stored = readDraftStash()
  const merged: StashEntries = new Map()
  let rewrite = Boolean(local)

  for (const key of new Set([...stored.keys(), ...persistedDrafts.keys()])) {
    const theirs = stored.get(key)
    const mine = persistedDrafts.get(key)

    if (newerEntry(theirs, mine)) {
      applyStoredDraft(key, theirs!)
      merged.set(key, theirs!)
    } else if (newerEntry(mine, theirs) && !(mine!.text === null && !theirs)) {
      merged.set(key, mine!)
      rewrite = true
    } else if (theirs) {
      merged.set(key, theirs)
    }
  }

  if (local) {
    // Later than every entry any window has saved, whatever the wall clock
    // says, so the save wins the merge everywhere and the cap never evicts it.
    merged.set(local.key, { at: nextStashStamp(merged, Date.now()), text: local.text })
  }

  persistedDrafts = rewrite ? compactDraftStash(merged, MAX_PERSISTED_DRAFTS, Date.now()) : merged

  if (rewrite) {
    // Best-effort only — quota/private-mode must never break typing. A failed
    // write stays in persistedDrafts, so the next sync retries it.
    writeDraftStash(persistedDrafts, SESSION_DRAFTS_STORAGE_KEY)
  }
}

// localStorage `storage` events fire across Electron BrowserWindows of the
// same origin, so the other window's write is the sync signal.
if (typeof window !== 'undefined') {
  window.addEventListener('storage', event => {
    if (event.key === DRAFT_STASH_STORAGE_KEY || event.key === null) {
      syncPersistedDrafts()
      healLegacyMirror(SESSION_DRAFTS_STORAGE_KEY)
    }
  })
}

/**
 * Push a composer's live text into the shared stash (`flush`), or repaint it
 * from the stash (`reload`).
 *
 * Both halves of the HUD handoff need this. The stash is the only draft state
 * two windows share, but a mounted composer only consults it when its session
 * scope changes — so entering HUD mode has to flush the app window's in-editor
 * text down to the stash before the HUD boots and reads it, and leaving has to
 * repaint the app's editor from whatever the HUD left behind (usually empty,
 * because the HUD sent it).
 *
 * Dispatched synchronously, unlike the focus bus: the flush must complete
 * before the HUD window is created.
 */
const DRAFT_SYNC_EVENT = 'hermes:composer-draft-sync'

export type ComposerDraftSyncMode = 'flush' | 'reload'

interface ComposerDraftSyncDetail {
  mode: ComposerDraftSyncMode
  target: string
}

export function requestComposerDraftSync(mode: ComposerDraftSyncMode, target = 'main'): void {
  if (typeof window !== 'undefined') {
    window.dispatchEvent(new CustomEvent<ComposerDraftSyncDetail>(DRAFT_SYNC_EVENT, { detail: { mode, target } }))
  }
}

export function onComposerDraftSyncRequest(handler: (detail: ComposerDraftSyncDetail) => void): () => void {
  if (typeof window === 'undefined') {
    return () => undefined
  }

  const listener = (event: Event) => handler((event as CustomEvent<ComposerDraftSyncDetail>).detail)
  window.addEventListener(DRAFT_SYNC_EVENT, listener)

  return () => window.removeEventListener(DRAFT_SYNC_EVENT, listener)
}

export function stashSessionDraft(scope: string | null | undefined, text: string, attachments: ComposerAttachment[]) {
  const key = draftKey(scope)

  draftsBySession.delete(key)

  if (text.trim() || attachments.length > 0) {
    draftsBySession.set(key, cloneDraft({ attachments, text }))
  } else if (isFreshDraftScope(key)) {
    // The fresh draft was sent or emptied — a restore notice has nothing left
    // to undo.
    $restoredDraftNotice.set(null)
  }

  const saved = draftsBySession.get(key)?.text || null
  const previous = persistedDrafts.get(key)

  // Clearing a draft this window never saw saved has nothing to clear.
  if (saved !== null || previous?.text) {
    syncPersistedDrafts({ key, text: saved })
  }

  publishDraftTitle(key, deriveDraftTitle(text))
}

export function takeSessionDraft(scope: string | null | undefined): SessionDraft {
  const stashed = draftsBySession.get(draftKey(scope))

  return stashed ? cloneDraft(stashed) : EMPTY_SESSION_DRAFT
}

/** When `scope`'s saved draft was last written (ms; 0 for one carried over from the unstamped v3
 *  list), or undefined when none is saved. */
export const savedDraftAt = (scope: string | null | undefined): number | undefined =>
  persistedDrafts.get(draftKey(scope))?.at

export const clearSessionDraft = (scope: string | null | undefined) => stashSessionDraft(scope, '', [])

/**
 * Stored draft scopes that hold content, excluding the new-chat key. The
 * dead-session prune sweeps these to discard drafts whose sessions no longer
 * exist on the backend; the new-chat draft is never a session reference.
 */
export function stashedDraftScopes(): string[] {
  return [...draftsBySession.keys()].filter(key => key !== NEW_SESSION_DRAFT_KEY)
}

/**
 * Move a stashed composer draft from one session key onto another.
 *
 * Auto-compression rotates the live stored tip id (root → continuation) while
 * the user may still be typing. Drafts keyed on the obsolete tip would otherwise
 * vanish from the composer when selection follows the new tip. A new chat is
 * stored under the pre-session key until its first session id arrives. No-op
 * unless the destination resolves, the keys differ, and the source has content. Does not overwrite a
 * non-empty destination draft.
 */
export function migrateSessionDraft(fromKey: string | null | undefined, toKey: string | null | undefined): boolean {
  const from = draftKey(fromKey)
  const to = draftKey(toKey)

  if (!toKey?.trim() || from === to) {
    return false
  }

  const source = draftsBySession.get(from)

  if (!source || (!source.text.trim() && source.attachments.length === 0)) {
    return false
  }

  const dest = draftsBySession.get(to)

  if (dest && (dest.text.trim() || dest.attachments.length > 0)) {
    return false
  }

  stashSessionDraft(toKey, source.text, source.attachments)
  clearSessionDraft(fromKey)

  return true
}

/**
 * The stored id the pre-session chat is about to be re-homed onto, announced
 * by the site that assigns it (first-send `session.create`, cold-start
 * resume-last-session) and consumed by the composer's scope swap.
 *
 * The swap cannot tell an assignment apart from the user opening another
 * session from a new chat — both flip the scope from the `__new__` bucket to
 * a concrete id — and only the assignment may carry the draft along: a
 * sidebar click keeps per-scope drafts where they were typed.
 */
let announcedNewSessionDraftKey: string | null = null

export function announceNewSessionDraftKey(toKey: string | null | undefined): void {
  announcedNewSessionDraftKey = toKey?.trim() || null
}

/** Consume the announcement; move the `__new__` draft when it names `toKey`.
 *  True when the announcement named `toKey` (the caller hands the rest of the
 *  pre-session chat over), even if there was no draft text to move. */
export function adoptNewSessionDraft(toKey: string | null | undefined): boolean {
  const announced = announcedNewSessionDraftKey
  announcedNewSessionDraftKey = null

  if (!announced || announced !== toKey?.trim()) {
    return false
  }

  migrateSessionDraft(null, toKey)

  return true
}

/**
 * Recovery for the unsent text of a session that turned out to be GONE
 * (#111868): deleted, or a stale id from a wiped / renamed backend.
 *
 * The resume path already drops such a window to a fresh draft without
 * toasting or looping (62af32efe7c, bounded by `goneSessionVerdict`). The
 * composer's draft stash is keyed per stored session, so the text the user
 * typed into the dead id is not lost — but nothing will ever open that key
 * again, so it is invisible. The gone verdict announces the dead key here;
 * the composer's scope swap (concrete id → the `__new__` bucket) consumes
 * it AFTER the outgoing cleanup stashed the live editor text, so even
 * keystrokes still inside the persist debounce ride along.
 *
 * Offer, don't hijack: the fresh draft is seeded and an inline notice with
 * Undo is published — no navigation, no focus steal, no toast. Fires once:
 * the source key is cleared by the move, so re-opening the dead id later
 * finds nothing to restore.
 */
let announcedGoneSessionDraftKey: string | null = null

export function announceGoneSessionDraft(fromKey: string | null | undefined): void {
  announcedGoneSessionDraftKey = fromKey?.trim() || null
}

/**
 * Consume the announcement when a composer enters the fresh-draft scope.
 * Moves the dead key's draft into the `__new__` bucket and publishes the
 * notice. Declines (no notice) when nothing was announced, the key holds no
 * text, or the user is already composing a new chat — never clobber what
 * they are typing. Keyed on the announcement, not on the composer observing
 * an id → fresh transition: the composer can remount across the drop (a
 * loading route mounts no composer), so the dead scope may never have been
 * this instance's previous scope.
 */
export function adoptGoneSessionDraft(): boolean {
  const announced = announcedGoneSessionDraftKey
  announcedGoneSessionDraftKey = null

  if (!announced) {
    return false
  }

  const source = draftsBySession.get(draftKey(announced))

  if (!source?.text.trim()) {
    return false
  }

  const dest = draftsBySession.get(freshDraftScope())

  if (dest && (dest.text.trim() || dest.attachments.length > 0)) {
    return false
  }

  const { attachments, text } = source
  stashSessionDraft(null, text, attachments)
  clearSessionDraft(announced)
  $restoredDraftNotice.set({ fromKey: announced, text })

  return true
}

export function dismissRestoredDraftNotice(): void {
  recordFriction('notice_dismissed', 'restored_draft')
  $restoredDraftNotice.set(null)
}

/**
 * Undo the restore: put the text back under the dead key (where it was,
 * still recoverable by the same path) and empty the fresh draft. Only while
 * the live text is still exactly what was restored — once the user has
 * edited it, Undo would destroy their work, so it only dismisses the notice.
 * Returns whether the fresh draft was emptied (the caller repaints).
 */
export function undoRestoredDraft(liveText: string): boolean {
  const notice = $restoredDraftNotice.get()
  $restoredDraftNotice.set(null)

  if (!notice || liveText !== notice.text) {
    return false
  }

  const current = draftsBySession.get(freshDraftScope())
  stashSessionDraft(notice.fromKey, notice.text, current?.attachments ?? [])
  clearSessionDraft(null)
  recordDislike('undo', 'restored_draft')

  return true
}

export function setComposerDraft(value: string) {
  $composerDraft.set(value)
}

export function appendComposerDraft(value: string) {
  const text = value.trim()

  if (!text) {
    return
  }

  const current = $composerDraft.get()
  const separator = current && !current.endsWith('\n') ? '\n\n' : ''

  $composerDraft.set(`${current}${separator}${text}`)
}

export function appendComposerInline(value: string) {
  const text = value.trim()

  if (!text) {
    return
  }

  const current = $composerDraft.get().trimEnd()
  const separator = current ? ' ' : ''

  $composerDraft.set(`${current}${separator}${text}`)
}

export function clearComposerDraft() {
  $composerDraft.set('')
}

// Main-scope conveniences — the names the app has always used.
export const addComposerAttachment = (attachment: ComposerAttachment) => mainComposerScope.add(attachment)
export const removeComposerAttachment = (id: string) => mainComposerScope.remove(id)

/** Replace an existing attachment in place by id. No-op (returns false) when the
 * id is gone — e.g. the user removed the chip while an eager upload was still in
 * flight, so a late success must NOT resurrect it. Use this instead of
 * addComposerAttachment for async results that may land after a removal. */
export const updateComposerAttachment = (attachment: ComposerAttachment) => mainComposerScope.update(attachment)

export const clearComposerAttachments = () => mainComposerScope.clear()

/** Update only the upload state of an existing attachment (no-op if it's gone,
 * e.g. the user removed it mid-upload). Pass `undefined` to clear it. */
export const setComposerAttachmentUploadState = (id: string, uploadState?: ComposerAttachment['uploadState']) =>
  mainComposerScope.setUploadState(id, uploadState)

const TERMINAL_REF_RE = /@terminal:(`[^`\n]+`|"[^"\n]+"|'[^'\n]+'|\S+)/g

function unquoteRefValue(raw: string) {
  const head = raw[0]
  const tail = raw[raw.length - 1]
  const quoted = (head === '`' && tail === '`') || (head === '"' && tail === '"') || (head === "'" && tail === "'")

  return (quoted ? raw.slice(1, -1) : raw).replace(/[,.;!?]+$/, '').trim()
}

function terminalLabelsFromDraft(draft: string) {
  const labels: string[] = []
  const seen = new Set<string>()

  for (const match of draft.matchAll(TERMINAL_REF_RE)) {
    const label = unquoteRefValue(match[1] || '')

    if (!label || seen.has(label)) {
      continue
    }

    seen.add(label)
    labels.push(label)
  }

  return labels
}

/** True when the draft still carries `@terminal:` chips (not already-frozen transport). */
export function draftHasTerminalChips(draft: string): boolean {
  return terminalLabelsFromDraft(draft).length > 0
}

export function setComposerTerminalSelection(label: string, text: string) {
  const nextLabel = label.trim()
  const nextText = text.trim()

  if (!nextLabel || !nextText) {
    return
  }

  const current = $composerTerminalSelections.get()

  if (current[nextLabel] === nextText) {
    return
  }

  $composerTerminalSelections.set({
    ...current,
    [nextLabel]: nextText
  })
}

export function reconcileComposerTerminalSelections(draft: string) {
  const current = $composerTerminalSelections.get()
  const labels = new Set(terminalLabelsFromDraft(draft))
  let changed = false
  const next: Record<string, string> = {}

  for (const [label, text] of Object.entries(current)) {
    if (!labels.has(label)) {
      changed = true

      continue
    }

    next[label] = text
  }

  if (changed) {
    $composerTerminalSelections.set(next)
  }
}

function terminalFence(text: string) {
  return `\`\`\`terminal\n${text}\n\`\`\``
}

function stripTerminalRefTokens(draft: string) {
  return draft
    .replace(new RegExp(TERMINAL_REF_RE.source, 'g'), '')
    .replace(/[ \t]{2,}/g, ' ')
    .replace(/[ \t]+\n/g, '\n')
    .replace(/\n[ \t]+/g, '\n')
    .trim()
}

export interface ComposerTransportPayload {
  /** Model-facing text: fenced selection blocks with `@terminal:` chips stripped. */
  transportText: string
  /** UI-facing text: original chip form, when it differs from transport. */
  displayText: string
  /** Chip labels whose selection text is missing from the in-memory map. */
  missingLabels: string[]
}

/**
 * Freeze `@terminal:` chips into transport text at the moment a message
 * crosses a send/steer/enqueue boundary. The selection map is memory-only and
 * label-colliding — later resolve against it can inject a different pane's
 * output (#77078). Callers that cannot resolve every chip must fail closed.
 *
 * Idempotent: already-frozen transport (no chips) is returned unchanged.
 */
export function freezeComposerTransportPayload(
  draft: string,
  selections: Record<string, string> = $composerTerminalSelections.get()
): ComposerTransportPayload {
  const labels = terminalLabelsFromDraft(draft)

  if (labels.length === 0) {
    return { transportText: draft, displayText: draft, missingLabels: [] }
  }

  const missingLabels = labels.filter(label => !selections[label]?.trim())

  if (missingLabels.length > 0) {
    return { transportText: draft, displayText: draft, missingLabels }
  }

  const existingFences = new Set(draft.match(/```terminal\n[\s\S]*?\n```/g) ?? [])
  const fences: string[] = []

  for (const label of labels) {
    const text = selections[label]?.trim()

    if (!text) {
      continue
    }

    const fence = terminalFence(text)

    if (!existingFences.has(fence)) {
      fences.push(fence)
      existingFences.add(fence)
    }
  }

  const remainder = stripTerminalRefTokens(draft)
  const transportText = [...fences, remainder].filter(Boolean).join('\n\n')

  return { transportText, displayText: draft, missingLabels: [] }
}

export function terminalContextBlocksFromDraft(draft: string) {
  const labels = terminalLabelsFromDraft(draft)

  if (labels.length === 0) {
    return []
  }

  const selections = $composerTerminalSelections.get()

  return labels.flatMap(label => {
    const text = selections[label]?.trim()

    if (!text) {
      return []
    }

    return terminalFence(text)
  })
}

export function clearComposerTerminalSelections() {
  if (Object.keys($composerTerminalSelections.get()).length === 0) {
    return
  }

  $composerTerminalSelections.set({})
}

function upsertAttachment(attachments: ComposerAttachment[], attachment: ComposerAttachment) {
  const index = attachments.findIndex(item => item.id === attachment.id)

  if (index < 0) {
    return [...attachments, attachment]
  }

  const previous = attachments[index]
  const next = [...attachments]
  next[index] = attachment

  if (previous?.previewUrl && previous.previewUrl !== attachment.previewUrl) {
    revokeAttachmentPreviewUrl(previous.previewUrl)
  }

  return next
}