wherever-dev 0.23.0 → 0.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/assistant-channels.d.ts +14 -0
  3. package/dist/assistant-channels.d.ts.map +1 -1
  4. package/dist/assistant-channels.js.map +1 -1
  5. package/dist/assistant-controller.d.ts.map +1 -1
  6. package/dist/assistant-controller.js +5 -2
  7. package/dist/assistant-controller.js.map +1 -1
  8. package/dist/assistant-folder.d.ts +14 -1
  9. package/dist/assistant-folder.d.ts.map +1 -1
  10. package/dist/assistant-folder.js +33 -2
  11. package/dist/assistant-folder.js.map +1 -1
  12. package/dist/assistant-tool-text.d.ts.map +1 -1
  13. package/dist/assistant-tool-text.js +5 -1
  14. package/dist/assistant-tool-text.js.map +1 -1
  15. package/dist/assistant-tools.d.ts +18 -3
  16. package/dist/assistant-tools.d.ts.map +1 -1
  17. package/dist/assistant-tools.js +58 -4
  18. package/dist/assistant-tools.js.map +1 -1
  19. package/dist/attach-file-tool.d.ts +17 -0
  20. package/dist/attach-file-tool.d.ts.map +1 -1
  21. package/dist/attach-file-tool.js +44 -37
  22. package/dist/attach-file-tool.js.map +1 -1
  23. package/dist/cli-requests.d.ts +2 -1
  24. package/dist/cli-requests.d.ts.map +1 -1
  25. package/dist/cli-requests.js.map +1 -1
  26. package/dist/index.js +25 -7
  27. package/dist/index.js.map +1 -1
  28. package/dist/session-pool.d.ts +9 -1
  29. package/dist/session-pool.d.ts.map +1 -1
  30. package/dist/session-pool.js +58 -2
  31. package/dist/session-pool.js.map +1 -1
  32. package/dist/telegram-channel.d.ts +14 -2
  33. package/dist/telegram-channel.d.ts.map +1 -1
  34. package/dist/telegram-channel.js +41 -8
  35. package/dist/telegram-channel.js.map +1 -1
  36. package/dist/telegram-replies.d.ts +18 -0
  37. package/dist/telegram-replies.d.ts.map +1 -1
  38. package/dist/telegram-replies.js +41 -23
  39. package/dist/telegram-replies.js.map +1 -1
  40. package/package.json +1 -1
  41. package/public/_app/immutable/chunks/{CLKlGLL7.js → Ba0iJyN2.js} +2 -2
  42. package/public/_app/immutable/chunks/{CLKlGLL7.js.map → Ba0iJyN2.js.map} +1 -1
  43. package/public/_app/immutable/chunks/BfCwf84t.js +2 -0
  44. package/public/_app/immutable/chunks/{BHw5ar2A.js.map → BfCwf84t.js.map} +1 -1
  45. package/public/_app/immutable/chunks/{FePVnZ_7.js → jBzVXpuo.js} +2 -2
  46. package/public/_app/immutable/chunks/{FePVnZ_7.js.map → jBzVXpuo.js.map} +1 -1
  47. package/public/_app/immutable/entry/{app.BJxkSaKZ.js → app.CePvTLA2.js} +3 -3
  48. package/public/_app/immutable/entry/{app.BJxkSaKZ.js.map → app.CePvTLA2.js.map} +1 -1
  49. package/public/_app/immutable/entry/start.MB6ZjVGe.js +2 -0
  50. package/public/_app/immutable/entry/start.MB6ZjVGe.js.map +1 -0
  51. package/public/_app/immutable/nodes/{0.DGFJlad5.js → 0.ydSaxbgZ.js} +2 -2
  52. package/public/_app/immutable/nodes/{0.DGFJlad5.js.map → 0.ydSaxbgZ.js.map} +1 -1
  53. package/public/_app/immutable/nodes/{1.Cy3IVwDh.js → 1.T9BouUHS.js} +2 -2
  54. package/public/_app/immutable/nodes/{1.Cy3IVwDh.js.map → 1.T9BouUHS.js.map} +1 -1
  55. package/public/_app/immutable/nodes/2.D_6BVhWL.js +123 -0
  56. package/public/_app/immutable/nodes/2.D_6BVhWL.js.map +1 -0
  57. package/public/_app/version.json +1 -1
  58. package/public/index.html +10 -10
  59. package/public/service-worker.js +1 -1
  60. package/public/_app/immutable/chunks/BHw5ar2A.js +0 -2
  61. package/public/_app/immutable/entry/start.CRP1MCwE.js +0 -2
  62. package/public/_app/immutable/entry/start.CRP1MCwE.js.map +0 -1
  63. package/public/_app/immutable/nodes/2.eb9p7ShF.js +0 -123
  64. package/public/_app/immutable/nodes/2.eb9p7ShF.js.map +0 -1
@@ -0,0 +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AAWv1C,EAAIgpE,EAAY,GAAArqE,GAAA4kD,GAAA,sCAgB5BwmB,EAAY,GAMtB7pE,GAAAnC,EAAA,IAAAiC,EAAAsqE,EAAA,EACN,CAAAtqE,EAAAsmB,EAAA,IACD7a,EAAQ,IAAAzL,EAAKu1C,EAAW,EAAC,WAAW,EACxBn1C,EAAArC,EAAA,KAAAiC,EAAAsqE,EAAY,KAAAtqE,EACxBsmB,EAAS,GAAAtmB,EAAI21C,EAAS,KAAIqzB,EAAY,OAbzC+C,GAAAC,GAAA,2BAEY1B,EAAY,oEAEvB7S,EAAY,aAEF7qD,EAAGsQ,KAAUoC,GAAU1S,EAAC5M,EAAE03D,EAAW,EAAEx6C,EAAK,oHAQzC,WAAAgrD,IAAU,oBAAmB,MAT3C,aAAK,mBAAL,YAAK9+C,EAAA,oBAJMihD,GAASjhD,EAAA,UAATihD,EAAS,oBA/CjBrqE,EAAAwpE,EAAQ,EAAA7qE,EAAA6jD,EAAA,EAAAxiD,EAWHyL,EAAQ,GAAAzL,EAAIu1C,EAAW,EAAC,YAAW52C,EAAAqkD,GAAA,GAAArkD,EAAAolD,GAAA,QA7P7C5H,CAAG,WAAHA,EAAG,GAoTH8vB,GAAkBpkB,GAAA,+BAIjB,IAAAqkB,EAAA7pB,GAAA,YAAA6pB,EAAA,IAAAzlD,EAGgBkhD,GAAc,EAAK,GAHnC7+C,EAAAxqB,EAAA4tE,CAAA,cADGvE,EAAW,GAAAhpE,EAAAmlD,EAAA,IAzkBhBp4B,EAAAnE,EAAA,WAICE,GAAA,gBAAAznB,EACmB2nE,EAAA,EAChB,gBACA,mBAAmB,iKAgRpBxZ,GAAA,IAAA1nC,EACgBkhD,MAAeA,EAAW,qBAxUtC","names":["html","node","get_value","is_controlled","svg","mathml","skip_warning","anchor","value","parent_node","hydrating","set_hydrate_node","get_first_child","template_effect","effect","active_effect","hydrate_next","assign_nodes","remove_effect_dom","hydrate_node","next","last","COMMENT_NODE","get_next_sibling","w.hydration_mismatch","HYDRATION_ERROR","ns","NAMESPACE_SVG","NAMESPACE_MATHML","wrapper","create_element","head","hash","render_fn","previous_hydrate_node","was_hydrating","head_anchor","set_hydrating","start","create_text","block","e","branch","HEAD_EFFECT","r","t","f","n","o","clsx","_clsx","to_class","directives","classname","to_style","styles","set_class","dom","is_html","prev_classes","next_classes","prev","CLASS_CACHE","next_class_name","set_style","prev_styles","next_styles","STYLE_CACHE","next_style_attr","select_option","select","mounting","is_array","w.select_multiple_invalid_value","option","get_option_value","option_value","is","init_select","observer","teardown","bind_select_value","get","set","batches","listen_to_event_and_reset_event","is_reset","query","selected_option","current_batch","batch","bind_value","input","is_numberlike_input","to_number","tick","end","length","new_length","untrack","render_effect","pending","bind_group","inputs","group_index","is_checkbox","binding_group","hydration_mismatch","index","get_binding_group_value","queue_micro_task","a","b","hydration_input","bind_checked","group","__value","checked","i","type","ssr","prerender","url","p","resolve","host","canonicalURL","previewImage","isHome","$.derived","$$props","metadata","name","description","page","$.head","$$anchor","meta","$.first_child","fragment","meta_1","$$render","consequent_1","meta_3","$.sibling","meta_4","meta_5","meta_6","meta_7","meta_8","meta_9","meta_10","meta_11","link","link_1","link_2","link_3","meta_12","meta_13","meta_14","meta_15","meta_16","$.get","$0","$1","$.set_attribute","$2","$3","themeColor","appleStatusBarStyle","version","audioCtx","getContext","Ctor","playNote","ctx","frequency","startTime","duration","peakGain","osc","gain","attack","customAudioCache","playCustomSound","el","playInvitingBeep","soundUrl","now","parseSkillInvocation","content","trimmed","open","closeIdx","rest","spaceIdx","skillName","args","skillInvocationIdentity","parsed","noop","safe_not_equal","subscribe","store","callbacks","unsub","get_store_value","_","subscriber_queue","writable","stop","subscribers","new_value","run_queue","subscriber","update","fn","subscribe2","run2","invalidate","FRAME_CHUNK_PARAM","FRAME_CHUNK_VERSION","MARK","FrameReassembler","text","nl","id","seqRaw","countRaw","seq","count","full","generateClientKey","UPLOAD_CAPABILITY","KiB","UPLOAD_WINDOW_MIN","UPLOAD_WINDOW_MAX","UPLOAD_CHUNK_MAX","UPLOAD_WINDOW_SECONDS","UPLOAD_RATE_ALPHA","LEGACY_READ_BYTES","NOT_READABLE_MESSAGE","encodeChunkFrame","uploadId","offset","payload","frame","view","bytesToBinaryString","bytes","out","generateUploadId","c","UploadReadError","uploadReadError","err","shortReadError","socketHost","fnv1a","h","serverKey","config","defaultState","WhereverClient","newConfig","preserveState","key","stamped","s","protocol","params","wsUrl","WebSocketImpl","wsOptions","currentWs","reassembler","inBadChunkRun","onOpen","queued","cached","rejoinFile","rejoinCwd","rejoinModel","onMessage","event","rawData","piece","msg","onClose","onError","data","resetState","dyingWs","swallow","st","sendBeat","checkLiveness","sinceLastTick","silentFor","streaming","threshold","ws","reason","onReturn","grace","probedWs","sentAt","graceMs","immediate","deadWs","scheme","preserve","listener","active","lastThinking","m","newMsg","lastAssistant","steering","newMessages","restoredQueued","echoIdentity","existing","lastUserMessage","toolArgs","k","v","finalizedMessages","startedAt","isForce","toolMsg","result","aborted","effectiveIsError","toolImages","endedAt","errorPrefix","message","abortedAt","matchesPendingLoad","isRequestedCreate","abandoned","sid","rejectedHydration","before","current","cloned","readOnly","sessionIdForPending","inFlight","candidates","mapped","totalCount","historyContents","seen","undelivered","older","lines","rawMessages","sessionId","applyStreamingTail","openCalls","openById","removeFromNameQueue","tName","idx","q","at","callIdx","isError","interrupted","call","tArgs","allOpen","idxs","lastOpenIdx","lastIndex","lastMsg","options","raw","command","isSudo","optimisticTool","messages","have","restored","remaining","arr","messageId","timer","x","confirmedId","target","targetPath","mutate","snapshot","sessionFile","cwd","model","keepShownSession","sent","entryId","gitInit","createRemote","repoVisibility","cloneRemote","action","trimmedUrl","previous","password","prompt","updates","cb","filename","source","reject","signal","upload","all","chunked","parts","chars","size","chunk","elapsed","sample","window","gen","socket","state","error","progress","code","wasOnWire","keepSessionId","GATED_KNOBS","isGated","knob","isKnobActive","knobs","shouldSignalConversationMode","resolveConversationMode","override","defaultOn","buildAttachmentMessage","paths","fileLines","isSessionPendingOpen","isSearchActive","decideHashJoin","shouldDropStaleHash","abortError","postUpload","opts","acked","report","xhr","settled","onSignal","finish","fail","readable","fileStillReadable","file","browserTimeZone","timezoneReportFrame","timezone","DRAFTS_CACHE_KEY","LEGACY_DRAFTS_KEY","sortDrafts","drafts","parseDrafts","normalizeDrafts","item","d","createdAt","updatedAt","serializeDrafts","decideDraftLoad","currentText","applyDraft","draftText","mode","draftToConsumeOnSend","sentText","draft","draftPreview","max","flat","draftOriginLabel","CONVERSATION_CACHE_DB","STORE","SAVED_AT_INDEX","DB_VERSION","MAX_CACHED_SESSIONS","MAX_RECORD_BYTES","WRITE_THROTTLE_MS","normalizeMessages","images","refs","utf8Length","trimToByteCap","record","maxBytes","total","sizes","promisify","req","done","tx","createConversationCache","factory","maxSessions","maxRecordBytes","dbPromise","db","withStore","fallback","completed","deleteKeysWhere","drop","cursor","keys","old","createWriteThrottle","write","intervalMs","run","cancel","BOOT_CACHE_TIMEOUT_MS","cacheSnapshot","canLoadOlderHistory","decideReturn","readBootCache","timeoutMs","settle","read","runBoot","deps","hydrated","retainCurrentServer","cache","clearCacheOnDisconnect","throttle","handleHydrationRejected","w","hashId","getStoredConfig","stored","saveConfig","defaultPort","loc","getConfig","adoptTokenFromUrlOnce","defaultHost","beepDefaultStore","BEEP_OVERRIDES_KEY","loadBeepOverrides","saveBeepOverrides","map","beepOverridesStore","beepSessionKeyStore","getBeepDefault","getBeepSoundUrl","setBeepSoundUrl","beepSessionOverride","derived","$key","$overrides","beepEnabled","$override","$default","setBeepDefault","setBeepSessionOverride","setBeepSessionKey","DIRECT_SEND_KEY","readDirectSend","autoSendOnSpeechEnd","getAutoSendOnSpeechEnd","setAutoSendOnSpeechEnd","conversationModeDefaultStore","CONVERSATION_MODE_OVERRIDES_KEY","loadConversationModeOverrides","saveConversationModeOverrides","conversationModeOverridesStore","conversationModeSessionKeyStore","conversationModeSessionOverride","conversationModeDefault","speakRepliesStore","collapseLongRepliesStore","micReopensAfterReplyStore","conversationMode","speakReplies","collapseLongReplies","micReopensAfterReply","getConversationMode","getConversationModeDefault","setConversationModeDefault","setConversationModeSessionOverride","setConversationModeSessionKey","setSpeakReplies","setCollapseLongReplies","setMicReopensAfterReply","getConversationKnobs","setConversationModeBundle","on","sendOptions","CLIENT_KEY_STORAGE","getClientKey","persistClientKey","initialConfig","client","conversationCache","cacheWrites","snap","hydratedServerKey","currentServerKey","prevCachedMessages","flushConversationCache","clearConversationCache","readBootConversation","hydrateFromCache","took","prevIsStreaming","prevSessionKey","sessionKey","pendingSearch","deliverPendingSearch","files","failed","res","uploadFile","composerPrefill","prefillComposer","pendingForkPrefill","forkedMsg","switchSession","applyAssistantPointer","setCurrentSession","fetchSessions","setSessionWorking","connect","isSecure","disconnect","suspend","resume","noteVisible","hasSuspendedSession","hasActiveSession","filePickerActiveUntil","FILE_PICKER_GRACE_MS","beginFilePicker","endFilePicker","isFilePickerActive","sendMessage","resendMessage","discardMessage","abort","cancelSteer","reloadResources","joinSession","dropStaleHash","forkSession","createSession","runSearch","folder","searchFolderStore","searchCreateRemoteStore","openAssistant","resetAssistant","leaveSession","loadMoreHistory","continueFolderConflict","ping","clearMessages","setConfig","port","token","hideThinking","hideTools","updateConfig","dismissSessionError","dismissNotice","sendSudoPassword","cancelSudoPrompt","changeModel","startRestore","cancelRestore","reloadSession","piState","$s","isConnected","isStreaming","connectionError","currentSession","folderConflict","folderMissing","restoreState","isInterrupted","pendingSteering","sessionError","sessionNotice","sudoPrompt","isReadOnly","activeSessionInfo","contextUsage","isCreatingSession","isLoadingSession","isResyncing","isAgentPending","hasMoreHistory","isLoadingMoreHistory","uploadFileViaPost","onProgress","baseUrl","getBaseUrl","getToken","fileByteSource","downloadFileUrl","path","toolImageSrc","img","method","uploadMethodStore","draftsRequest","pathname","init","errData","fetchDrafts","saveDraftRemote","deleteDraftRemote","deleteSession","extractSayText","argsObj","outstandingUtterances","idleWaiters","settleOneUtterance","waiters","whenTtsIdle","ttsUnlocked","gestureUnlockArmed","disarmGestureUnlock","resumeQueue","synth","PRIMING_TEXT","loadVoices","resolveUtteranceLang","lang","voices","wanted","primary","voice","unlockTts","browserSpeechDeps","Utterance","priming","GESTURE_EVENTS","armTtsGestureUnlock","onGesture","speakUtterance","spoken","settleOnce","utterance","resolvedLang","localHost","$.state","localPort","localToken","localHideThinking","localBeepDefault","localBeepSoundUrl","localConversationMode","localSpeakReplies","localCollapseLongReplies","localMicReopensAfterReply","saving","connected","$isConnected","onMount","$.set","handleTestBeep","handleConfigChange","handleConnect","handleDisconnect","handleReload","div","root","div_1","div_2","$.child","$.remove_input_defaults","div_3","input_1","div_4","input_2","div_5","input_3","div_6","input_4","div_7","div_8","input_5","button","div_9","div_10","input_6","div_11","input_7","div_12","input_8","div_13","input_9","div_14","button_1","root_1","$.delegated","$.append","button_2","root_2","consequent","alternate","button_3","$$value","pushSupported","g","urlB64ToUint8Array","base64String","padding","base64","pushUrl","qs","ok","sameKey","isThisDeviceSubscribed","pm","sub","subscribeThisDevice","publicKey","unsubscribeThisDevice","describePushError","permission","applyPushToggle","want","subscribed","sendTestNotification","deliveries","currentSessionId","$.prop","supported","busy","testing","testResult","testError","checkbox","manager","toggle","fetchConfig","sendTest","p_1","root_3","$.reset","root_4","text_1","node_3","p_2","root_5","text_2","consequent_2","p_3","root_6","text_3","consequent_3","consequent_4","$.set_checked","telegramSectionVisible","status","pairingInstruction","canRepair","requestTelegramRepair","browserDeps","copyText","doc","area","label","copyState","copy","onDestroy","$.set_text","$.user_effect","waiting","repair","$.template_effect","fragment_1","span","node_2","CopyButton","fragment_2","p_4","root_7","consequent_6","p_5","root_8","consequent_7","p_6","root_9","consequent_8","IMAGE_EXTS","AUDIO_EXTS","VIDEO_EXTS","extensionOf","base","dot","mediaKind","ext","extractDownloadablePath","toolName","pathVal","FALLBACK_MAX_CHARS","spokenFallbackText","reply","maxChars","plain","sentences","sentence","shouldSpeakFallback","LONG_REPLY_CHAR_THRESHOLD","isLongReply","shouldCollapseReply","_getDefaults","_defaults","changeDefaults","newDefaults","noopTest","edit","regex","opt","obj","val","valSource","other","bull","indent","newline","blockCode","fences","hr","heading","bullet","lheadingCore","lheading","lheadingGfm","_paragraph","blockText","_blockLabel","def","list","_tag","_comment","paragraph","blockquote","blockNormal","gfmTable","blockGfm","blockPedantic","escape","inlineCode","br","inlineText","_punctuation","_punctuationOrSpace","_notPunctuationOrSpace","punctuation","_punctuationGfmStrongEm","_punctuationOrSpaceGfmStrongEm","_notPunctuationOrSpaceGfmStrongEm","blockSkip","emStrongLDelimCore","emStrongLDelim","emStrongLDelimGfm","emStrongRDelimAstCore","emStrongRDelimAst","emStrongRDelimAstGfm","emStrongRDelimUnd","anyPunctuation","autolink","_inlineComment","tag","_inlineLabel","reflink","nolink","reflinkSearch","inlineNormal","inlinePedantic","inlineGfm","inlineBreaks","inline","escapeReplacements","getEscapeReplacement","ch","escape2","html2","encode","cleanUrl","href","splitCells","tableRow","row","match","str","escaped","curr","cells","rtrim","invert","l","suffLen","findClosingBracket","level","outputLink","cap","link2","lexer2","rules","title","indentCodeCompensation","matchIndentToCode","indentToCode","matchIndentInNode","indentInNode","_Tokenizer","options2","src","tokens","inBlockquote","currentLines","currentRaw","top","lastToken","oldToken","newText","newToken","isordered","list2","itemRegex","endsWithBlankLine","endEarly","itemContents","line","nextLine","blankLine","nextBulletRegex","hrRegex","fencesBeginRegex","headingBeginRegex","htmlBeginRegex","rawLine","nextLineWithoutTabs","istask","ischecked","lastItem","spacers","hasMultipleLineBreaks","tag2","headers","aligns","rows","align","cell","rtrimSlash","lastParenIndex","linkLen","links","linkString","maskedSrc","prevChar","lLength","rDelim","rLength","delimTotal","midDelimTotal","endReg","lastCharLength","text2","hasNonSpaceChars","hasSpaceCharsOnBothEnds","prevCapZero","_Lexer","__Lexer","lastParagraphClipped","extTokenizer","cutSrc","startIndex","tempSrc","tempStart","getStartIndex","errMsg","keepPrevChar","_Renderer","langString","depth","ordered","body","j","startAttr","itemBody","header","cleanHref","_TextRenderer","_Parser","__Parser","anyToken","genericToken","ret","textToken","renderer","_Hooks","markdown","Marked","callback","values","tableToken","listToken","childTokens","tokens2","extensions","pack","prevRenderer","args2","extLevel","prop","rendererProp","rendererFunc","tokenizer","tokenizerProp","tokenizerFunc","prevTokenizer","hooks","hooksProp","hooksFunc","prevHook","arg","ret2","walkTokens2","packWalktokens","blockType","origOpt","throwError","parser2","src2","silent","async","markedInstance","marked","_arrayLikeToArray","_arrayWithHoles","_iterableToArrayLimit","u","_nonIterableRest","_slicedToArray","_unsupportedIterableToArray","entries","setPrototypeOf","isFrozen","getPrototypeOf","getOwnPropertyDescriptor","freeze","seal","create","_ref","apply","construct","func","thisArg","_len","_key","Func","_len2","_key2","arrayForEach","unapply","arrayLastIndexOf","arrayPop","arrayPush","arraySplice","arrayIsArray","stringToLowerCase","stringToString","stringMatch","stringReplace","stringIndexOf","stringTrim","numberToString","booleanToString","bigintToString","symbolToString","objectHasOwnProperty","objectToString","regExpTest","typeErrorCreate","unconstruct","_len3","_key3","_len4","_key4","addToSet","array","transformCaseFunc","element","lcElement","cleanArray","clone","object","newObject","_ref2","_ref3","property","stringifyValue","valueAsRecord","valueToString","lookupGetter","stringified","desc","fallbackValue","isRegex","html$1","svg$1","svgFilters","svgDisallowed","mathMl$1","mathMlDisallowed","mathMl","xml","MUSTACHE_EXPR","ERB_EXPR","TMPLIT_EXPR","DATA_ATTR","ARIA_ATTR","IS_ALLOWED_URI","IS_SCRIPT_OR_DATA","ATTR_WHITESPACE","DOCTYPE_NAME","CUSTOM_ELEMENT","ELEMENT_MARKUP_PROBE","COMMENT_MARKUP_PROBE","FALLBACK_TAG_CLOSE","SELF_CLOSING_TAG","NODE_TYPE","getGlobal","_createTrustedTypesPolicy","trustedTypes","purifyHostElement","suffix","ATTR_NAME","policyName","scriptUrl","_createHooksMap","_resolveSetOption","cfg","createDOMPurify","DOMPurify","document","originalDocument","currentScript","HTMLTemplateElement","Node","Element","NodeFilter","_window$NamedNodeMap","DOMParser","ElementPrototype","cloneNode","remove","getNextSibling","getChildNodes","getParentNode","getShadowRoot","getAttributes","getNodeType","getNodeName","template","trustedTypesPolicy","emptyHTML","defaultTrustedTypesPolicy","defaultTrustedTypesPolicyResolved","IN_TRUSTED_TYPES_POLICY","_assertNotInTrustedTypesPolicy","_createTrustedHTML","_createTrustedScriptURL","_getDefaultTrustedTypesPolicy","_document","implementation","createNodeIterator","createDocumentFragment","getElementsByTagName","importNode","MUSTACHE_EXPR$1","ERB_EXPR$1","TMPLIT_EXPR$1","DATA_ATTR$1","ARIA_ATTR$1","IS_SCRIPT_OR_DATA$1","ATTR_WHITESPACE$1","CUSTOM_ELEMENT$1","IS_ALLOWED_URI$1","ALLOWED_TAGS","DEFAULT_ALLOWED_TAGS","ALLOWED_ATTR","DEFAULT_ALLOWED_ATTR","CUSTOM_ELEMENT_HANDLING","FORBID_TAGS","FORBID_ATTR","EXTRA_ELEMENT_HANDLING","ALLOW_ARIA_ATTR","ALLOW_DATA_ATTR","ALLOW_UNKNOWN_PROTOCOLS","ALLOW_SELF_CLOSE_IN_ATTR","SAFE_FOR_TEMPLATES","SAFE_FOR_XML","WHOLE_DOCUMENT","SET_CONFIG","SET_CONFIG_ALLOWED_TAGS","SET_CONFIG_ALLOWED_ATTR","FORCE_BODY","RETURN_DOM","RETURN_DOM_FRAGMENT","RETURN_TRUSTED_TYPE","SANITIZE_DOM","SANITIZE_NAMED_PROPS","SANITIZE_NAMED_PROPS_PREFIX","KEEP_CONTENT","IN_PLACE","USE_PROFILES","FORBID_CONTENTS","DEFAULT_FORBID_CONTENTS","DATA_URI_TAGS","DEFAULT_DATA_URI_TAGS","URI_SAFE_ATTRIBUTES","DEFAULT_URI_SAFE_ATTRIBUTES","MATHML_NAMESPACE","SVG_NAMESPACE","HTML_NAMESPACE","NAMESPACE","IS_EMPTY_INPUT","ALLOWED_NAMESPACES","DEFAULT_ALLOWED_NAMESPACES","DEFAULT_MATHML_TEXT_INTEGRATION_POINTS","MATHML_TEXT_INTEGRATION_POINTS","DEFAULT_HTML_INTEGRATION_POINTS","HTML_INTEGRATION_POINTS","COMMON_SVG_AND_HTML_ELEMENTS","PARSER_MEDIA_TYPE","SUPPORTED_PARSER_MEDIA_TYPES","DEFAULT_PARSER_MEDIA_TYPE","CONFIG","formElement","isRegexOrFunction","testValue","_parseConfig","customElementHandling","previousTrustedTypesPolicy","ALL_SVG_TAGS","ALL_MATHML_TAGS","_checkSvgNamespace","tagName","parent","parentTagName","_checkMathMlNamespace","_checkHtmlNamespace","_checkValidNamespace","_forceRemove","_neutralizeRoot","childNodes","child","attributes","attribute","_removeAttribute","_stripDisallowedAttributes","_neutralizeSubtree","stack","_initDocument","dirty","leadingWhitespace","matches","dirtyPayload","_createNodeIterator","_stripTemplateExpressions","_scrubTemplateExpressions2","_node$querySelectorAl","walker","currentNode","templates","tmpl","_isDocumentFragment","_isClobbered","realTagName","_isNode","_executeHooks","hook","_isUnsafeNode","_sanitizeDisallowedNode","_isBasicCustomElement","parentNode","childCount","hoisted","_sanitizeElements","_isValidAttribute","lcTag","lcName","nameIsPermitted","RESERVED_CUSTOM_ELEMENT_NAMES","_applyTrustedTypesToAttribute","namespaceURI","_setAttributeValue","_sanitizeAttributes","hookEvent","attr","attrValue","initValue","_sanitizeShadowDOM2","shadowNode","shadowIterator","innerSr","_sanitizeAttachedShadowRoots","isElement","rootName","sr","importedNode","returnNode","inPlace","nn","nodeIterator","entry","serializedHTML","entryPoint","hookFunction","purify","CODE_SUMMARY_MAX","escapeHtml","codeRenderer","langLabel","nonEmpty","multiline","codeHtml","summaryText","hookRegistered","ensureHook","renderMarkdown","URL_RE","linkifyText","urlText","trailing","trailMatch","markdownCache","renderAssistant","linkifyCache","renderUser","formatTokens","formatTime","timestamp","parseUserMessage","skill","fileRegex","cleanLines","attachments","cleanContent","parseArgsObject","argsStr","getSmartTitleArgs","rawArgsStr","cmd","cleanCmd","pattern","commonPath","getFullArgsFormatted","isFirstClassTool","isAssociatedWithForceCommand","shouldAutoExpand","parseToolMessage","toolOutput","firstLineBreak","headerLine","firstSpace","smartTitleArgs","fullArgs","toolDuration","filterMessages","filtered","activeStreamExists","isThinking","speechLocale","lastAssistantReply","isScrolledToBottom","contextLabel","$piState","newFolderCwd","completions","$.proxy","inputFocused","inputEl","containerEl","lastCheckedPath","newFolderModel","newFolderGitInit","userManualGitInit","createRemoteRepo","showGitInitConfirmModal","showCloneConfirmModal","checkingRemote","cloneRemoteInfo","submitCreateSession","pathStatus","appState","modelsData","$availableModels","defaultGitInit","$gitInitDefaultStore","isRemoteRepoCreation","pathCheckTimeout","triggerCheck","pathValue","fetchEmpty","autocompletePath","fetchFn","checkPath","defaultModel","handleFormCreateSession","probe","checkRemoteRepo","messageList","sessionInfo","$activeSessionInfo","loadingSession","$isLoadingSession","resyncing","$isResyncing","$isReadOnly","handleFork","beepOverride","$beepSessionOverride","beepOn","$beepEnabled","conversationOn","$conversationMode","conversationFollowsDefault","$conversationModeSessionOverride","toggleConversationMode","collapseActive","$collapseLongReplies","spokenSayIds","spokeThisTurn","$messages","$speakReplies","prevStreamingForSpeech","fallbackSpokenIds","streamingNow","$isStreaming","cycleBeep","hasCachedSession","loadFailed","$sessionError","shouldAutoScroll","forceScroll","expandedMessages","toggleMessage","currentVal","toggleRaw","copiedMessageId","copiedTimeout","copyMessage","ta","handleScroll","scrollToBottom","scrollToBottomIfShould","lastSessionFile","wasLoadingSession","scrollToBottomSettled","sFile","isLoading","msgList","anyToolRunning","$.user_pre_effect","forceScrollToBottom","moreHistory","$hasMoreHistory","loadingMore","$isLoadingMoreHistory","REVEAL_GAP_PX","pendingAnchorId","pendingAnchorFromBottom","handleLoadMore","anchorId","anchorFromBottom","anchorEl","delta","node_1","wherever","img_1","form","completion","span_1","consequent_5","span_2","root_10","root_11","$.each","$.index","root_12","root_13","alternate_1","root_14","div_15","root_15","label_1","label_2","consequent_9","div_16","root_16","consequent_10","node_8","text_4","$.event","div_17","root_17","div_18","root_18","div_19","root_19","node_9","div_20","root_20","node_10","consequent_14","alternate_2","consequent_15","node_11","div_21","root_23","div_22","node_12","div_23","root_25","div_24","root_26","div_25","root_27","div_26","root_28","div_27","root_29","consequent_19","div_28","node_14","text_7","consequent_16","consequent_17","consequent_18","alternate_3","div_29","root_31","span_3","span_4","text_8","node_16","span_5","root_32","text_9","isExpanded","dlPath","dlUrl","dlKind","isAttachTool","isSayTool","fileName","div_30","root_34","div_31","root_35","div_32","root_36","span_6","span_7","root_37","text_10","consequent_24","root_38","span_8","span_9","span_10","text_12","div_33","root_39","span_11","span_12","consequent_23","consequent_26","alternate_4","a_1","root_40","img_2","consequent_27","audio","root_41","consequent_28","video","root_42","consequent_29","div_34","root_43","div_35","root_44","span_13","span_14","root_45","text_14","consequent_31","div_36","root_46","span_15","span_16","text_15","consequent_32","consequent_33","div_37","root_47","div_38","button_4","div_39","node_25","span_17","root_48","span_18","root_49","span_19","root_50","span_20","root_51","consequent_35","consequent_36","consequent_37","alternate_5","span_21","text_16","node_26","span_22","root_52","text_17","consequent_38","span_23","root_53","text_18","$.set_class","div_40","node_28","consequent_40","alternate_6","node_29","a_2","root_57","span_24","root_58","consequent_41","alternate_7","consequent_42","a_3","root_59","img_3","consequent_43","audio_1","root_60","consequent_44","video_1","root_61","consequent_45","div_41","root_62","div_42","imgSrc","a_4","root_64","img_4","consequent_46","consequent_47","div_43","root_65","node_37","div_44","root_66","pre","text_19","consequent_48","div_45","pre_1","root_67","text_20","div_46","root_68","div_47","root_69","div_48","root_70","consequent_49","consequent_50","consequent_51","alternate_8","consequent_52","consequent_34","alternate_9","pre_2","root_72","text_21","replyExpanded","replyCollapsed","showRaw","div_49","root_73","pre_3","root_74","text_22","div_50","root_75","consequent_55","alternate_11","div_51","node_40","button_5","node_41","consequent_56","alternate_12","button_6","node_42","consequent_57","alternate_13","node_43","button_7","root_80","button_8","root_81","d_3","consequent_58","consequent_59","consequent_54","alternate_14","parsedUserMsg","div_52","root_83","span_25","span_26","node_45","div_53","root_84","text_24","consequent_61","div_54","root_85","node_46","userHtml","span_27","root_87","$.html","text_25","consequent_63","alternate_15","span_28","root_89","consequent_64","consequent_65","alternate_16","span_29","root_91","consequent_66","consequent_62","alternate_17","div_55","root_92","filePath","div_56","root_93","span_30","consequent_67","consequent_60","alternate_18","div_57","fragment_16","node_51","consequent_68","node_52","div_58","root_96","button_9","$pendingSteering","div_59","root_97","div_60","root_98","button_10","button_11","consequent_71","consequent_72","consequent_13","alternate_19","consequent_11","div_61","div_62","label_3","node_55","button_12","root_99","span_31","span_32","text_31","consequent_73","button_13","span_33","span_34","node_56","div_63","root_100","span_35","consequent_74","div_64","button_14","root_101","text_35","$$args","consequent_75","button_15","node_57","node_58","div_65","root_102","div_66","span_36","div_67","div_68","label_4","node_59","span_37","root_103","span_38","root_104","consequent_76","alternate_20","div_69","root_105","div_70","label_5","text_37","div_71","root_106","label_6","label_7","input_10","consequent_77","consequent_78","div_72","button_16","button_17","consequent_79","div_73","root_107","div_74","span_39","text_38","root_108","text_40","consequent_80","div_75","node_63","button_18","button_19","consequent_81","decideComposeSend","PRE_START","GENERIC_FAILURE","preStartUpload","uploadPercent","pct","canRetryUpload","chipView","retry","isUploadInFlight","attachmentBlocksSend","attachment","uploadErrorFrom","decideMicReopen","AUTO_STOP_DEFAULTS","createAutoStopDetector","speechLevel","silenceMs","leadingSilenceMs","maxMs","elapsedMs","silentMs","heardSpeech","stopped","frameMs","frameLevel","samples","sum","activeEngine","SpeechRecognition","isBrowserSupported","isRecording","isProcessing","isHolding","showSettings","directSend","locale","engine","speechError","pressTimer","recognitionInstance","audioContext","micSource","scriptProcessor","audioStream","pcmChunks","autoStopDetector","baseText","textModified","locales","unsubscribeDirectSend","storedLocale","storedEngine","track","savePreferences","playBeep","AudioContextClass","downsampleBuffer","buffer","inputSampleRate","outputSampleRate","sampleRateRatio","newLength","offsetResult","offsetBuffer","nextOffsetBuffer","accum","startBrowserRecording","finalSessionText","interimSessionText","sessionText","stopBrowserRecording","startCloudRecording","stream","inputBuffer","sampleRate","stopRecording","stopCloudRecording","processCloudTranscription","totalLength","flatBuffer","originalSampleRate","targetSampleRate","downsampledBuffer","wavBuffer","createWav","wavBlob","startRecording","autoStop","startRecordingProgrammatically","handlePointerDown","handlePointerUp","handlePointerCancel","numOfChan","format","bitDepth","writeString","floatTo16BitPCM","output","string","sendDisabled","showAttach","searchMode","searchConfigured","searchModels","searchModel","enterToSend","isCollapsed","speechEngine","speechButton","skillMenuOpen","skillMenuIndex","fileInput","nextAttachmentId","uploadControllers","slashPrefix","skillMatches","ap","bp","applySkill","textarea","effectivelyDisabled","sendBlocked","isAnyUploading","canSend","DRAFT_PREFIX","draftKey","hydratedKey","readCachedDrafts","draftsOpen","pendingDraft","draftSource","draftSavedFlash","draftError","draftsLoading","draftsRequestSeq","draftsAdoptedSeq","draftFlashTimer","adoptDrafts","migrateLegacyDrafts","legacy","refreshDrafts","draftsFetchedWhileConnected","saveCurrentAsDraft","keyAtRequest","requestLoadDraft","loadDraft","consumeDraftOnSend","deleteDraft","toggleDrafts","closeDrafts","saved","appliedPrefillBump","prefillText","bump","$composerPrefill","focusInput","prevStreamingForReopen","nowStreaming","toggleEnterToSend","handleFileChange","runUpload","updateAttachment","dropAttachment","diagnosticsUrl","controller","isCurrent","cancelUpload","retryUpload","removeAttachment","handleSend","uploadedPaths","messageToSend","lower","decision","handleKeydown","chosen","ul","li","node_6","text_5","consequent_12","root_21","root_22","fragment_6","text_13","fragment_7","consequent_20","consequent_21","node_13","root_30","consequent_22","consequent_25","root_33","$.bind_select_value","node_15","ul_1","li_1","textarea_1","$.remove_textarea_child","fragment_8","node_18","SpeechButton","node_19","node_20","node_21","buildForkTree","sessions","byPath","childrenOf","roots","recencyCache","inProgress","groupRecency","best","childBest","byRecency","visited","walk","folders","$readOnlySessionFolders","$sessionFolders","loading","refresh","fetchReadOnlySessions","models","expanded","searchExpanded","confirmingDelete","confirmingDeleteFolder","searchQuery","filteredFolders","fetchModels","matchesFilter","session","folderName","foldersArr","toggleStar","sessionPath","starred","setSessionStarred","isFolderExpanded","folderPath","toggleFolder","handleDeleteSession","handleDeleteAllFolderSessions","sessionPaths","handleSessionClick","createFormOpen","sidebarCwd","sidebarCompletions","sidebarInputFocused","sidebarInputEl","sidebarContainerEl","lastCheckedSidebarPath","sidebarModel","sidebarGitInit","userManualSidebarGitInit","sidebarCreateRemote","sidebarRepoVisibility","showSidebarGitConfirmModal","sidebarPathStatus","isSidebarRemoteRepoCreation","sidebarPathCheckTimeout","triggerSidebarCheck","handleSidebarCreateSession","handleSidebarConfirmModalSubmit","newSessionPicker","openNewSessionPicker","closeNewSessionPicker","handleCreateSession","formatRelative","timeStr","diff","mins","hours","truncate","node_5","$$item","node_17","root_24","text_11","select_1","option_1","option_1_value","$.bind_value","input_11","$.set_value","$.clsx","MATCH_START","MATCH_END","snippetSegments","snippet","segments","push","snippetPlainText","hitKindLabel","kind","tool","relativeTime","iso","seconds","minutes","days","months","threadRow","thread","$.noop","extraClass","threadLabel","initialQuery","expandedThreads","MIN_QUERY","DEBOUNCE_MS","debounceTimer","started","scheduleSearch","response","searchConversations","submit","hitKey","hit","text_6","segment","mark","fragment_5","$sudoPrompt","lastPromptId","onKeydown","creating","PHASE_LABELS","phaseLabel","phase","scopeLabel","scope","$.set_style","missing","$folderMissing","restore","$restoreState","job","running","ready","failure","rejection","createRequested","awaitingAnswer","joinedOtherUrl","urlTouched","loadingCandidates","showRawOutput","showCreate","gitInitChoice","prefilledFor","fetchRemoteCandidates","configured","submitClone","submitCreate","RestoreProgress","node_4","fragment_4","candidate","sidebarOpen","sessionView","searchReadOnly","searchInitialQuery","openSearch","fromReadOnly","initial","chatList","booting","readHashId","handleHashChange","hashJoinAttempt","hiddenTimer","HIDE_DISCONNECT_DELAY","handleVisibility","handlePageShow","handlePageHide","handleConnected","handleReconnect","handleRefresh","handleShowMainScreen","agentPending","$isAgentPending","$isInterrupted","sError","notice","$sessionNotice","fConflict","$folderConflict","fMissing","wasSessionActive","currentStarred","hashJoinTimer","$isCreatingSession","isCreating","createRestore","searchFolder","$searchFolderStore","assistantActive","$assistantStatusStore","viewingAssistant","isAssistantSession","chatInput","searchActive","searchDefaultModel","$searchDefaultModelStore","appearanceLabel","$appearanceStore","folderDefault","listDefault","hasFocusedSearch","startSearch","Head","ConnectionSettings","node_7","AssistantPushSettings","AssistantTelegramSettings","ConversationSearch","SessionBrowser","$.init_select","select_value","consequent_30","button_20","button_21","$.bind_this","ChatMessageList","RestorePanel","consequent_39","ChatInput","node_39","SudoPasswordDialog","button_22"],"ignoreList":[0,1,2,3,4,5,6,7,13,36,37],"sources":["../../../../../../../node_modules/.pnpm/svelte@5.55.9/node_modules/svelte/src/internal/client/dom/blocks/html.js","../../../../../../../node_modules/.pnpm/svelte@5.55.9/node_modules/svelte/src/internal/client/dom/blocks/svelte-head.js","../../../../../../../node_modules/.pnpm/clsx@2.1.1/node_modules/clsx/dist/clsx.mjs","../../../../../../../node_modules/.pnpm/svelte@5.55.9/node_modules/svelte/src/internal/shared/attributes.js","../../../../../../../node_modules/.pnpm/svelte@5.55.9/node_modules/svelte/src/internal/client/dom/elements/class.js","../../../../../../../node_modules/.pnpm/svelte@5.55.9/node_modules/svelte/src/internal/client/dom/elements/style.js","../../../../../../../node_modules/.pnpm/svelte@5.55.9/node_modules/svelte/src/internal/client/dom/elements/bindings/select.js","../../../../../../../node_modules/.pnpm/svelte@5.55.9/node_modules/svelte/src/internal/client/dom/elements/bindings/input.js","../../../../../../src/routes/+page.ts","../../../../../../src/lib/core/utils/web/path.ts","../../../../../../src/lib/Head.svelte","../../../../../../src/lib/core/beep.ts","../../../../../../../client/dist/types.js","../../../../../../../node_modules/.pnpm/sveltore@0.0.2/node_modules/sveltore/dist/index.js","../../../../../../../client/dist/frame-chunks.js","../../../../../../../client/dist/client.js","../../../../../../src/lib/core/conversation-mode.ts","../../../../../../src/lib/core/attachments.ts","../../../../../../src/lib/core/view-mode.ts","../../../../../../src/lib/core/post-upload.ts","../../../../../../src/lib/core/timezone-report.ts","../../../../../../src/lib/core/drafts.ts","../../../../../../src/lib/core/conversation-cache.ts","../../../../../../src/lib/core/instant-resume.ts","../../../../../../src/lib/wherever.ts","../../../../../../src/lib/core/speak.ts","../../../../../../src/lib/components/ConnectionSettings.svelte","../../../../../../src/lib/core/push-subscription.ts","../../../../../../src/lib/components/AssistantPushSettings.svelte","../../../../../../src/lib/core/telegram-settings.ts","../../../../../../src/lib/core/clipboard.ts","../../../../../../src/lib/components/CopyButton.svelte","../../../../../../src/lib/components/AssistantTelegramSettings.svelte","../../../../../../src/lib/core/media-kind.ts","../../../../../../src/lib/core/speak-fallback.ts","../../../../../../src/lib/core/collapse-reply.ts","../../../../../../../node_modules/.pnpm/marked@15.0.12/node_modules/marked/lib/marked.esm.js","../../../../../../../node_modules/.pnpm/dompurify@3.4.11/node_modules/dompurify/dist/purify.es.mjs","../../../../../../src/lib/core/utils/markdown.ts","../../../../../../src/lib/components/chat-message-helpers.ts","../../../../../../src/lib/components/ChatMessageList.svelte","../../../../../../src/lib/core/compose-send.ts","../../../../../../src/lib/core/upload-chip.ts","../../../../../../src/lib/core/hands-free.ts","../../../../../../src/lib/components/speech/SpeechButton.svelte","../../../../../../src/lib/components/ChatInput.svelte","../../../../../../src/lib/core/fork-tree.ts","../../../../../../src/lib/components/SessionBrowser.svelte","../../../../../../src/lib/core/search-snippet.ts","../../../../../../src/lib/components/ConversationSearch.svelte","../../../../../../src/lib/components/SudoPasswordDialog.svelte","../../../../../../src/lib/components/RestoreProgress.svelte","../../../../../../src/lib/components/RestorePanel.svelte","../../../../../../src/routes/+page.svelte"],"sourcesContent":["/** @import { Effect, TemplateNode } from '#client' */\n/** @import {} from 'trusted-types' */\nimport {\n\tFILENAME,\n\tHYDRATION_ERROR,\n\tNAMESPACE_SVG,\n\tNAMESPACE_MATHML\n} from '../../../../constants.js';\nimport { remove_effect_dom, template_effect } from '../../reactivity/effects.js';\nimport { hydrate_next, hydrate_node, hydrating, set_hydrate_node } from '../hydration.js';\n\nimport { assign_nodes } from '../template.js';\nimport * as w from '../../warnings.js';\nimport { hash, sanitize_location } from '../../../../utils.js';\nimport { DEV } from 'esm-env';\nimport { dev_current_component_function } from '../../context.js';\nimport { create_element, get_first_child, get_next_sibling } from '../operations.js';\nimport { active_effect } from '../../runtime.js';\nimport { COMMENT_NODE } from '#client/constants';\n\n/**\n * @param {Element} element\n * @param {string | null} server_hash\n * @param {string | TrustedHTML} value\n */\nfunction check_hash(element, server_hash, value) {\n\tif (!server_hash || server_hash === hash(String(value ?? ''))) return;\n\n\tlet location;\n\n\t// @ts-expect-error\n\tconst loc = element.__svelte_meta?.loc;\n\tif (loc) {\n\t\tlocation = `near ${loc.file}:${loc.line}:${loc.column}`;\n\t} else if (dev_current_component_function?.[FILENAME]) {\n\t\tlocation = `in ${dev_current_component_function[FILENAME]}`;\n\t}\n\n\tw.hydration_html_changed(sanitize_location(location));\n}\n\n/**\n * @param {Element | Text | Comment} node\n * @param {() => string | TrustedHTML} get_value\n * @param {boolean} [is_controlled]\n * @param {boolean} [svg]\n * @param {boolean} [mathml]\n * @param {boolean} [skip_warning]\n * @returns {void}\n */\nexport function html(\n\tnode,\n\tget_value,\n\tis_controlled = false,\n\tsvg = false,\n\tmathml = false,\n\tskip_warning = false\n) {\n\tvar anchor = node;\n\n\t/** @type {string | TrustedHTML} */\n\tvar value = '';\n\n\tif (is_controlled) {\n\t\tvar parent_node = /** @type {Element} */ (node);\n\n\t\tif (hydrating) {\n\t\t\tanchor = set_hydrate_node(get_first_child(parent_node));\n\t\t}\n\t}\n\n\ttemplate_effect(() => {\n\t\tvar effect = /** @type {Effect} */ (active_effect);\n\n\t\tif (value === (value = get_value() ?? '')) {\n\t\t\tif (hydrating) hydrate_next();\n\t\t\treturn;\n\t\t}\n\n\t\tif (is_controlled && !hydrating) {\n\t\t\t// When @html is the only child, use innerHTML directly.\n\t\t\t// This also handles contenteditable, where the user may delete the anchor comment.\n\t\t\teffect.nodes = null;\n\t\t\tparent_node.innerHTML = /** @type {string} */ (value);\n\n\t\t\tif (value !== '') {\n\t\t\t\tassign_nodes(\n\t\t\t\t\t/** @type {TemplateNode} */ (get_first_child(parent_node)),\n\t\t\t\t\t/** @type {TemplateNode} */ (parent_node.lastChild)\n\t\t\t\t);\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\n\t\tif (effect.nodes !== null) {\n\t\t\tremove_effect_dom(effect.nodes.start, /** @type {TemplateNode} */ (effect.nodes.end));\n\t\t\teffect.nodes = null;\n\t\t}\n\n\t\tif (value === '') return;\n\n\t\tif (hydrating) {\n\t\t\t// We're deliberately not trying to repair mismatches between server and client,\n\t\t\t// as it's costly and error-prone (and it's an edge case to have a mismatch anyway)\n\t\t\tvar hash = /** @type {Comment} */ (hydrate_node).data;\n\n\t\t\t/** @type {TemplateNode | null} */\n\t\t\tvar next = hydrate_next();\n\t\t\tvar last = next;\n\n\t\t\twhile (\n\t\t\t\tnext !== null &&\n\t\t\t\t(next.nodeType !== COMMENT_NODE || /** @type {Comment} */ (next).data !== '')\n\t\t\t) {\n\t\t\t\tlast = next;\n\t\t\t\tnext = get_next_sibling(next);\n\t\t\t}\n\n\t\t\tif (next === null) {\n\t\t\t\tw.hydration_mismatch();\n\t\t\t\tthrow HYDRATION_ERROR;\n\t\t\t}\n\n\t\t\tif (DEV && !skip_warning) {\n\t\t\t\tcheck_hash(/** @type {Element} */ (next.parentNode), hash, value);\n\t\t\t}\n\n\t\t\tassign_nodes(hydrate_node, last);\n\t\t\tanchor = set_hydrate_node(next);\n\t\t\treturn;\n\t\t}\n\n\t\t// Don't use create_fragment_with_script_from_html here because that would mean script tags are executed.\n\t\t// @html is basically `.innerHTML = ...` and that doesn't execute scripts either due to security reasons.\n\t\t// Use a <template>, <svg>, or <math> wrapper depending on context. If value is a TrustedHTML object,\n\t\t// it will be assigned directly to innerHTML without coercion — this allows {@html policy.createHTML(...)} to work.\n\t\tvar ns = svg ? NAMESPACE_SVG : mathml ? NAMESPACE_MATHML : undefined;\n\t\tvar wrapper = /** @type {HTMLTemplateElement | SVGElement | MathMLElement} */ (\n\t\t\tcreate_element(svg ? 'svg' : mathml ? 'math' : 'template', ns)\n\t\t);\n\t\twrapper.innerHTML = /** @type {any} */ (value);\n\n\t\t/** @type {DocumentFragment | Element} */\n\t\tvar node = svg || mathml ? wrapper : /** @type {HTMLTemplateElement} */ (wrapper).content;\n\n\t\tassign_nodes(\n\t\t\t/** @type {TemplateNode} */ (get_first_child(node)),\n\t\t\t/** @type {TemplateNode} */ (node.lastChild)\n\t\t);\n\n\t\tif (svg || mathml) {\n\t\t\twhile (get_first_child(node)) {\n\t\t\t\tanchor.before(/** @type {TemplateNode} */ (get_first_child(node)));\n\t\t\t}\n\t\t} else {\n\t\t\tanchor.before(node);\n\t\t}\n\t});\n}\n","/** @import { TemplateNode } from '#client' */\nimport { hydrate_node, hydrating, set_hydrate_node, set_hydrating } from '../hydration.js';\nimport { create_text, get_first_child, get_next_sibling } from '../operations.js';\nimport { block, branch } from '../../reactivity/effects.js';\nimport { COMMENT_NODE, HEAD_EFFECT } from '#client/constants';\n\n/**\n * @param {string} hash\n * @param {(anchor: Node) => void} render_fn\n * @returns {void}\n */\nexport function head(hash, render_fn) {\n\t// The head function may be called after the first hydration pass and ssr comment nodes may still be present,\n\t// therefore we need to skip that when we detect that we're not in hydration mode.\n\tlet previous_hydrate_node = null;\n\tlet was_hydrating = hydrating;\n\n\t/** @type {Comment | Text} */\n\tvar anchor;\n\n\tif (hydrating) {\n\t\tprevious_hydrate_node = hydrate_node;\n\n\t\tvar head_anchor = get_first_child(document.head);\n\n\t\t// There might be multiple head blocks in our app, and they could have been\n\t\t// rendered in an arbitrary order — find one corresponding to this component\n\t\twhile (\n\t\t\thead_anchor !== null &&\n\t\t\t(head_anchor.nodeType !== COMMENT_NODE || /** @type {Comment} */ (head_anchor).data !== hash)\n\t\t) {\n\t\t\thead_anchor = get_next_sibling(head_anchor);\n\t\t}\n\n\t\t// If we can't find an opening hydration marker, skip hydration (this can happen\n\t\t// if a framework rendered body but not head content)\n\t\tif (head_anchor === null) {\n\t\t\tset_hydrating(false);\n\t\t} else {\n\t\t\tvar start = /** @type {TemplateNode} */ (get_next_sibling(head_anchor));\n\t\t\thead_anchor.remove(); // in case this component is repeated\n\n\t\t\tset_hydrate_node(start);\n\t\t}\n\t}\n\n\tif (!hydrating) {\n\t\tanchor = document.head.appendChild(create_text());\n\t}\n\n\ttry {\n\t\tblock(() => {\n\t\t\tvar e = branch(() => render_fn(anchor));\n\t\t\te.f |= HEAD_EFFECT;\n\t\t});\n\t} finally {\n\t\tif (was_hydrating) {\n\t\t\tset_hydrating(true);\n\t\t\tset_hydrate_node(/** @type {TemplateNode} */ (previous_hydrate_node));\n\t\t}\n\t}\n}\n","function r(e){var t,f,n=\"\";if(\"string\"==typeof e||\"number\"==typeof e)n+=e;else if(\"object\"==typeof e)if(Array.isArray(e)){var o=e.length;for(t=0;t<o;t++)e[t]&&(f=r(e[t]))&&(n&&(n+=\" \"),n+=f)}else for(f in e)e[f]&&(n&&(n+=\" \"),n+=f);return n}export function clsx(){for(var e,t,f=0,n=\"\",o=arguments.length;f<o;f++)(e=arguments[f])&&(t=r(e))&&(n&&(n+=\" \"),n+=t);return n}export default clsx;","import { escape_html } from '../../escaping.js';\nimport { clsx as _clsx } from 'clsx';\nimport { has_own_property } from './utils.js';\n\n/**\n * `<div translate={false}>` should be rendered as `<div translate=\"no\">` and _not_\n * `<div translate=\"false\">`, which is equivalent to `<div translate=\"yes\">`. There\n * may be other odd cases that need to be added to this list in future\n * @type {Record<string, Map<any, string>>}\n */\nconst replacements = {\n\ttranslate: new Map([\n\t\t[true, 'yes'],\n\t\t[false, 'no']\n\t])\n};\n\n/**\n * @template V\n * @param {string} name\n * @param {V} value\n * @param {boolean} [is_boolean]\n * @returns {string}\n */\nexport function attr(name, value, is_boolean = false) {\n\t// attribute hidden for values other than \"until-found\" behaves like a boolean attribute\n\tif (name === 'hidden' && value !== 'until-found') {\n\t\tis_boolean = true;\n\t}\n\tif (value == null || (!value && is_boolean)) return '';\n\tconst normalized =\n\t\t(has_own_property.call(replacements, name) && replacements[name].get(value)) || value;\n\tconst assignment = is_boolean ? `=\"\"` : `=\"${escape_html(normalized, true)}\"`;\n\treturn ` ${name}${assignment}`;\n}\n\n/**\n * Small wrapper around clsx to preserve Svelte's (weird) handling of falsy values.\n * TODO Svelte 6 revisit this, and likely turn all falsy values into the empty string (what clsx also does)\n * @param {any} value\n */\nexport function clsx(value) {\n\tif (typeof value === 'object') {\n\t\treturn _clsx(value);\n\t} else {\n\t\treturn value ?? '';\n\t}\n}\n\nconst whitespace = [...' \\t\\n\\r\\f\\u00a0\\u000b\\ufeff'];\n\n/**\n * @param {any} value\n * @param {string | null} [hash]\n * @param {Record<string, boolean>} [directives]\n * @returns {string | null}\n */\nexport function to_class(value, hash, directives) {\n\tvar classname = value == null ? '' : '' + value;\n\n\tif (hash) {\n\t\tclassname = classname ? classname + ' ' + hash : hash;\n\t}\n\n\tif (directives) {\n\t\tfor (var key of Object.keys(directives)) {\n\t\t\tif (directives[key]) {\n\t\t\t\tclassname = classname ? classname + ' ' + key : key;\n\t\t\t} else if (classname.length) {\n\t\t\t\tvar len = key.length;\n\t\t\t\tvar a = 0;\n\n\t\t\t\twhile ((a = classname.indexOf(key, a)) >= 0) {\n\t\t\t\t\tvar b = a + len;\n\n\t\t\t\t\tif (\n\t\t\t\t\t\t(a === 0 || whitespace.includes(classname[a - 1])) &&\n\t\t\t\t\t\t(b === classname.length || whitespace.includes(classname[b]))\n\t\t\t\t\t) {\n\t\t\t\t\t\tclassname = (a === 0 ? '' : classname.substring(0, a)) + classname.substring(b + 1);\n\t\t\t\t\t} else {\n\t\t\t\t\t\ta = b;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn classname === '' ? null : classname;\n}\n\n/**\n *\n * @param {Record<string,any>} styles\n * @param {boolean} important\n */\nfunction append_styles(styles, important = false) {\n\tvar separator = important ? ' !important;' : ';';\n\tvar css = '';\n\n\tfor (var key of Object.keys(styles)) {\n\t\tvar value = styles[key];\n\t\tif (value != null && value !== '') {\n\t\t\tcss += ' ' + key + ': ' + value + separator;\n\t\t}\n\t}\n\n\treturn css;\n}\n\n/**\n * @param {string} name\n * @returns {string}\n */\nfunction to_css_name(name) {\n\tif (name[0] !== '-' || name[1] !== '-') {\n\t\treturn name.toLowerCase();\n\t}\n\treturn name;\n}\n\n/**\n * @param {any} value\n * @param {Record<string, any> | [Record<string, any>, Record<string, any>]} [styles]\n * @returns {string | null}\n */\nexport function to_style(value, styles) {\n\tif (styles) {\n\t\tvar new_style = '';\n\n\t\t/** @type {Record<string,any> | undefined} */\n\t\tvar normal_styles;\n\n\t\t/** @type {Record<string,any> | undefined} */\n\t\tvar important_styles;\n\n\t\tif (Array.isArray(styles)) {\n\t\t\tnormal_styles = styles[0];\n\t\t\timportant_styles = styles[1];\n\t\t} else {\n\t\t\tnormal_styles = styles;\n\t\t}\n\n\t\tif (value) {\n\t\t\tvalue = String(value)\n\t\t\t\t.replaceAll(/\\s*\\/\\*.*?\\*\\/\\s*/g, '')\n\t\t\t\t.trim();\n\n\t\t\t/** @type {boolean | '\"' | \"'\"} */\n\t\t\tvar in_str = false;\n\t\t\tvar in_apo = 0;\n\t\t\tvar in_comment = false;\n\n\t\t\tvar reserved_names = [];\n\n\t\t\tif (normal_styles) {\n\t\t\t\treserved_names.push(...Object.keys(normal_styles).map(to_css_name));\n\t\t\t}\n\t\t\tif (important_styles) {\n\t\t\t\treserved_names.push(...Object.keys(important_styles).map(to_css_name));\n\t\t\t}\n\n\t\t\tvar start_index = 0;\n\t\t\tvar name_index = -1;\n\n\t\t\tconst len = value.length;\n\t\t\tfor (var i = 0; i < len; i++) {\n\t\t\t\tvar c = value[i];\n\n\t\t\t\tif (in_comment) {\n\t\t\t\t\tif (c === '/' && value[i - 1] === '*') {\n\t\t\t\t\t\tin_comment = false;\n\t\t\t\t\t}\n\t\t\t\t} else if (in_str) {\n\t\t\t\t\tif (in_str === c) {\n\t\t\t\t\t\tin_str = false;\n\t\t\t\t\t}\n\t\t\t\t} else if (c === '/' && value[i + 1] === '*') {\n\t\t\t\t\tin_comment = true;\n\t\t\t\t} else if (c === '\"' || c === \"'\") {\n\t\t\t\t\tin_str = c;\n\t\t\t\t} else if (c === '(') {\n\t\t\t\t\tin_apo++;\n\t\t\t\t} else if (c === ')') {\n\t\t\t\t\tin_apo--;\n\t\t\t\t}\n\n\t\t\t\tif (!in_comment && in_str === false && in_apo === 0) {\n\t\t\t\t\tif (c === ':' && name_index === -1) {\n\t\t\t\t\t\tname_index = i;\n\t\t\t\t\t} else if (c === ';' || i === len - 1) {\n\t\t\t\t\t\tif (name_index !== -1) {\n\t\t\t\t\t\t\tvar name = to_css_name(value.substring(start_index, name_index).trim());\n\n\t\t\t\t\t\t\tif (!reserved_names.includes(name)) {\n\t\t\t\t\t\t\t\tif (c !== ';') {\n\t\t\t\t\t\t\t\t\ti++;\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tvar property = value.substring(start_index, i).trim();\n\t\t\t\t\t\t\t\tnew_style += ' ' + property + ';';\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tstart_index = i + 1;\n\t\t\t\t\t\tname_index = -1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (normal_styles) {\n\t\t\tnew_style += append_styles(normal_styles);\n\t\t}\n\n\t\tif (important_styles) {\n\t\t\tnew_style += append_styles(important_styles, true);\n\t\t}\n\n\t\tnew_style = new_style.trim();\n\t\treturn new_style === '' ? null : new_style;\n\t}\n\n\treturn value == null ? null : String(value);\n}\n","import { to_class } from '../../../shared/attributes.js';\nimport { CLASS_CACHE } from '../../constants.js';\nimport { hydrating } from '../hydration.js';\n\n/**\n * @param {Element} dom\n * @param {boolean | number} is_html\n * @param {string | null} value\n * @param {string} [hash]\n * @param {Record<string, any>} [prev_classes]\n * @param {Record<string, any>} [next_classes]\n * @returns {Record<string, boolean> | undefined}\n */\nexport function set_class(dom, is_html, value, hash, prev_classes, next_classes) {\n\tvar prev = /** @type {any} */ (dom)[CLASS_CACHE];\n\n\tif (\n\t\thydrating ||\n\t\tprev !== value ||\n\t\tprev === undefined // for edge case of `class={undefined}`\n\t) {\n\t\tvar next_class_name = to_class(value, hash, next_classes);\n\n\t\tif (!hydrating || next_class_name !== dom.getAttribute('class')) {\n\t\t\t// Removing the attribute when the value is only an empty string causes\n\t\t\t// performance issues vs simply making the className an empty string. So\n\t\t\t// we should only remove the class if the value is nullish\n\t\t\t// and there no hash/directives :\n\t\t\tif (next_class_name == null) {\n\t\t\t\tdom.removeAttribute('class');\n\t\t\t} else if (is_html) {\n\t\t\t\tdom.className = next_class_name;\n\t\t\t} else {\n\t\t\t\tdom.setAttribute('class', next_class_name);\n\t\t\t}\n\t\t}\n\n\t\t/** @type {any} */ (dom)[CLASS_CACHE] = value;\n\t} else if (next_classes && prev_classes !== next_classes) {\n\t\tfor (var key in next_classes) {\n\t\t\tvar is_present = !!next_classes[key];\n\n\t\t\tif (prev_classes == null || is_present !== !!prev_classes[key]) {\n\t\t\t\tdom.classList.toggle(key, is_present);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn next_classes;\n}\n","import { to_style } from '../../../shared/attributes.js';\nimport { STYLE_CACHE } from '../../constants.js';\nimport { hydrating } from '../hydration.js';\n\n/**\n * @param {Element & ElementCSSInlineStyle} dom\n * @param {Record<string, any>} prev\n * @param {Record<string, any>} next\n * @param {string} [priority]\n */\nfunction update_styles(dom, prev = {}, next, priority) {\n\tfor (var key in next) {\n\t\tvar value = next[key];\n\n\t\tif (prev[key] !== value) {\n\t\t\tif (next[key] == null) {\n\t\t\t\tdom.style.removeProperty(key);\n\t\t\t} else {\n\t\t\t\tdom.style.setProperty(key, value, priority);\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * @param {Element & ElementCSSInlineStyle} dom\n * @param {string | null} value\n * @param {Record<string, any> | [Record<string, any>, Record<string, any>]} [prev_styles]\n * @param {Record<string, any> | [Record<string, any>, Record<string, any>]} [next_styles]\n */\nexport function set_style(dom, value, prev_styles, next_styles) {\n\tvar prev = /** @type {any} */ (dom)[STYLE_CACHE];\n\n\tif (hydrating || prev !== value) {\n\t\tvar next_style_attr = to_style(value, next_styles);\n\n\t\tif (!hydrating || next_style_attr !== dom.getAttribute('style')) {\n\t\t\tif (next_style_attr == null) {\n\t\t\t\tdom.removeAttribute('style');\n\t\t\t} else {\n\t\t\t\tdom.style.cssText = next_style_attr;\n\t\t\t}\n\t\t}\n\n\t\t/** @type {any} */ (dom)[STYLE_CACHE] = value;\n\t} else if (next_styles) {\n\t\tif (Array.isArray(next_styles)) {\n\t\t\tupdate_styles(dom, prev_styles?.[0], next_styles[0]);\n\t\t\tupdate_styles(dom, prev_styles?.[1], next_styles[1], 'important');\n\t\t} else {\n\t\t\tupdate_styles(dom, prev_styles, next_styles);\n\t\t}\n\t}\n\n\treturn next_styles;\n}\n","import { effect, teardown } from '../../../reactivity/effects.js';\nimport { listen_to_event_and_reset_event } from './shared.js';\nimport { is } from '../../../proxy.js';\nimport { is_array } from '../../../../shared/utils.js';\nimport * as w from '../../../warnings.js';\nimport { Batch, current_batch, previous_batch } from '../../../reactivity/batch.js';\nimport { async_mode_flag } from '../../../../flags/index.js';\n\n/**\n * Selects the correct option(s) (depending on whether this is a multiple select)\n * @template V\n * @param {HTMLSelectElement} select\n * @param {V} value\n * @param {boolean} mounting\n */\nexport function select_option(select, value, mounting = false) {\n\tif (select.multiple) {\n\t\t// If value is null or undefined, keep the selection as is\n\t\tif (value == undefined) {\n\t\t\treturn;\n\t\t}\n\n\t\t// If not an array, warn and keep the selection as is\n\t\tif (!is_array(value)) {\n\t\t\treturn w.select_multiple_invalid_value();\n\t\t}\n\n\t\t// Otherwise, update the selection\n\t\tfor (var option of select.options) {\n\t\t\toption.selected = value.includes(get_option_value(option));\n\t\t}\n\n\t\treturn;\n\t}\n\n\tfor (option of select.options) {\n\t\tvar option_value = get_option_value(option);\n\t\tif (is(option_value, value)) {\n\t\t\toption.selected = true;\n\t\t\treturn;\n\t\t}\n\t}\n\n\tif (!mounting || value !== undefined) {\n\t\tselect.selectedIndex = -1; // no option should be selected\n\t}\n}\n\n/**\n * Selects the correct option(s) if `value` is given,\n * and then sets up a mutation observer to sync the\n * current selection to the dom when it changes. Such\n * changes could for example occur when options are\n * inside an `#each` block.\n * @param {HTMLSelectElement} select\n */\nexport function init_select(select) {\n\tvar observer = new MutationObserver(() => {\n\t\t// @ts-ignore\n\t\tselect_option(select, select.__value);\n\t\t// Deliberately don't update the potential binding value,\n\t\t// the model should be preserved unless explicitly changed\n\t});\n\n\tobserver.observe(select, {\n\t\t// Listen to option element changes\n\t\tchildList: true,\n\t\tsubtree: true, // because of <optgroup>\n\t\t// Listen to option element value attribute changes\n\t\t// (doesn't get notified of select value changes,\n\t\t// because that property is not reflected as an attribute)\n\t\tattributes: true,\n\t\tattributeFilter: ['value']\n\t});\n\n\tteardown(() => {\n\t\tobserver.disconnect();\n\t});\n}\n\n/**\n * @param {HTMLSelectElement} select\n * @param {() => unknown} get\n * @param {(value: unknown) => void} set\n * @returns {void}\n */\nexport function bind_select_value(select, get, set = get) {\n\tvar batches = new WeakSet();\n\tvar mounting = true;\n\n\tlisten_to_event_and_reset_event(select, 'change', (is_reset) => {\n\t\tvar query = is_reset ? '[selected]' : ':checked';\n\t\t/** @type {unknown} */\n\t\tvar value;\n\n\t\tif (select.multiple) {\n\t\t\tvalue = [].map.call(select.querySelectorAll(query), get_option_value);\n\t\t} else {\n\t\t\t/** @type {HTMLOptionElement | null} */\n\t\t\tvar selected_option =\n\t\t\t\tselect.querySelector(query) ??\n\t\t\t\t// will fall back to first non-disabled option if no option is selected\n\t\t\t\tselect.querySelector('option:not([disabled])');\n\t\t\tvalue = selected_option && get_option_value(selected_option);\n\t\t}\n\n\t\tset(value);\n\n\t\t// @ts-ignore\n\t\tselect.__value = value;\n\n\t\tif (current_batch !== null) {\n\t\t\tbatches.add(current_batch);\n\t\t}\n\t});\n\n\t// Needs to be an effect, not a render_effect, so that in case of each loops the logic runs after the each block has updated\n\teffect(() => {\n\t\tvar value = get();\n\n\t\tif (select === document.activeElement) {\n\t\t\t// In sync mode render effects are executed during tree traversal -> needs current_batch\n\t\t\t// In async mode render effects are flushed once batch resolved, at which point current_batch is null -> needs previous_batch\n\t\t\tvar batch = /** @type {Batch} */ (async_mode_flag ? previous_batch : current_batch);\n\n\t\t\t// Don't update the <select> if it is focused. We can get here if, for example,\n\t\t\t// an update is deferred because of async work depending on the select:\n\t\t\t//\n\t\t\t// <select bind:value={selected}>...</select>\n\t\t\t// <p>{await find(selected)}</p>\n\t\t\tif (batches.has(batch)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tselect_option(select, value, mounting);\n\n\t\t// Mounting and value undefined -> take selection from dom\n\t\tif (mounting && value === undefined) {\n\t\t\t/** @type {HTMLOptionElement | null} */\n\t\t\tvar selected_option = select.querySelector(':checked');\n\t\t\tif (selected_option !== null) {\n\t\t\t\tvalue = get_option_value(selected_option);\n\t\t\t\tset(value);\n\t\t\t}\n\t\t}\n\n\t\t// @ts-ignore\n\t\tselect.__value = value;\n\t\tmounting = false;\n\t});\n\n\tinit_select(select);\n}\n\n/** @param {HTMLOptionElement} option */\nfunction get_option_value(option) {\n\t// __value only exists if the <option> has a value attribute\n\tif ('__value' in option) {\n\t\treturn option.__value;\n\t} else {\n\t\treturn option.value;\n\t}\n}\n","/** @import { Batch } from '../../../reactivity/batch.js' */\nimport { DEV } from 'esm-env';\nimport { render_effect, teardown } from '../../../reactivity/effects.js';\nimport { listen_to_event_and_reset_event } from './shared.js';\nimport * as e from '../../../errors.js';\nimport { is } from '../../../proxy.js';\nimport { queue_micro_task } from '../../task.js';\nimport { hydrating } from '../../hydration.js';\nimport { tick, untrack } from '../../../runtime.js';\nimport { is_runes } from '../../../context.js';\nimport { current_batch, previous_batch } from '../../../reactivity/batch.js';\nimport { async_mode_flag } from '../../../../flags/index.js';\n\n/**\n * @param {HTMLInputElement} input\n * @param {() => unknown} get\n * @param {(value: unknown) => void} set\n * @returns {void}\n */\nexport function bind_value(input, get, set = get) {\n\tvar batches = new WeakSet();\n\n\tlisten_to_event_and_reset_event(input, 'input', async (is_reset) => {\n\t\tif (DEV && input.type === 'checkbox') {\n\t\t\t// TODO should this happen in prod too?\n\t\t\te.bind_invalid_checkbox_value();\n\t\t}\n\n\t\t/** @type {any} */\n\t\tvar value = is_reset ? input.defaultValue : input.value;\n\t\tvalue = is_numberlike_input(input) ? to_number(value) : value;\n\t\tset(value);\n\n\t\tif (current_batch !== null) {\n\t\t\tbatches.add(current_batch);\n\t\t}\n\n\t\t// Because `{#each ...}` blocks work by updating sources inside the flush,\n\t\t// we need to wait a tick before checking to see if we should forcibly\n\t\t// update the input and reset the selection state\n\t\tawait tick();\n\n\t\t// Respect any validation in accessors\n\t\tif (value !== (value = get())) {\n\t\t\tvar start = input.selectionStart;\n\t\t\tvar end = input.selectionEnd;\n\t\t\tvar length = input.value.length;\n\n\t\t\t// the value is coerced on assignment\n\t\t\tinput.value = value ?? '';\n\n\t\t\t// Restore selection\n\t\t\tif (end !== null) {\n\t\t\t\tvar new_length = input.value.length;\n\t\t\t\t// If cursor was at end and new input is longer, move cursor to new end\n\t\t\t\tif (start === end && end === length && new_length > length) {\n\t\t\t\t\tinput.selectionStart = new_length;\n\t\t\t\t\tinput.selectionEnd = new_length;\n\t\t\t\t} else {\n\t\t\t\t\tinput.selectionStart = start;\n\t\t\t\t\tinput.selectionEnd = Math.min(end, new_length);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t});\n\n\tif (\n\t\t// If we are hydrating and the value has since changed,\n\t\t// then use the updated value from the input instead.\n\t\t(hydrating && input.defaultValue !== input.value) ||\n\t\t// If defaultValue is set, then value == defaultValue\n\t\t// TODO Svelte 6: remove input.value check and set to empty string?\n\t\t(untrack(get) == null && input.value)\n\t) {\n\t\tset(is_numberlike_input(input) ? to_number(input.value) : input.value);\n\n\t\tif (current_batch !== null) {\n\t\t\tbatches.add(current_batch);\n\t\t}\n\t}\n\n\trender_effect(() => {\n\t\tif (DEV && input.type === 'checkbox') {\n\t\t\t// TODO should this happen in prod too?\n\t\t\te.bind_invalid_checkbox_value();\n\t\t}\n\n\t\tvar value = get();\n\n\t\tif (input === document.activeElement) {\n\t\t\t// In sync mode render effects are executed during tree traversal -> needs current_batch\n\t\t\t// In async mode render effects are flushed once batch resolved, at which point current_batch is null -> needs previous_batch\n\t\t\tvar batch = /** @type {Batch} */ (async_mode_flag ? previous_batch : current_batch);\n\n\t\t\t// Never rewrite the contents of a focused input. We can get here if, for example,\n\t\t\t// an update is deferred because of async work depending on the input:\n\t\t\t//\n\t\t\t// <input bind:value={query}>\n\t\t\t// <p>{await find(query)}</p>\n\t\t\tif (batches.has(batch)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tif (is_numberlike_input(input) && value === to_number(input.value)) {\n\t\t\t// handles 0 vs 00 case (see https://github.com/sveltejs/svelte/issues/9959)\n\t\t\treturn;\n\t\t}\n\n\t\tif (input.type === 'date' && !value && !input.value) {\n\t\t\t// Handles the case where a temporarily invalid date is set (while typing, for example with a leading 0 for the day)\n\t\t\t// and prevents this state from clearing the other parts of the date input (see https://github.com/sveltejs/svelte/issues/7897)\n\t\t\treturn;\n\t\t}\n\n\t\t// don't set the value of the input if it's the same to allow\n\t\t// minlength to work properly\n\t\tif (value !== input.value) {\n\t\t\t// @ts-expect-error the value is coerced on assignment\n\t\t\tinput.value = value ?? '';\n\t\t}\n\t});\n}\n\n/** @type {Set<HTMLInputElement[]>} */\nconst pending = new Set();\n\n/**\n * @param {HTMLInputElement[]} inputs\n * @param {null | [number]} group_index\n * @param {HTMLInputElement} input\n * @param {() => unknown} get\n * @param {(value: unknown) => void} set\n * @returns {void}\n */\nexport function bind_group(inputs, group_index, input, get, set = get) {\n\tvar is_checkbox = input.getAttribute('type') === 'checkbox';\n\tvar binding_group = inputs;\n\n\t// needs to be let or related code isn't treeshaken out if it's always false\n\tlet hydration_mismatch = false;\n\n\tif (group_index !== null) {\n\t\tfor (var index of group_index) {\n\t\t\t// @ts-expect-error\n\t\t\tbinding_group = binding_group[index] ??= [];\n\t\t}\n\t}\n\n\tbinding_group.push(input);\n\n\tlisten_to_event_and_reset_event(\n\t\tinput,\n\t\t'change',\n\t\t() => {\n\t\t\t// @ts-ignore\n\t\t\tvar value = input.__value;\n\n\t\t\tif (is_checkbox) {\n\t\t\t\tvalue = get_binding_group_value(binding_group, value, input.checked);\n\t\t\t}\n\n\t\t\tset(value);\n\t\t},\n\t\t// TODO better default value handling\n\t\t() => set(is_checkbox ? [] : null)\n\t);\n\n\trender_effect(() => {\n\t\tvar value = get();\n\n\t\t// If we are hydrating and the value has since changed, then use the update value\n\t\t// from the input instead.\n\t\tif (hydrating && input.defaultChecked !== input.checked) {\n\t\t\thydration_mismatch = true;\n\t\t\treturn;\n\t\t}\n\n\t\tif (is_checkbox) {\n\t\t\tvalue = value || [];\n\t\t\t// @ts-ignore\n\t\t\tinput.checked = value.includes(input.__value);\n\t\t} else {\n\t\t\t// @ts-ignore\n\t\t\tinput.checked = is(input.__value, value);\n\t\t}\n\t});\n\n\tteardown(() => {\n\t\tvar index = binding_group.indexOf(input);\n\n\t\tif (index !== -1) {\n\t\t\tbinding_group.splice(index, 1);\n\t\t}\n\t});\n\n\tif (!pending.has(binding_group)) {\n\t\tpending.add(binding_group);\n\n\t\tqueue_micro_task(() => {\n\t\t\t// necessary to maintain binding group order in all insertion scenarios\n\t\t\tbinding_group.sort((a, b) => (a.compareDocumentPosition(b) === 4 ? -1 : 1));\n\t\t\tpending.delete(binding_group);\n\t\t});\n\t}\n\n\tqueue_micro_task(() => {\n\t\tif (hydration_mismatch) {\n\t\t\tvar value;\n\n\t\t\tif (is_checkbox) {\n\t\t\t\tvalue = get_binding_group_value(binding_group, value, input.checked);\n\t\t\t} else {\n\t\t\t\tvar hydration_input = binding_group.find((input) => input.checked);\n\t\t\t\t// @ts-ignore\n\t\t\t\tvalue = hydration_input?.__value;\n\t\t\t}\n\n\t\t\tset(value);\n\t\t}\n\t});\n}\n\n/**\n * @param {HTMLInputElement} input\n * @param {() => unknown} get\n * @param {(value: unknown) => void} set\n * @returns {void}\n */\nexport function bind_checked(input, get, set = get) {\n\tlisten_to_event_and_reset_event(input, 'change', (is_reset) => {\n\t\tvar value = is_reset ? input.defaultChecked : input.checked;\n\t\tset(value);\n\t});\n\n\tif (\n\t\t// If we are hydrating and the value has since changed,\n\t\t// then use the update value from the input instead.\n\t\t(hydrating && input.defaultChecked !== input.checked) ||\n\t\t// If defaultChecked is set, then checked == defaultChecked\n\t\tuntrack(get) == null\n\t) {\n\t\tset(input.checked);\n\t}\n\n\trender_effect(() => {\n\t\tvar value = get();\n\t\tinput.checked = Boolean(value);\n\t});\n}\n\n/**\n * @template V\n * @param {Array<HTMLInputElement>} group\n * @param {V} __value\n * @param {boolean} checked\n * @returns {V[]}\n */\nfunction get_binding_group_value(group, __value, checked) {\n\t/** @type {Set<V>} */\n\tvar value = new Set();\n\n\tfor (var i = 0; i < group.length; i += 1) {\n\t\tif (group[i].checked) {\n\t\t\t// @ts-ignore\n\t\t\tvalue.add(group[i].__value);\n\t\t}\n\t}\n\n\tif (!checked) {\n\t\tvalue.delete(__value);\n\t}\n\n\treturn Array.from(value);\n}\n\n/**\n * @param {HTMLInputElement} input\n */\nfunction is_numberlike_input(input) {\n\tvar type = input.type;\n\treturn type === 'number' || type === 'range';\n}\n\n/**\n * @param {string} value\n */\nfunction to_number(value) {\n\treturn value === '' ? null : +value;\n}\n\n/**\n * @param {HTMLInputElement} input\n * @param {() => FileList | null} get\n * @param {(value: FileList | null) => void} set\n */\nexport function bind_files(input, get, set = get) {\n\tlisten_to_event_and_reset_event(input, 'change', () => {\n\t\tset(input.files);\n\t});\n\n\tif (\n\t\t// If we are hydrating and the value has since changed,\n\t\t// then use the updated value from the input instead.\n\t\thydrating &&\n\t\tinput.files\n\t) {\n\t\tset(input.files);\n\t}\n\n\trender_effect(() => {\n\t\tinput.files = get();\n\t});\n}\n","export const ssr = false;\nexport const prerender = true;\n","import {params, globalQueryParams} from '$lib/core/config';\nimport {resolve} from '$app/paths';\nimport {getParamsFromURL, queryStringifyNoArray} from './url.js';\n\nexport function route(p: string, hash?: string) {\n\tif (!p.endsWith('/')) {\n\t\tp += '/';\n\t}\n\tconst pathToResolve = `${p}${getQueryStringToKeep(p)}${hash ? `#${hash}` : ''}`;\n\tlet path = resolve<any>(pathToResolve);\n\treturn path;\n}\n\nfunction getQueryStringToKeep(p: string): string {\n\tif (globalQueryParams && globalQueryParams.length > 0) {\n\t\tconst {params: paramFromPath} = getParamsFromURL(p);\n\t\tfor (const queryParam of globalQueryParams) {\n\t\t\tif (\n\t\t\t\ttypeof params[queryParam] != 'undefined' &&\n\t\t\t\ttypeof paramFromPath[queryParam] === 'undefined'\n\t\t\t) {\n\t\t\t\tparamFromPath[queryParam] = params[queryParam];\n\t\t\t}\n\t\t}\n\t\treturn queryStringifyNoArray(paramFromPath);\n\t} else {\n\t\treturn '';\n\t}\n}\n\nexport function url(p: string, hash?: string) {\n\treturn resolve<any>(\n\t\thash ? `${p}${hash.startsWith('#') ? hash : `#${hash}`}` : p,\n\t);\n}\n\nexport function isSameRoute(a: string, b: string): boolean {\n\treturn a === b || a === route(b);\n}\n\nexport function isParentRoute(a: string, b: string): boolean {\n\treturn a.startsWith(b) || a.startsWith(route(b));\n}\n","<script lang=\"ts\">\n\timport {dev, version} from '$app/environment';\n\timport {page} from '$app/state';\n\n\timport {\n\t\tname,\n\t\tdescription,\n\t\tthemeColor,\n\t\tcanonicalURL,\n\t\tappleStatusBarStyle,\n\t\tENSName,\n\t} from '../web-config.json';\n\timport {url} from '$lib/core/utils/web/path';\n\n\tconst host = canonicalURL.endsWith('/')\n\t\t? canonicalURL.slice(0, -1)\n\t\t: canonicalURL;\n\tconst previewImage = host + '/preview.png';\n\n\tinterface Props {\n\t\ttype?: 'website' | 'article';\n\t\ttitle?: string;\n\t\tdescription?: string;\n\t\timage?: string;\n\t\thome?: boolean;\n\t}\n\n\tlet overrides: Props = $props();\n\n\tlet isHome = $derived(overrides.home || false);\n\n\tlet metadata = $derived({\n\t\ttype: overrides.type || 'website',\n\t\ttitle: overrides.title || name,\n\t\tdescription: overrides.description || description,\n\t\timage: overrides.image || previewImage,\n\t\turl: `${host}${page.url.pathname}`,\n\t});\n</script>\n\n<svelte:head>\n\t<title>{metadata.title}</title>\n\t<meta name=\"title\" content={metadata.title} />\n\t<meta name=\"description\" content={metadata.description} />\n\t{#if isHome}\n\t\t{#if ENSName}\n\t\t\t<meta name=\"Dwebsite\" content={ENSName} />\n\t\t{/if}\n\n\t\t<!-- TODO get url -->\n\t{/if}\n\n\t<meta property=\"og:type\" content={metadata.type} />\n\t<meta property=\"og:url\" content={metadata.url} />\n\t<meta property=\"og:title\" content={metadata.title} />\n\t<meta property=\"og:description\" content={metadata.description} />\n\t<meta property=\"og:image\" content={metadata.image} />\n\t<meta property=\"twitter:card\" content=\"summary_large_image\" />\n\t<meta property=\"twitter:url\" content={metadata.url} />\n\t<meta property=\"twitter:title\" content={metadata.title} />\n\t<meta property=\"twitter:description\" content={metadata.description} />\n\t<meta property=\"twitter:image\" content={metadata.image} />\n\n\t<!-- minimal -->\n\t<!-- use SVG, if need PNG, adapt accordingly -->\n\t<!-- TODO automatise -->\n\t<link rel=\"icon\" href={url('/pwa/favicon.png')} type=\"image/png\" />\n\t<link rel=\"icon\" href={url('/pwa/favicon.ico')} sizes=\"any\" /><!-- 32×32 -->\n\t<link\n\t\trel=\"apple-touch-icon\"\n\t\thref={url('/pwa/apple-touch-icon.png')}\n\t/><!-- 180×180 -->\n\t<link rel=\"manifest\" href={url('/pwa/manifest.webmanifest')} />\n\n\t<!-- extra info -->\n\t<meta name=\"theme-color\" content={themeColor} />\n\t<meta name=\"mobile-web-app-capable\" content=\"yes\" />\n\t<meta name=\"application-name\" content={name} />\n\n\t<!-- apple -->\n\t<meta name=\"apple-mobile-web-app-capable\" content=\"yes\" />\n\t<meta\n\t\tname=\"apple-mobile-web-app-status-bar-style\"\n\t\tcontent={appleStatusBarStyle}\n\t/>\n\t<meta name=\"apple-mobile-web-app-title\" content={name} />\n\n\t<meta name=\"version\" content={version} />\n</svelte:head>\n","// Inviting \"agent is waiting for you\" chime, synthesised with the Web Audio API\n// so no audio asset needs to be bundled or fetched. The sound is deliberately\n// gentle: a soft two-note rising interval (a friendly \"ding-dong\" that invites\n// attention rather than an alarm), with a short attack and a smooth decay so it\n// never clips or sounds harsh.\n//\n// Browsers block audio until the user has interacted with the page, so the\n// AudioContext is created lazily on the first play and any failure is swallowed\n// (a beep is a nicety, never a hard requirement).\n\nlet audioCtx: AudioContext | null = null;\n\nfunction getContext(): AudioContext | null {\n\tif (typeof window === 'undefined') return null;\n\ttry {\n\t\tif (!audioCtx) {\n\t\t\tconst Ctor =\n\t\t\t\twindow.AudioContext ||\n\t\t\t\t(window as unknown as {webkitAudioContext?: typeof AudioContext})\n\t\t\t\t\t.webkitAudioContext;\n\t\t\tif (!Ctor) return null;\n\t\t\taudioCtx = new Ctor();\n\t\t}\n\t\t// A context can be left 'suspended' until a user gesture resumes it.\n\t\tif (audioCtx.state === 'suspended') {\n\t\t\t// Best-effort; if it stays suspended the play simply produces no sound.\n\t\t\taudioCtx.resume().catch(() => {});\n\t\t}\n\t\treturn audioCtx;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n// Play one note (a sine tone) with a soft attack/decay envelope.\nfunction playNote(\n\tctx: AudioContext,\n\tfrequency: number,\n\tstartTime: number,\n\tduration: number,\n\tpeakGain: number,\n): void {\n\tconst osc = ctx.createOscillator();\n\tconst gain = ctx.createGain();\n\tosc.type = 'sine';\n\tosc.frequency.value = frequency;\n\n\t// Envelope: quick-but-not-instant attack, then an exponential fade so the\n\t// tail is smooth (no click). exponentialRampToValueAtTime cannot target 0,\n\t// so we ramp to a tiny value and stop just after.\n\tconst attack = 0.015;\n\tgain.gain.setValueAtTime(0.0001, startTime);\n\tgain.gain.exponentialRampToValueAtTime(peakGain, startTime + attack);\n\tgain.gain.exponentialRampToValueAtTime(0.0001, startTime + duration);\n\n\tosc.connect(gain);\n\tgain.connect(ctx.destination);\n\tosc.start(startTime);\n\tosc.stop(startTime + duration + 0.02);\n}\n\n// Cache one Audio element per custom sound URL so we do not re-fetch/re-decode\n// on every play. Rewinding a reused element is cheaper and avoids a growing pile\n// of elements.\nconst customAudioCache = new Map<string, HTMLAudioElement>();\n\n// Play a user-supplied sound file (URL/path). Returns true if playback was\n// started (or at least attempted without throwing synchronously), false if it\n// could not be set up so the caller can fall back to the synthesized chime.\nfunction playCustomSound(url: string): boolean {\n\tif (typeof Audio === 'undefined') return false;\n\ttry {\n\t\tlet el = customAudioCache.get(url);\n\t\tif (!el) {\n\t\t\tel = new Audio(url);\n\t\t\tel.preload = 'auto';\n\t\t\tcustomAudioCache.set(url, el);\n\t\t}\n\t\ttry {\n\t\t\tel.currentTime = 0;\n\t\t} catch {\n\t\t\t// Some elements throw if not yet seekable; ignore and let play() handle it.\n\t\t}\n\t\t// play() returns a promise that rejects if blocked (autoplay policy) or the\n\t\t// source failed to load. Swallow both: a beep is a nicety.\n\t\tconst p = el.play();\n\t\tif (p && typeof p.catch === 'function') p.catch(() => {});\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/**\n * Play the inviting waiting-for-human chime. Safe to call from anywhere; a no-op\n * (rather than a throw) when audio is unavailable or blocked.\n *\n * When `soundUrl` is provided (a user-configured sound file), it is played\n * instead of the synthesized chime; if that cannot be set up, we fall back to\n * the built-in two-note chime (C6 then F6, a gentle rising interval that reads\n * as a friendly \"you're up\" prompt).\n */\nexport function playInvitingBeep(soundUrl?: string): void {\n\tif (soundUrl && soundUrl.trim()) {\n\t\tif (playCustomSound(soundUrl.trim())) return;\n\t\t// else fall through to the synthesized chime.\n\t}\n\tconst ctx = getContext();\n\tif (!ctx) return;\n\ttry {\n\t\tconst now = ctx.currentTime;\n\t\t// Two soft rising notes: C6 then F6 (a gentle, welcoming interval).\n\t\tplayNote(ctx, 1046.5, now, 0.16, 0.12);\n\t\tplayNote(ctx, 1396.9, now + 0.13, 0.22, 0.12);\n\t} catch {\n\t\t// Swallow: the beep is a nicety, never a hard requirement.\n\t}\n}\n","// Recognize a `/skill:<name> <args>` invocation in EITHER form and return its\n// parsed parts, or null when the content is not a skill invocation.\n//\n// Two forms carry the same logical invocation and must be treated as one:\n// - RAW: what the client sends and optimistically echoes, e.g.\n// `/skill:setup do the thing`\n// - EXPANDED: what the server stores/echoes back after pi inlines the skill\n// body (pi's _expandSkillCommand), e.g.\n// `<skill name=\"setup\" location=\"...\">\\n...body...\\n</skill>\\n\\ndo the thing`\n// Both resolve to { skillName: 'setup', args: 'do the thing' }. This lets the\n// delivery-confirmation match the optimistic RAW echo to the server's EXPANDED\n// echo (same invocation) instead of appending a duplicate and orphaning the\n// optimistic bubble as \"failed\".\nexport function parseSkillInvocation(content) {\n if (!content)\n return null;\n const trimmed = content.trimStart();\n // Expanded form: the stored/echoed skill block.\n const open = trimmed.match(/^<skill\\s+name=\"([^\"]*)\"[^>]*>/);\n if (open) {\n const closeIdx = trimmed.indexOf('</skill>');\n if (closeIdx === -1)\n return null;\n return {\n skillName: open[1],\n args: trimmed.slice(closeIdx + '</skill>'.length).trim(),\n };\n }\n // Raw form: the `/skill:<name> <args>` the user typed / the client sent.\n if (trimmed.startsWith('/skill:')) {\n const rest = trimmed.slice('/skill:'.length);\n const spaceIdx = rest.indexOf(' ');\n const skillName = spaceIdx === -1 ? rest : rest.slice(0, spaceIdx);\n if (!skillName)\n return null;\n const args = spaceIdx === -1 ? '' : rest.slice(spaceIdx + 1).trim();\n return { skillName, args };\n }\n return null;\n}\n// A stable identity string for a skill invocation, or null when `content` is not\n// one. Equal identities mean the RAW and EXPANDED forms are the same invocation.\n// The NUL separator cannot appear in either the name or the args.\nexport function skillInvocationIdentity(content) {\n const parsed = parseSkillInvocation(content);\n if (!parsed)\n return null;\n return `skill:${parsed.skillName}\\u0000${parsed.args}`;\n}\n//# sourceMappingURL=types.js.map","// src/svelte_internals_utils.ts\nfunction noop() {\n}\nvar identity = (x) => x;\nfunction run(fn) {\n return fn();\n}\nfunction run_all(fns) {\n fns.forEach(run);\n}\nfunction is_function(thing) {\n return typeof thing === \"function\";\n}\nfunction safe_not_equal(a, b) {\n return a != a ? b == b : a !== b || a && typeof a === \"object\" || typeof a === \"function\";\n}\nfunction subscribe(store, ...callbacks) {\n if (store == null) {\n return noop;\n }\n const unsub = store.subscribe(...callbacks);\n return unsub.unsubscribe ? () => unsub.unsubscribe() : unsub;\n}\nfunction get_store_value(store) {\n let value;\n subscribe(store, (_) => value = _)();\n return value;\n}\n\n// src/svelte_stores.ts\nvar subscriber_queue = [];\nfunction readable(value, start) {\n return {\n subscribe: writable(value, start).subscribe\n };\n}\nfunction writable(value, start = noop) {\n let stop;\n const subscribers = /* @__PURE__ */ new Set();\n function set(new_value) {\n if (safe_not_equal(value, new_value)) {\n value = new_value;\n if (stop) {\n const run_queue = !subscriber_queue.length;\n for (const subscriber of subscribers) {\n subscriber[1]();\n subscriber_queue.push(subscriber, value);\n }\n if (run_queue) {\n for (let i = 0; i < subscriber_queue.length; i += 2) {\n subscriber_queue[i][0](subscriber_queue[i + 1]);\n }\n subscriber_queue.length = 0;\n }\n }\n }\n }\n function update(fn) {\n set(fn(value));\n }\n function subscribe2(run2, invalidate = noop) {\n const subscriber = [run2, invalidate];\n subscribers.add(subscriber);\n if (subscribers.size === 1) {\n stop = start(set) || noop;\n }\n run2(value);\n return () => {\n subscribers.delete(subscriber);\n if (subscribers.size === 0) {\n stop();\n stop = null;\n }\n };\n }\n return { set, update, subscribe: subscribe2 };\n}\nfunction derived(stores, fn, initial_value) {\n const single = !Array.isArray(stores);\n const stores_array = single ? [stores] : stores;\n const auto = fn.length < 2;\n return readable(initial_value, (set) => {\n let inited = false;\n const values = [];\n let pending = 0;\n let cleanup = noop;\n const sync = () => {\n if (pending) {\n return;\n }\n cleanup();\n const result = fn(single ? values[0] : values, set);\n if (auto) {\n set(result);\n } else {\n cleanup = is_function(result) ? result : noop;\n }\n };\n const unsubscribers = stores_array.map(\n (store, i) => subscribe(\n store,\n (value) => {\n values[i] = value;\n pending &= ~(1 << i);\n if (inited) {\n sync();\n }\n },\n () => {\n pending |= 1 << i;\n }\n )\n );\n inited = true;\n sync();\n return function stop() {\n run_all(unsubscribers);\n cleanup();\n };\n });\n}\nexport {\n derived,\n get_store_value as get,\n identity,\n noop,\n readable,\n writable\n};\n","/**\n * Client half of frame chunking (`frames=chunk.v1`); the server half and the\n * rationale are in `server/src/frame-chunks.ts` (kept in sync by hand).\n *\n * The client asks for chunks with `frames=chunk.v1` on the socket URL. A large\n * server frame then arrives as several text frames, each\n * `\\u0001<id> <seq> <count>\\n<data>`; concatenating the data in order gives back\n * the original JSON. Every chunk is an inbound frame, which is what keeps the\n * liveness watchdog from condemning a socket that is busy delivering a\n * multi-MB history over a slow link.\n */\nexport const FRAME_CHUNK_PARAM = 'frames';\nexport const FRAME_CHUNK_VERSION = 'chunk.v1';\nconst MARK = 1; // U+0001: never the first character of a JSON document\n/**\n * Reassembles chunked frames for ONE socket (make a new one per socket: a\n * message whose chunks were cut short by a drop is never completed on another).\n * Chunks of one message are sent back to back, so only one message is ever in\n * progress; a new id simply replaces an unfinished one.\n */\nexport class FrameReassembler {\n id = null;\n count = 0;\n parts = [];\n /** True when `text` is a chunk rather than an ordinary frame. */\n static isChunk(text) {\n return text.charCodeAt(0) === MARK;\n }\n /** Feed one text frame. A non-chunk frame is passed straight through. */\n push(text) {\n if (!FrameReassembler.isChunk(text))\n return { kind: 'frame', text };\n const nl = text.indexOf('\\n');\n if (nl < 0)\n return { kind: 'invalid' };\n const [id, seqRaw, countRaw] = text.slice(1, nl).split(' ');\n const seq = Number(seqRaw);\n const count = Number(countRaw);\n if (!id || !Number.isInteger(seq) || !Number.isInteger(count) || count < 1 || seq < 0 || seq >= count) {\n return { kind: 'invalid' };\n }\n if (seq === 0 || id !== this.id) {\n if (seq !== 0) {\n // The start of this message was never seen: drop it.\n this.reset();\n return { kind: 'invalid' };\n }\n this.id = id;\n this.count = count;\n this.parts = [];\n }\n if (seq !== this.parts.length || count !== this.count) {\n this.reset();\n return { kind: 'invalid' };\n }\n this.parts.push(text.slice(nl + 1));\n if (this.parts.length < this.count) {\n return { kind: 'partial', received: this.parts.length, count: this.count };\n }\n const full = this.parts.join('');\n this.reset();\n return { kind: 'frame', text: full };\n }\n reset() {\n this.id = null;\n this.count = 0;\n this.parts = [];\n }\n}\n//# sourceMappingURL=frame-chunks.js.map","import { writable, get } from \"sveltore\";\nimport { skillInvocationIdentity, } from \"./types.js\";\nimport { FrameReassembler, FRAME_CHUNK_PARAM, FRAME_CHUNK_VERSION } from \"./frame-chunks.js\";\n// Per-instance fallback identity: stable for the lifetime of this client object,\n// which is exactly the lifetime across which reconnects happen.\nfunction generateClientKey() {\n return `ck-${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`;\n}\n// --- Uploads (docs/adr/0012, frames in docs/USAGE.md) ----------------------\n/** The capability a server advertises in `connected` for chunked uploads. */\nexport const UPLOAD_CAPABILITY = 'upload.v1';\nconst KiB = 1024;\n/**\n * Chunked-upload pacing. The window is the number of BYTES in flight (sent, not\n * yet acked): about UPLOAD_WINDOW_SECONDS worth at the throughput measured from\n * acks, clamped to [UPLOAD_WINDOW_MIN, UPLOAD_WINDOW_MAX]. Before any ack has\n * been timed it is the minimum, so a slow uplink is never flooded (a queue of\n * bytes ahead of the heartbeat pong is what used to kill the socket). Each chunk\n * is `min(window, UPLOAD_CHUNK_MAX)`, well under the server's 1 MiB cap.\n */\nconst UPLOAD_WINDOW_MIN = 64 * KiB;\nconst UPLOAD_WINDOW_MAX = 1024 * KiB;\nconst UPLOAD_CHUNK_MAX = 256 * KiB;\nconst UPLOAD_WINDOW_SECONDS = 2;\n// Weight of the newest throughput sample in the moving average.\nconst UPLOAD_RATE_ALPHA = 0.3;\n// Legacy base64 is built from reads of this many bytes: a multiple of 3, so\n// each piece encodes without `=` padding and the pieces simply concatenate.\nconst LEGACY_READ_BYTES = 3 * 256 * KiB;\nconst NOT_READABLE_MESSAGE = 'The file is no longer readable, pick it again';\n/** `[u8 kind=1][u8 version=1][u8 idLen][uploadId ascii][u64 offset BE][payload]` */\nexport function encodeChunkFrame(uploadId, offset, payload) {\n const head = 3 + uploadId.length;\n const frame = new Uint8Array(head + 8 + payload.length);\n frame[0] = 1;\n frame[1] = 1;\n frame[2] = uploadId.length;\n for (let i = 0; i < uploadId.length; i++)\n frame[3 + i] = uploadId.charCodeAt(i);\n const view = new DataView(frame.buffer);\n view.setUint32(head, Math.floor(offset / 2 ** 32));\n view.setUint32(head + 4, offset >>> 0);\n frame.set(payload, head + 8);\n return frame;\n}\nfunction bytesToBinaryString(bytes) {\n let out = '';\n for (let i = 0; i < bytes.length; i += 0x8000) {\n out += String.fromCharCode.apply(null, bytes.subarray(i, i + 0x8000));\n }\n return out;\n}\n/**\n * 128 random bits, base64url without padding (22 characters, matching the\n * server's `^[A-Za-z0-9_-]{22,64}$`). The id is what makes a resume\n * unguessable, so it comes from `crypto.getRandomValues`; Math.random is only a\n * last resort for a runtime without Web Crypto.\n */\nfunction generateUploadId() {\n const bytes = new Uint8Array(16);\n const c = globalThis.crypto;\n if (c && typeof c.getRandomValues === 'function') {\n c.getRandomValues(bytes);\n }\n else {\n for (let i = 0; i < bytes.length; i++)\n bytes[i] = Math.floor(Math.random() * 256);\n }\n return btoa(bytesToBinaryString(bytes)).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\nclass UploadReadError extends Error {\n code;\n}\n// The error an upload fails with when its byte source cannot be read.\nfunction uploadReadError(err) {\n if (err instanceof UploadReadError)\n return err;\n if (err && err.name === 'NotReadableError') {\n const e = new UploadReadError(NOT_READABLE_MESSAGE);\n e.code = 'not_readable';\n return e;\n }\n return new UploadReadError(`Failed to read the file: ${(err && err.message) || err}`);\n}\n// A read that returned fewer (or other) bytes than asked: the file changed or\n// was invalidated under us, which to the user is the same as unreadable.\nfunction shortReadError() {\n const e = new UploadReadError(NOT_READABLE_MESSAGE);\n e.code = 'not_readable';\n return e;\n}\n// The host as it goes on the socket URL: a pasted `http(s)://` prefix is dropped.\nfunction socketHost(host) {\n return host.startsWith('http') ? host.replace(/^https?:\\/\\//, '') : host;\n}\n// 32-bit FNV-1a over the UTF-16 code units, as 8 hex digits. NOT a security\n// hash: it only keeps the raw token out of the key (and out of IndexedDB keys)\n// while still telling two tokens apart.\nfunction fnv1a(input) {\n let h = 0x811c9dc5;\n for (let i = 0; i < input.length; i++) {\n h ^= input.charCodeAt(i);\n h = Math.imul(h, 0x01000193);\n }\n return (h >>> 0).toString(16).padStart(8, '0');\n}\n/**\n * The identity of the server a config points at: `host:port#<fnv1a(token)>`.\n * Two configured servers (or one server with a rotated token) never share a\n * key, so the web's conversation cache can never show one server's\n * conversation for another (ADR 0013).\n *\n * Synchronous and pure on purpose: `connect()` is synchronous and must compare\n * it with the stamp before deciding whether to preserve the store, and\n * `crypto.subtle` is both async and missing on plain-http LAN origins. The\n * scheme (`secure`) is deliberately NOT part of the key: ws vs wss to the same\n * host:port is the same server.\n */\nexport function serverKey(config) {\n return `${socketHost(config.host)}:${config.port}#${fnv1a(config.token ?? '')}`;\n}\nconst defaultState = {\n connected: false,\n connecting: false,\n creatingSession: false,\n loadingSession: false,\n resyncing: false,\n agentPending: false,\n error: null,\n session: null,\n sessionId: null,\n isStreaming: false,\n messages: [],\n clientId: null,\n serverVersion: null,\n piVersion: null,\n folderConflict: null,\n folderMissing: null,\n restore: null,\n isInterrupted: false,\n notice: null,\n sudoPrompt: null,\n sessionError: null,\n readOnly: false,\n activeSessionFile: null,\n activeCwd: null,\n activeModel: null,\n hideThinking: false,\n hideTools: false,\n historyTotalCount: 0,\n historyOffset: 0,\n loadingMoreHistory: false,\n historyAuthoritative: false,\n serverKey: null,\n contextUsage: null,\n pendingSteering: [],\n skills: [],\n};\nexport class WhereverClient {\n ws = null;\n config;\n // Identity sent on every connect so the server can retire this viewer's own\n // stale/phantom connection instead of counting it as a second viewer. Replaced\n // (once) if the server reports it as superseded by another live connection.\n clientKey;\n stateStore;\n reconnectTimer = null;\n agentEndTimeout = null;\n // Watchdog for an in-flight session_load. We set loadingSession/resyncing the\n // moment a load is requested and clear them when message_history (or an\n // error/conflict/disconnect) arrives. If none of those ever comes back (a lost\n // reply, a server that answered for a different session, or any unforeseen\n // edge), the \"Loading session...\" / \"Reconnecting...\" affordance would hang\n // forever. This timer guarantees the load state always resolves: on expiry we\n // clear the flags and surface a recoverable error instead of an endless spin.\n loadWatchdog = null;\n static LOAD_WATCHDOG_MS = 12_000;\n // Watchdog for an in-flight session_new. Symmetrical to loadWatchdog: creating\n // a session sets creatingSession=true and shows a BLOCKING full-screen overlay,\n // and the only things that clear it are session_created/session_error/\n // session_interrupted (or a socket close). If none of those\n // ever arrives (a slow git init / remote-repo creation, an error thrown before\n // the reply is sent, or a half-open socket the liveness watchdog has not yet\n // reaped), the overlay spins forever and the only recovery is a reload. This\n // timer guarantees creatingSession always resolves. It is longer than the load\n // watchdog because creating can legitimately take a while (git init + creating\n // a remote GitHub repo over the network).\n createWatchdog = null;\n static CREATE_WATCHDOG_MS = 25_000;\n reconnectAttempts = 0;\n static MIN_RECONNECT_DELAY = 2000;\n reconnectDelay = WhereverClient.MIN_RECONNECT_DELAY;\n // Wall-clock time the current socket was created, so a return to the page can\n // tell a handshake that has hung across a freeze from one just started.\n socketStartedAt = 0;\n maxReconnectDelay = 15000;\n // Whether the socket has EVER opened successfully since construction. Repeated\n // closes with zero successful opens almost always mean a rejected handshake\n // (bad/missing token, wrong host/port, or wrong ws-vs-wss scheme) rather than\n // a transient network drop. A browser WebSocket cannot read the HTTP 401 body\n // (it just sees close code 1006), so we infer auth/config failure from this\n // pattern and surface an actionable error instead of looping silently.\n hasEverConnected = false;\n static HANDSHAKE_FAIL_HINT_AFTER = 2;\n // Liveness watchdog: a half-open TCP socket fires neither 'close' nor 'error',\n // so the existing reconnect machinery never triggers and the agent hangs\n // forever (see work/observations/ws-half-open-connection-hangs-agent-no-heartbeat.md).\n // We record the time of the last inbound frame and, if the socket goes silent\n // for longer than STALE_SOCKET_MS, proactively tear it down and reconnect.\n // A periodic app-level {type:'ping'} keeps a healthy connection refreshed even\n // during long, token-less model turns.\n livenessTimer = null;\n heartbeatTimer = null;\n lastInboundAt = 0;\n // > the server heartbeat (when present) and any normal token-less gap, so a\n // healthy connection is never falsely reaped; short enough to self-heal fast.\n static STALE_SOCKET_MS = 60_000;\n // While a turn is streaming, the keepalive pong should keep traffic flowing, so\n // a shorter deadline surfaces a stalled transport (vs a merely slow model)\n // faster. Still > one HEARTBEAT_MS so a single healthy pong keeps it fresh.\n static TURN_STALL_MS = 45_000;\n // Send a keepalive well under STALE_SOCKET_MS so the pong refreshes liveness.\n static HEARTBEAT_MS = 25_000;\n // Probe-before-teardown (docs/adr/0011): silence past the threshold never\n // tears a socket down by itself. The watchdog pings and waits this long; ANY\n // inbound frame in that window (onMessage) cancels the probe, and only a\n // socket still silent when it expires is torn down. Needed because on a thaw\n // the timers fire BEFORE the frames queued during the freeze are dispatched,\n // so the raw silence verdict is routinely false on a phone.\n static PROBE_GRACE_MS = 5_000;\n // The probe a return to the page starts (noteVisible) uses a shorter grace.\n // The long grace above exists because timers that came due DURING a freeze\n // fire before the frames queued during it; a probe started from the\n // visibility event is a fresh timer, so the queued frames (and a healthy\n // socket's pong, one round trip later) are dispatched well before it fires.\n // Waiting the full 5 s there, then the reconnect backoff on top, is what made\n // coming back to the PWA slower than a reload.\n static VISIBLE_PROBE_GRACE_MS = 2_000;\n // A socket still CONNECTING this long when the page becomes visible is\n // treated as a handshake that hung (typically started before a freeze,\n // against a network that was gone) and restarted. Well above an honest slow\n // mobile TLS handshake, so a return never throws away one that is about to\n // complete.\n static STALLED_HANDSHAKE_MS = 8_000;\n // The pending probe's grace timer, and the socket it was started on. Cleared\n // by any inbound frame, by stopLivenessWatchdog (every socket change), and\n // ignored if the socket it belongs to is no longer current.\n probeTimer = null;\n // Wall-clock time of the previous watchdog tick. A gap of more than 2x\n // HEARTBEAT_MS means the page was frozen; that is an extra, PROACTIVE probe\n // trigger, never the gate (a 45-50 s freeze gap is not a >2x jump yet still\n // crosses TURN_STALL_MS, which is why the probe itself decides).\n lastLivenessTickAt = 0;\n isInitialConnect = true;\n // When set, the next successful (re)connection should rejoin the previously\n // active session instead of starting blank. Used by resume() so a backgrounded\n // tab returns to its cached conversation and resyncs history in place.\n resumeSessionFile = null;\n resumeCwd;\n resumeModel;\n // The sessionFile of the most recent session_load we are still waiting on.\n // A slow load (session A) followed by a switch to another session (B) must not\n // let A's late session_created reply clobber the now-active B: when the reply's\n // sessionFile does not match pendingLoadFile, it is a superseded load and is\n // ignored. Set on every session_load we issue (switch/join/reconnect), cleared\n // when the matching session_created lands (or on leave/new-session/error).\n // null means \"accept any\" (e.g. session_new, whose target file is not known\n // until the reply). The latest tap always wins.\n pendingLoadFile = null;\n // A session request (load or create) the user made while the socket was not\n // open, so its frame could not be sent. It is the user's newest intent and so\n // supersedes the automatic rejoin: onOpen replays it INSTEAD of rejoining the\n // previously-active session. Without this, switching away from a session that\n // was still reconnecting (PWA brought back to the foreground) lost the switch\n // and the rejoin pulled the user back to the old session. Cleared by a leave,\n // a full disconnect, a server-key wipe, the request's watchdog expiring\n // while still armed, or the replay itself. A socket that closes before\n // opening disarms that watchdog without dropping the request, so it is then\n // replayed on a later socket: it is still the user's latest intent.\n queuedSessionRequest = null;\n // Session files and ids of loads the user moved away from while their reply\n // was still on the wire on THIS socket (a rejoin, a slow load). Their late\n // session_created / message_history are dropped even when nothing else would\n // reject them: a session_new in flight accepts any session_created (its file\n // is unknown until the reply), so a late rejoin reply used to be taken for the\n // new session's and switch the view back. Reset on every new socket (the old\n // socket's replies can no longer arrive), and an entry is removed when the\n // user loads that session again.\n abandonedSessions = new Set();\n // serverKey(config) of the socket currently open (captured by connect() next\n // to the socket it opens). session_created stamps it on the store, so the\n // stamp names the server that actually DELIVERED the session even if the\n // settings are edited afterwards.\n socketServerKey = null;\n // The sessionFile painted by hydrateCachedSession(), until the server answers\n // its rejoin with a session_created (or the hydration is abandoned). While\n // set, an untagged session_error answering that load (pendingLoadFile ===\n // hydratedFile) means the cached session is dead: see hydration_rejected.\n hydratedFile = null;\n listeners = new Set();\n // In-flight WebSocket uploads, keyed by uploadId. An upload is NOT bound to\n // the socket it started on. On mobile, picking a file backgrounds the page and\n // the socket is often lost within seconds; the upload then waits for the next\n // connection (it is (re)sent once the rejoin is answered, since a reply owed\n // by a dead socket never arrives). Without a server reply an upload is\n // settled by: a full teardown (disconnect(true)), UPLOAD_TIMEOUT_MS of\n // waiting, MAX_UPLOAD_SENDS attempts each lost with its socket (legacy only),\n // cancellation, or a session change. The one unbounded case is by design: an\n // upload on the wire of a socket that stays open is left to its replies (the\n // server's handlers always answer), so a slow but healthy transfer is never\n // cut off. Two protocols share this machinery (see PendingUpload).\n pendingUploads = new Map();\n // Progress of every upload this client started, keyed by uploadId: the same\n // value each upload's onProgress receives. Settled entries (done / failed /\n // aborted) stay until forgetUpload(), so a late subscriber still sees how an\n // upload ended.\n uploadsStore = writable({});\n // `connected.capabilities` of the CURRENT socket; null until its `connected`\n // frame arrives. Uploads are HELD while null: sending one as legacy to a\n // server that would have taken it chunked would throw resumability away.\n socketCapabilities = null;\n // An upload whose socket dies under it on every attempt (a frame too large\n // for the server's maxPayload, which closes with 1009; or a slow uplink where\n // the multi-MB frame starves the heartbeat) would otherwise be re-sent\n // forever, kicking the live session into a resync each time. After this many\n // sends lost with their socket, it fails. LEGACY frame only: a chunked upload\n // resumes from the server's offset, so a lost socket costs it nothing.\n static MAX_UPLOAD_SENDS = 3;\n // `ws`'s default maxPayload is 100 MiB per frame; leave room for the JSON\n // envelope. Larger base64 payloads are refused (~72 MB files). A backstop:\n // the legacy path refuses `size > MAX_LEGACY_UPLOAD_BYTES` before reading.\n static MAX_UPLOAD_BASE64_CHARS = 96 * 1024 * 1024;\n // base64 of 72 MiB is exactly 96 MiB, MAX_UPLOAD_BASE64_CHARS.\n static MAX_LEGACY_UPLOAD_BYTES = 72 * 1024 * 1024;\n // Bounds the time an upload spends WAITING to be sent (no socket, or held for\n // a rejoin), not its transmission: the clock is cleared whenever the frame\n // actually goes out on an open socket, and re-armed when that socket closes.\n // So a large, slow-but-healthy upload is never rejected mid-transfer.\n static UPLOAD_TIMEOUT_MS = 10 * 60_000;\n // True between a reconnect's rejoin session_load and its session_created.\n // A fresh server socket starts attached to no session with readOnly=false;\n // the server only sets this client's write verdict (readOnly) when it answers\n // the session_load. Uploads sent in that window would bypass the read-only\n // gate (and a multi-MB frame queued ahead of the rejoin could trip the load\n // watchdog), so they are held until session_created lands.\n uploadsHeldForRejoin = false;\n // Per-message confirmation watchdogs. A user message committed optimistically\n // is only proven delivered when the server echoes it back; if no echo lands\n // within CONFIRM_MS the watchdog flips it to delivery:'failed' so the UI can\n // offer a retry instead of pretending it was sent (the half-open-socket loss).\n confirmTimers = new Map();\n static CONFIRM_MS = 12_000;\n static PENDING_PREFIX = 'wherever-pending:';\n constructor(config) {\n this.config = {\n secure: true,\n ...config\n };\n this.clientKey = this.config.clientKey || generateClientKey();\n this.stateStore = writable({\n ...defaultState,\n hideThinking: !!this.config.hideThinking,\n hideTools: !!this.config.hideTools,\n });\n }\n connect(newConfig, preserveState = false) {\n if (newConfig) {\n this.config = {\n ...this.config,\n ...newConfig\n };\n }\n this.disconnect(false);\n // A store stamped by ANOTHER server (host/port/token edited in Connection\n // Settings, which saves without reconnecting, then this connect, including\n // the automatic one from scheduleReconnect) must not be preserved or\n // rejoined: it would paint, and the web would re-cache, one server's\n // conversation under another's key, and the rejoin would ask the new\n // server for a session it does not have. Wipe instead (which clears the\n // stamp too), and drop every pending rejoin source.\n const key = serverKey(this.config);\n const stamped = get(this.stateStore).serverKey;\n if (stamped !== null && stamped !== key) {\n preserveState = false;\n this.resumeSessionFile = null;\n this.resumeCwd = undefined;\n this.resumeModel = undefined;\n this.pendingLoadFile = null;\n this.hydratedFile = null;\n this.queuedSessionRequest = null;\n }\n this.socketServerKey = key;\n // preserveState keeps the cached session/messages in the store across a\n // reconnect (resume path), so the previous conversation stays visible while\n // we reconnect and resync. The default (fresh connect) clears to a blank\n // store as before.\n this.stateStore.update(s => preserveState\n ? { ...s, connecting: true, error: null }\n : {\n ...defaultState,\n connecting: true,\n hideThinking: !!this.config.hideThinking,\n hideTools: !!this.config.hideTools,\n });\n const protocol = this.config.secure ? \"wss\" : \"ws\";\n const host = socketHost(this.config.host);\n // clientKey rides on the URL (not a post-connect frame) so the server can\n // evict this viewer's previous connection BEFORE any session traffic is\n // handled, closing the phantom-viewer window entirely.\n const params = [];\n if (this.config.token)\n params.push(`token=${encodeURIComponent(this.config.token)}`);\n params.push(`clientKey=${encodeURIComponent(this.clientKey)}`);\n // Ask the server to split large frames (frame-chunks.ts): a multi-MB history\n // arriving as ONE frame over a slow link looked like a dead socket to the\n // liveness watchdog, which tore it down and looped forever.\n params.push(`${FRAME_CHUNK_PARAM}=${FRAME_CHUNK_VERSION}`);\n // History tool images by reference (fetched lazily, cached by the browser)\n // rather than as base64 re-sent on every load and reconnect. Opt-in: the\n // caller must then render images that have no `data`.\n if (this.config.imageRefs)\n params.push('imageRefs=1');\n const wsUrl = `${protocol}://${host}:${this.config.port}/ws?${params.join('&')}`;\n const WebSocketImpl = this.config.WebSocketCtor || (typeof globalThis !== 'undefined' ? globalThis.WebSocket : null);\n if (!WebSocketImpl) {\n this.stateStore.update(s => ({\n ...s,\n connecting: false,\n error: \"No WebSocket implementation found. Please pass custom WebSocketCtor.\"\n }));\n return;\n }\n // A new socket: its capabilities are unknown until its `connected` frame.\n this.socketCapabilities = null;\n this.socketStartedAt = Date.now();\n try {\n const wsOptions = this.config.secure && this.config.WebSocketCtor ? { rejectUnauthorized: false } : undefined;\n this.ws = wsOptions ? new WebSocketImpl(wsUrl, wsOptions) : new WebSocketImpl(wsUrl);\n }\n catch (err) {\n this.stateStore.update(s => ({\n ...s,\n connecting: false,\n error: `Failed to connect: ${err}`\n }));\n this.scheduleReconnect();\n return;\n }\n const currentWs = this.ws;\n const reassembler = new FrameReassembler();\n // One warning per run of bad chunks: after one, every remaining chunk of\n // that message is invalid too.\n let inBadChunkRun = false;\n const onOpen = () => {\n if (this.ws !== currentWs)\n return;\n if (!this.isInitialConnect) {\n console.info('[wherever] reconnected to relay');\n }\n this.hasEverConnected = true;\n this.reconnectAttempts = 0;\n this.reconnectDelay = WhereverClient.MIN_RECONNECT_DELAY;\n this.isInitialConnect = false;\n // Replies to loads issued on an earlier socket can no longer arrive.\n this.abandonedSessions.clear();\n this.startLivenessWatchdog();\n this.stateStore.update(s => ({\n ...s,\n connected: true,\n connecting: false,\n error: null\n }));\n // Resume path: rejoin the previously-active session so its history is\n // resynced in place. resyncing stays true until message_history (or an\n // error/conflict) arrives, keeping the \"reconnecting\" affordance up and\n // input blocked without dropping the cached messages.\n //\n // Re-attachment is REQUIRED on every reconnect that still holds a session,\n // not just the suspend/resume path. The server is stateless per socket:\n // each new connection starts attached to NO session (the old socket's\n // close removed this client from the pool). If we do not re-issue\n // session_load here, the relay is connected but the session stream is\n // dead, so the UI shows a frozen conversation (a stale tool call as the\n // last message, Abort disabled) while the agent keeps running headless.\n // Two sources for what to rejoin:\n // 1. resumeSessionFile -> explicit suspend()/resume() (tab background).\n // 2. the store's activeSessionFile -> an UNSOLICITED drop (network\n // blip, tab switch, laptop sleep, half-open reap) where suspend()\n // never ran. This is the case that used to silently freeze.\n //\n // A session request the user made while the socket was down (a switch or\n // a create, see queuedSessionRequest) is newer than any rejoin, so it is\n // sent instead and nothing is rejoined.\n let queued = this.queuedSessionRequest;\n this.queuedSessionRequest = null;\n // A queued load of the session we would rejoin anyway (reloadSession()\n // while disconnected) IS the rejoin: take that path, which keeps held\n // uploads and the resyncing affordance.\n if (queued?.type === 'load' &&\n queued.sessionFile === (this.resumeSessionFile ?? get(this.stateStore).activeSessionFile)) {\n queued = null;\n }\n if (queued) {\n this.resumeSessionFile = null;\n this.resumeCwd = undefined;\n this.resumeModel = undefined;\n this.uploadsHeldForRejoin = false;\n this.rejectPendingUploads('The session changed before the upload could be sent');\n if (queued.type === 'load') {\n this.stateStore.update(s => ({ ...s, loadingSession: true, resyncing: false }));\n this.pendingLoadFile = queued.sessionFile;\n this.send({\n type: 'session_load',\n sessionFile: queued.sessionFile,\n cwd: queued.cwd,\n model: queued.model,\n });\n this.armLoadWatchdog();\n }\n else {\n this.stateStore.update(s => ({\n ...s,\n creatingSession: true,\n loadingSession: false,\n resyncing: false,\n }));\n this.pendingLoadFile = null;\n this.send(queued.frame);\n this.armCreateWatchdog();\n }\n return;\n }\n const cached = get(this.stateStore);\n const rejoinFile = this.resumeSessionFile ?? cached.activeSessionFile;\n const rejoinCwd = this.resumeSessionFile != null\n ? this.resumeCwd\n : (cached.activeCwd ?? undefined);\n const rejoinModel = this.resumeSessionFile != null\n ? this.resumeModel\n : (cached.activeModel ?? undefined);\n this.resumeSessionFile = null;\n this.resumeCwd = undefined;\n this.resumeModel = undefined;\n // Uploads that were waiting for a socket (or whose reply died with the old\n // one) go out only AFTER the rejoin has been answered (see\n // uploadsHeldForRejoin): session_load first, uploads on session_created.\n // With no session to rejoin there is no write verdict to wait for, and\n // nothing to attribute the upload to any more, so they fail.\n this.uploadsHeldForRejoin = !!rejoinFile;\n if (!rejoinFile) {\n this.rejectPendingUploads('The session was closed before the upload could be sent');\n }\n if (rejoinFile) {\n // Keep the cached conversation on screen but mark it resyncing so the\n // \"Reconnecting and syncing session...\" banner shows and sending is\n // blocked until fresh history lands. resyncing is cleared by\n // message_history (or an error/conflict) via the reducer.\n // The history in the store (cached, or from the dropped socket) may be\n // stale until this rejoin's message_history lands.\n this.stateStore.update(s => s.resyncing && !s.historyAuthoritative\n ? s\n : { ...s, resyncing: true, historyAuthoritative: false });\n this.pendingLoadFile = rejoinFile;\n this.send({ type: 'session_load', sessionFile: rejoinFile, cwd: rejoinCwd, model: rejoinModel });\n this.armLoadWatchdog();\n }\n else {\n this.stateStore.update(s => (s.resyncing ? { ...s, resyncing: false } : s));\n }\n };\n const onMessage = (event) => {\n if (this.ws !== currentWs)\n return;\n // Any inbound frame (including the pong reply to our keepalive) proves the\n // socket is alive and resets the stale-socket watchdog.\n this.lastInboundAt = Date.now();\n // ...and answers any pending probe, so it must not tear the socket down.\n this.cancelLivenessProbe();\n try {\n const rawData = typeof event.data === 'string' ? event.data : event.data.toString();\n const piece = reassembler.push(rawData);\n if (piece.kind !== 'invalid')\n inBadChunkRun = false;\n if (piece.kind === 'partial') {\n // A large frame is still arriving: the load it answers is making\n // progress, so it must not time out meanwhile.\n if (this.loadWatchdog)\n this.armLoadWatchdog();\n return;\n }\n if (piece.kind === 'invalid') {\n if (!inBadChunkRun)\n console.warn('[wherever] dropped a malformed or incomplete chunked frame');\n inBadChunkRun = true;\n return;\n }\n const msg = JSON.parse(piece.text);\n this.handleMessage(msg);\n }\n catch (err) {\n console.error(\"Failed to parse WebSocket message:\", err);\n }\n };\n const onClose = () => {\n if (this.ws !== currentWs)\n return;\n this.uploadsLostSocket();\n this.stopLivenessWatchdog();\n this.clearLoadWatchdog();\n this.ws = null;\n this.stateStore.update(s => ({\n ...s,\n connected: false,\n connecting: false,\n // Never leave a session-load spinner stuck if the socket drops mid-load.\n loadingSession: false,\n creatingSession: false,\n // If we still hold an active session, the drop is an unsolicited one on a\n // live conversation: mark it resyncing NOW (during the reconnect backoff)\n // so the user immediately sees \"Reconnecting...\" instead of a frozen view\n // with a stale tool call and a disabled Abort. onOpen re-attaches and the\n // reducer clears resyncing when fresh history lands.\n resyncing: s.activeSessionFile ? true : s.resyncing,\n }));\n this.scheduleReconnect();\n };\n const onError = (err) => {\n if (this.ws !== currentWs)\n return;\n this.stateStore.update(s => ({\n ...s,\n error: s.error || 'Connection error occurred'\n }));\n };\n if (typeof currentWs.addEventListener === 'function') {\n currentWs.addEventListener('open', onOpen);\n currentWs.addEventListener('message', onMessage);\n currentWs.addEventListener('close', onClose);\n currentWs.addEventListener('error', onError);\n }\n else if (typeof currentWs.on === 'function') {\n currentWs.on('open', onOpen);\n currentWs.on('message', (data) => onMessage({ data }));\n currentWs.on('close', onClose);\n currentWs.on('error', onError);\n }\n }\n disconnect(resetState = true) {\n if (this.reconnectTimer) {\n clearTimeout(this.reconnectTimer);\n this.reconnectTimer = null;\n }\n // A pending agent_end clear timer belongs to the socket we are tearing down.\n // Leaving it armed lets it fire against a freshly (re)connected session's\n // state, so cancel it here.\n if (this.agentEndTimeout) {\n clearTimeout(this.agentEndTimeout);\n this.agentEndTimeout = null;\n }\n this.stopLivenessWatchdog();\n // The load/create affordances belong to the socket we are tearing down. If\n // left armed they would later fire against a fresh (re)connected session's\n // state, so cancel them here.\n this.clearLoadWatchdog();\n this.clearCreateWatchdog();\n // suspend()/resume() close the socket through here, bypassing onClose.\n this.uploadsLostSocket();\n if (this.ws) {\n const dyingWs = this.ws;\n try {\n if (typeof dyingWs.removeAllListeners === 'function') {\n dyingWs.removeAllListeners();\n }\n // Closing a socket that is still CONNECTING (e.g. the wherever server is\n // not running so the handshake never completed) makes `ws` abort the\n // handshake and emit an 'error' asynchronously on the next tick. With\n // every listener removed, that 'error' would be an unhandled\n // EventEmitter error and crash the whole process as an\n // uncaughtException. Keep a no-op error sink on the socket we are\n // tearing down so the late error is swallowed, in both the node (`ws`)\n // and browser (`WebSocket`) environments.\n const swallow = () => { };\n if (typeof dyingWs.on === 'function') {\n dyingWs.on('error', swallow);\n }\n else if (typeof dyingWs.addEventListener === 'function') {\n dyingWs.addEventListener('error', swallow);\n }\n else {\n dyingWs.onerror = swallow;\n }\n dyingWs.close();\n }\n catch (err) { }\n this.ws = null;\n }\n if (resetState) {\n // Full teardown wipes the store, so no unconfirmed message survives in it;\n // clear their watchdogs to avoid firing against a fresh store. The\n // persisted-pending localStorage entries intentionally REMAIN so a later\n // load can still recover them.\n for (const t of this.confirmTimers.values())\n clearTimeout(t);\n this.confirmTimers.clear();\n // An explicit full disconnect abandons in-flight uploads (they would\n // otherwise be re-sent to whatever server is connected next).\n this.rejectPendingUploads('Disconnected before the upload completed');\n this.uploadsHeldForRejoin = false;\n this.hydratedFile = null;\n this.queuedSessionRequest = null;\n this.abandonedSessions.clear();\n this.stateStore.set({\n ...defaultState,\n hideThinking: !!this.config.hideThinking,\n hideTools: !!this.config.hideTools,\n });\n }\n else {\n // Preserve-cache teardown (suspend / resume's pre-connect close). The\n // socket is gone, so the store MUST reflect disconnected: leaving a stale\n // connected:true made resume() early-return (its `if (connected) return`\n // guard), so the real reconnect fell through to a plain connect() that did\n // NOT preserve the session, which is what flashed the search / new-session\n // empty-state on tab return. Clearing connected here (without wiping the\n // cached session/messages) lets resume() actually rejoin in place, and\n // never leaves the blocking load/create overlays up on a dead socket.\n this.stateStore.update(s => ({\n ...s,\n connected: false,\n connecting: false,\n loadingSession: false,\n creatingSession: false,\n }));\n }\n }\n // Suspend the connection without tearing down the cached session state. Used\n // when the tab is backgrounded: closing the WebSocket improves bfcache\n // eligibility, but we keep messages/sessionId so returning is a cheap resync\n // rather than a full reload. Records the active session so resume() can rejoin\n // it. Does NOT schedule a reconnect (disconnect(false) clears that timer).\n suspend() {\n const s = get(this.stateStore);\n if (s.activeSessionFile) {\n this.resumeSessionFile = s.activeSessionFile;\n this.resumeCwd = s.activeCwd ?? undefined;\n this.resumeModel = s.activeModel ?? undefined;\n }\n // The socket producing the live stream is going away. If we carry a stale\n // isStreaming:true across the suspend/resume gap, the composer will wrongly\n // queue the next message as if the agent were still busy (and the queue\n // never drains because no agent_end ever arrives on the dead socket). The\n // authoritative value is re-established by session_created on rejoin.\n if (s.isStreaming) {\n this.stateStore.update(st => ({ ...st, isStreaming: false }));\n }\n this.disconnect(false);\n }\n // Resume after suspend(): reconnect while preserving the cached store, mark\n // the session as resyncing, and let onOpen rejoin the recorded session. If\n // there is no active session to rejoin, this is just a state-preserving\n // reconnect.\n resume() {\n const s = get(this.stateStore);\n if (s.connected || s.connecting)\n return;\n // Rejoin whatever session we still hold: an explicit suspend() record OR the\n // cached active session from an unsolicited drop. In BOTH cases onOpen\n // re-issues session_load, so mark resyncing here to show the affordance and\n // block sending until fresh history lands.\n // No load watchdog is armed here: connect() -> disconnect(false) would clear\n // it at once, and onOpen arms one for the rejoin it actually issues. While\n // the socket never opens (offline boot over a hydrated cache) there is no\n // load in flight to time out, so no \"timed out\" error must appear.\n if (this.resumeSessionFile || s.activeSessionFile) {\n this.stateStore.update(st => ({ ...st, resyncing: true }));\n }\n this.connect(undefined, true);\n }\n // True when suspend() recorded an active session to rejoin on the next resume.\n // Callers use this to take the resume (preserve-cache, rejoin-in-place) path\n // only when there is actually a suspended session; otherwise a plain connect()\n // is correct and avoids racing/latching the hash auto-join on a fresh load.\n hasSuspendedSession() {\n return this.resumeSessionFile !== null;\n }\n // True when the store still holds an active session to rejoin in place -- from\n // an explicit suspend() OR an unsolicited drop that left activeSessionFile set.\n // Callers use this to prefer the preserve-cache resume() path over a fresh,\n // session-wiping connect() when returning to a still-live conversation.\n hasActiveSession() {\n return this.resumeSessionFile !== null || get(this.stateStore).activeSessionFile !== null;\n }\n // Start (or restart) the stale-socket watchdog + keepalive for the current\n // socket. A half-open connection emits no 'close'/'error', so without this the\n // existing reconnect logic would never fire and the agent would hang forever.\n startLivenessWatchdog() {\n this.stopLivenessWatchdog();\n this.lastInboundAt = Date.now();\n this.lastLivenessTickAt = this.lastInboundAt;\n const sendBeat = () => {\n // Keep a healthy connection warm so the pong refreshes lastInboundAt even\n // during long, token-less model turns.\n try {\n this.ping();\n }\n catch { }\n };\n if (typeof setInterval === 'function') {\n this.heartbeatTimer = setInterval(sendBeat, WhereverClient.HEARTBEAT_MS);\n if (this.heartbeatTimer && typeof this.heartbeatTimer.unref === 'function') {\n this.heartbeatTimer.unref();\n }\n }\n const checkLiveness = () => {\n if (!this.ws)\n return;\n const now = Date.now();\n const sinceLastTick = now - this.lastLivenessTickAt;\n this.lastLivenessTickAt = now;\n // A wall-clock jump between ticks means the page was frozen: probe now\n // rather than waiting for the silence threshold. Only a trigger; the\n // probe's grace period still decides.\n if (sinceLastTick > 2 * WhereverClient.HEARTBEAT_MS) {\n this.startLivenessProbe('clock jump');\n return;\n }\n const silentFor = now - this.lastInboundAt;\n const streaming = get(this.stateStore).isStreaming;\n // Per-turn stall timeout: while a turn is in flight the heartbeat pong (and,\n // normally, tokens) should keep traffic flowing, so a shorter deadline\n // distinguishes \"model is slow\" (heartbeat still arriving -> not stale) from\n // \"transport is dead\" (heartbeat stopped). When idle, fall back to the\n // generic stale-socket threshold.\n const threshold = streaming\n ? WhereverClient.TURN_STALL_MS\n : WhereverClient.STALE_SOCKET_MS;\n if (silentFor < threshold)\n return;\n // Silent past the threshold: SUSPECT, not dead. Probe first (see\n // PROBE_GRACE_MS); the teardown happens only if the probe goes unanswered.\n this.startLivenessProbe(`no inbound frame for ${silentFor}ms ` +\n `(threshold ${threshold}ms, ${streaming ? 'mid-turn' : 'idle'})`);\n };\n if (typeof setInterval === 'function') {\n this.livenessTimer = setInterval(checkLiveness, WhereverClient.HEARTBEAT_MS);\n if (this.livenessTimer && typeof this.livenessTimer.unref === 'function') {\n this.livenessTimer.unref();\n }\n }\n }\n // The page just became visible again (visibilitychange: visible, pageshow).\n // The client has no `document` access, so the page calls this. If the current\n // socket is OPEN and watched, probe it right away instead of waiting for the\n // next tick, and reset the stale baseline so the time the page spent frozen is\n // not counted as silence (the probe decides whether the socket is alive).\n //\n // The user is looking at the page, so a return must never pay the slow paths\n // meant for an unattended client: the probe uses the short\n // VISIBLE_PROBE_GRACE_MS, a socket it condemns is replaced at once instead of\n // after the reconnect backoff, and the backoff grown while hidden is reset.\n // A socket still CONNECTING after STALLED_HANDSHAKE_MS is restarted.\n // With no socket at all this only resets the backoff: the page follows up\n // with resume() / connect(), which connect at once.\n noteVisible() {\n this.reconnectDelay = WhereverClient.MIN_RECONNECT_DELAY;\n const ws = this.ws;\n if (!ws)\n return;\n if (ws.readyState === 0 /* CONNECTING */) {\n if (Date.now() - this.socketStartedAt > WhereverClient.STALLED_HANDSHAKE_MS) {\n console.info('[wherever] handshake stalled; restarting it');\n this.reconnectNow();\n }\n return;\n }\n if (ws.readyState !== 1 /* OPEN */ || !this.livenessTimer)\n return;\n this.lastInboundAt = Date.now();\n this.lastLivenessTickAt = this.lastInboundAt;\n // Restart any pending probe: its grace may have been eaten by the freeze.\n this.cancelLivenessProbe();\n this.startLivenessProbe('page became visible', true);\n }\n // Send a ping and arm the grace check. Idempotent while a probe is pending.\n // `onReturn` marks the probe a return to the page started: short grace, and\n // an immediate reconnect if it goes unanswered.\n startLivenessProbe(reason, onReturn = false) {\n const grace = onReturn\n ? WhereverClient.VISIBLE_PROBE_GRACE_MS\n : WhereverClient.PROBE_GRACE_MS;\n if (this.probeTimer || !this.ws || typeof setTimeout !== 'function')\n return;\n const probedWs = this.ws;\n try {\n this.ping();\n }\n catch { }\n const sentAt = Date.now();\n this.probeTimer = setTimeout(() => {\n this.probeTimer = null;\n if (this.ws !== probedWs)\n return;\n // The grace check itself ran far too late: the page was frozen during\n // the grace period, so the reply may still be queued behind this timer.\n // Probe again rather than condemn the socket on frozen time.\n // Decision (beyond the task's letter): this has no retry cap. Under heavy\n // background timer throttling (timers batched to ~1/min in a long-hidden\n // tab) every grace check is late, so the verdict on a dead socket is\n // deferred until the page is visible again, where noteVisible() restarts\n // an unthrottled probe and a dead socket goes ~2 s later. Accepted: a\n // hidden page has no viewer, and a capped retry would reintroduce the\n // false teardown on thaw this probe exists to prevent.\n // A return probe whose check ran late means the page froze again, so\n // nobody is waiting on it any more: re-probe as an ordinary probe.\n if (Date.now() - sentAt > 2 * grace) {\n this.startLivenessProbe(reason);\n return;\n }\n this.tearDownStaleSocket(reason, grace, onReturn);\n }, grace);\n if (this.probeTimer && typeof this.probeTimer.unref === 'function') {\n this.probeTimer.unref();\n }\n }\n cancelLivenessProbe() {\n if (this.probeTimer) {\n clearTimeout(this.probeTimer);\n this.probeTimer = null;\n }\n }\n // The probe went unanswered: treat the socket as dead. Tearing it down\n // forcibly is what makes a half-open connection recover, since the OS never\n // produced a FIN/RST to trigger the normal close path.\n tearDownStaleSocket(reason, graceMs, immediate) {\n if (!this.ws)\n return;\n const streaming = get(this.stateStore).isStreaming;\n console.warn(`[wherever] relay connection stale: ${reason}; probe unanswered for ` +\n `${graceMs}ms; tearing down dead socket and reconnecting`);\n this.stopLivenessWatchdog();\n const deadWs = this.ws;\n this.ws = null;\n // This path bypasses onClose (the socket is no longer current), so the\n // uploads it carried must be marked waiting here.\n this.uploadsLostSocket();\n try {\n if (typeof deadWs.terminate === 'function') {\n deadWs.terminate();\n }\n else if (typeof deadWs.close === 'function') {\n deadWs.close();\n }\n }\n catch { }\n this.stateStore.update(s => ({\n ...s,\n connected: false,\n connecting: false,\n loadingSession: false,\n creatingSession: false,\n // If a turn was in flight, surface it as a recoverable error so the UI\n // shows \"the transport stalled\" rather than silently parking mid-stream.\n sessionError: streaming\n ? 'Connection to relay stalled mid-turn; reconnecting...'\n : s.sessionError,\n isStreaming: false,\n }));\n // A probe started by a return to the page has a user waiting on it: no\n // backoff, the dead socket is replaced now.\n if (immediate)\n this.reconnectNow();\n else\n this.scheduleReconnect();\n }\n stopLivenessWatchdog() {\n this.cancelLivenessProbe();\n if (this.heartbeatTimer) {\n clearInterval(this.heartbeatTimer);\n this.heartbeatTimer = null;\n }\n if (this.livenessTimer) {\n clearInterval(this.livenessTimer);\n this.livenessTimer = null;\n }\n }\n // Arm (or re-arm) the load watchdog. Called whenever a session_load is issued\n // so an unresolved load can never strand the loading UI. Idempotent: a fresh\n // load resets the deadline.\n armLoadWatchdog() {\n this.clearLoadWatchdog();\n this.loadWatchdog = setTimeout(() => {\n this.loadWatchdog = null;\n const s = get(this.stateStore);\n if (this.queuedSessionRequest?.type === 'load')\n this.queuedSessionRequest = null;\n if (!s.loadingSession && !s.resyncing)\n return;\n console.warn('[wherever] session load timed out; clearing loading state');\n this.failHeldUploads('Could not rejoin the session, so the upload was not sent');\n this.stateStore.update(st => ({\n ...st,\n loadingSession: false,\n resyncing: false,\n sessionError: st.sessionError ||\n 'Loading the session timed out. Please retry from the sidebar or reload.',\n }));\n }, WhereverClient.LOAD_WATCHDOG_MS);\n }\n // Clear the load watchdog. Called at every point the load resolves\n // (message_history, session_error, disconnect, leave).\n clearLoadWatchdog() {\n if (this.loadWatchdog) {\n clearTimeout(this.loadWatchdog);\n this.loadWatchdog = null;\n }\n }\n // Arm (or re-arm) the create watchdog. Called when session_new is issued so an\n // unanswered create can never strand the blocking \"Creating session...\"\n // overlay. On expiry we clear creatingSession and surface a recoverable error\n // instead of an endless spin that only a reload escapes.\n armCreateWatchdog() {\n this.clearCreateWatchdog();\n this.createWatchdog = setTimeout(() => {\n this.createWatchdog = null;\n const s = get(this.stateStore);\n // The user was told it failed: a later reconnect must not create it anyway.\n if (this.queuedSessionRequest?.type === 'create')\n this.queuedSessionRequest = null;\n if (!s.creatingSession)\n return;\n console.warn('[wherever] session create timed out; clearing creating state');\n this.stateStore.update(st => ({\n ...st,\n creatingSession: false,\n sessionError: st.sessionError ||\n 'Creating the session timed out. It may still be starting on the server; check the sidebar or reload.',\n }));\n }, WhereverClient.CREATE_WATCHDOG_MS);\n }\n // Clear the create watchdog. Called at every point a create resolves\n // (session_created, session_error, session_interrupted,\n // disconnect, leave).\n clearCreateWatchdog() {\n if (this.createWatchdog) {\n clearTimeout(this.createWatchdog);\n this.createWatchdog = null;\n }\n }\n scheduleReconnect() {\n if (this.reconnectTimer)\n return;\n this.reconnectTimer = setTimeout(() => {\n this.reconnectTimer = null;\n this.reconnectDelay = Math.min(this.reconnectDelay * 1.5, this.maxReconnectDelay);\n this.reconnectNow();\n }, this.reconnectDelay);\n }\n // Reconnect right away (the body of a backoff timer firing), preserving the\n // store when a session is active so onOpen rejoins it in place.\n reconnectNow() {\n if (this.reconnectTimer) {\n clearTimeout(this.reconnectTimer);\n this.reconnectTimer = null;\n }\n console.info(`[wherever] reconnecting to relay (attempt ${++this.reconnectAttempts})`);\n // If we have retried a few times and NEVER once opened the socket, this is\n // almost certainly a rejected handshake, not a flaky network. Surface a\n // concrete, actionable error (the server rejects a bad/missing token with\n // HTTP 401 during the WS upgrade, which the browser reports only as an\n // opaque 1006 close). Keep retrying, but stop looking like a mere network\n // hiccup.\n if (!this.hasEverConnected &&\n this.reconnectAttempts >= WhereverClient.HANDSHAKE_FAIL_HINT_AFTER) {\n const scheme = this.config.secure ? 'wss' : 'ws';\n this.stateStore.update(s => ({\n ...s,\n error: 'Cannot connect to the wherever server: the connection is being rejected. ' +\n 'This usually means a missing or wrong token, or a wrong host/port/scheme ' +\n `(currently ${scheme}://${this.config.host}:${this.config.port}). ` +\n 'Check the auth token and connection settings.',\n }));\n }\n // If we still hold an active session, PRESERVE the cached store across the\n // reconnect. A default connect() resets to a blank store, which wiped\n // activeSessionFile BEFORE onOpen could re-attach to it -- that is what\n // silently detached the frontend from a still-running session (frozen\n // conversation, no re-follow, not even a \"connecting\"/\"loading\" hint).\n // Preserving the store keeps the conversation on screen and lets onOpen\n // re-issue session_load from activeSessionFile.\n const preserve = !!get(this.stateStore).activeSessionFile;\n this.stateStore.update(s => ({\n ...s,\n connecting: true,\n error: 'Reconnecting...',\n }));\n this.connect(undefined, preserve);\n }\n handleMessage(msg) {\n for (const listener of this.listeners) {\n try {\n listener(msg);\n }\n catch (err) {\n console.error(\"Error in message listener:\", err);\n }\n }\n // Any message that resolves an in-flight session_load disarms the watchdog.\n // session_created arrives just before message_history; message_history is the\n // real completion, but an error/destroy/interrupt also resolves it.\n switch (msg.type) {\n case 'message_history': {\n // Only the history for the load we are actually waiting on resolves the\n // watchdog. A stale history for a superseded session (a slow session A\n // that finished after we switched to session B) must NOT disarm the\n // watchdog still guarding B's in-flight load, or a lost B reply could\n // strand the spinner. Once B's session_created has landed, sessionId is\n // B's, so a history whose sessionId differs is stale and is skipped. The\n // initial load has no sessionId yet, so its history still resolves.\n const active = get(this.stateStore).sessionId;\n if (active && msg.sessionId && msg.sessionId !== active)\n break;\n if (msg.sessionId && this.abandonedSessions.has(msg.sessionId))\n break;\n this.clearLoadWatchdog();\n break;\n }\n case 'session_error':\n case 'session_destroyed':\n case 'session_interrupted':\n this.clearLoadWatchdog();\n break;\n }\n // Any message that resolves an in-flight session_new disarms the create\n // watchdog. session_created is the success path; error/interrupt end it too.\n switch (msg.type) {\n case 'session_created':\n case 'session_error':\n case 'session_interrupted':\n this.clearCreateWatchdog();\n break;\n }\n switch (msg.type) {\n case 'connected':\n this.stateStore.update((s) => ({\n ...s,\n connected: true,\n connecting: false,\n clientId: msg.clientId,\n serverVersion: msg.serverVersion ?? null,\n piVersion: msg.piVersion ?? null,\n error: null,\n }));\n // Uploads held for unknown capabilities can now choose their protocol\n // (still subject to the rejoin hold).\n this.socketCapabilities = Array.isArray(msg.capabilities)\n ? msg.capabilities.filter((c) => typeof c === 'string')\n : [];\n this.resendPendingUploads();\n break;\n case 'connection_superseded':\n // A newer connection arrived carrying OUR clientKey, so the server is\n // retiring this socket as a superseded duplicate. Receiving this proves we\n // are alive, i.e. the key is being shared by accident (a duplicated tab\n // clones sessionStorage). Take a fresh identity BEFORE the reconnect the\n // imminent close will schedule, so the two connections stop evicting each\n // other; the owner of the key keeps it and we come back as our own viewer.\n this.clientKey = generateClientKey();\n try {\n this.config.onClientKeyChange?.(this.clientKey);\n }\n catch (err) {\n console.error('onClientKeyChange failed:', err);\n }\n break;\n case 'file_uploaded':\n this.completeUpload(msg.uploadId, { savedPath: msg.savedPath, filename: msg.filename });\n break;\n case 'file_upload_error':\n this.failUpload(msg.uploadId, msg.error);\n break;\n case 'upload_offset':\n this.handleUploadOffset(msg);\n break;\n case 'agent_start':\n if (this.agentEndTimeout) {\n clearTimeout(this.agentEndTimeout);\n this.agentEndTimeout = null;\n }\n this.stateStore.update((s) => ({ ...s, isStreaming: true }));\n break;\n case 'thinking_update':\n this.stateStore.update((s) => {\n let lastThinking = [...s.messages]\n .reverse()\n .find((m) => m.role === 'thinking' && m.isStreaming);\n if (!lastThinking) {\n const newMsg = {\n id: this.generateId(),\n role: 'thinking',\n content: msg.delta,\n timestamp: Date.now(),\n isStreaming: true,\n };\n return { ...s, messages: [...s.messages, newMsg] };\n }\n return {\n ...s,\n messages: s.messages.map((m) => m.id === lastThinking.id\n ? { ...m, content: m.content + msg.delta, isStreaming: true }\n : m),\n };\n });\n break;\n case 'message_update':\n this.stateStore.update((s) => {\n let lastAssistant = [...s.messages]\n .reverse()\n .find((m) => m.role === 'assistant' && m.isStreaming);\n if (!lastAssistant) {\n const newMsg = {\n id: this.generateId(),\n role: 'assistant',\n content: msg.delta,\n timestamp: Date.now(),\n isStreaming: true,\n };\n return { ...s, messages: [...s.messages, newMsg] };\n }\n return {\n ...s,\n messages: s.messages.map((m) => m.id === lastAssistant.id\n ? { ...m, content: m.content + msg.delta, isStreaming: true }\n : m),\n };\n });\n break;\n case 'message_ack':\n // The server accepted this outbound user message (a normal turn, or a\n // mid-stream steer queued for the next step) and handed it to the agent.\n // This is the delivery CONFIRMATION: it arrives immediately, so an\n // accepted steer is not left waiting on the message_end (role:user)\n // echo, which for a steer only comes at the next model call and can miss\n // the confirmation window (flipping the message to a false \"Retry\").\n // Content-matched to the oldest still-unconfirmed pending message.\n if (typeof msg.content === 'string') {\n this.confirmDeliveredByContent(msg.content);\n }\n break;\n case 'queue_update': {\n // The server relayed pi's current steer queue. Replace our pending-steer\n // set outright (it is the full queue): a message whose content is still\n // in this set is a queued steer that has NOT yet been injected, so the\n // UI can offer to cancel it. When a queued steer is delivered or\n // cancelled, a fresh queue_update arrives with it removed.\n const steering = Array.isArray(msg.steering)\n ? [...msg.steering]\n : [];\n this.stateStore.update((s) => ({\n ...s,\n pendingSteering: steering,\n messages: this.withRestoredQueuedMessages(s.messages, steering),\n }));\n break;\n }\n case 'message_end':\n this.stateStore.update((s) => {\n let newMessages = s.messages;\n const lastThinking = [...newMessages]\n .reverse()\n .find((m) => m.role === 'thinking' && m.isStreaming);\n if (lastThinking) {\n newMessages = newMessages.map((m) => m.id === lastThinking.id ? { ...m, isStreaming: false } : m);\n }\n const lastAssistant = [...newMessages]\n .reverse()\n .find((m) => m.role === 'assistant' && m.isStreaming);\n if (lastAssistant) {\n newMessages = newMessages.map((m) => m.id === lastAssistant.id\n ? {\n ...m,\n content: msg.content || m.content,\n isStreaming: false,\n }\n : m);\n }\n else if (msg.content) {\n // The server echoes the user's own message back once pi has appended\n // it: that is the delivery CONFIRMATION for an optimistic (unconfirmed)\n // echo. Confirm the matching pending message (flip delivery off, clear\n // its watchdog, update the persisted-pending store) instead of adding\n // a duplicate. If there was no pending match (e.g. another client sent\n // it), fall back to the existing content-dedupe.\n if (msg.role === 'user') {\n const confirmedPending = this.confirmDeliveredByContent(msg.content);\n if (confirmedPending) {\n // Re-read: confirmDeliveredByContent already updated the store.\n return get(this.stateStore);\n }\n // A steer we restored from the queue snapshot has now been injected:\n // this echo IS that bubble, so reconcile onto it (drop the marker)\n // rather than appending a duplicate. Oldest first, since pi delivers\n // the queue in order.\n const restoredQueued = newMessages.find((m) => m.role === 'user' &&\n m.restoredFromQueue &&\n m.content === msg.content);\n if (restoredQueued) {\n return {\n ...s,\n messages: newMessages.map((m) => m.id === restoredQueued.id\n ? { ...m, restoredFromQueue: undefined }\n : m),\n };\n }\n }\n // Skill invocations arrive TWICE from the server: first the RAW\n // `/skill:<name> <args>` (as the immediate message_ack, which already\n // confirmed the optimistic bubble by exact content), then the\n // EXPANDED skill block (this message_end echo). They are the same\n // invocation, so instead of appending the expanded form as a\n // duplicate, REWRITE the already-present raw bubble to the expanded\n // content so it renders as the skill chip.\n const echoIdentity = msg.role === 'user' ? skillInvocationIdentity(msg.content) : null;\n if (echoIdentity) {\n const existing = [...newMessages]\n .reverse()\n .find((m) => m.role === 'user' &&\n skillInvocationIdentity(m.content) === echoIdentity);\n if (existing) {\n if (existing.content !== msg.content) {\n newMessages = newMessages.map((m) => m.id === existing.id ? { ...m, content: msg.content } : m);\n }\n return { ...s, messages: newMessages };\n }\n }\n const lastUserMessage = [...newMessages]\n .reverse()\n .find((m) => m.role === 'user');\n const isDuplicateUserMsg = msg.role === 'user' &&\n lastUserMessage &&\n lastUserMessage.content === msg.content;\n if (!isDuplicateUserMsg) {\n newMessages = [\n ...newMessages,\n {\n id: this.generateId(),\n role: msg.role || 'assistant',\n content: msg.content,\n timestamp: Date.now(),\n isStreaming: false,\n },\n ];\n }\n }\n return { ...s, messages: newMessages };\n });\n break;\n case 'agent_end':\n if (this.agentEndTimeout) {\n clearTimeout(this.agentEndTimeout);\n this.agentEndTimeout = null;\n }\n this.agentEndTimeout = setTimeout(() => {\n const now = Date.now();\n this.stateStore.update((s) => ({\n ...s,\n isStreaming: false,\n // The run ended: any steer that was queued has been delivered (or\n // dropped), so nothing is cancellable anymore. The server also emits\n // a final queue_update, but clear here defensively in case it is\n // missed, so a stale \"Cancel\" affordance cannot linger.\n pendingSteering: [],\n messages: s.messages.map((m) => m.isStreaming\n ? {\n ...m,\n isStreaming: false,\n // A tool still streaming when the turn ends never got a\n // tool_end (e.g. the turn was aborted, or its result frame\n // was lost): its outcome is unknown. Mark it interrupted\n // (neutral), never let it fall through to a green success\n // tick, which would falsely claim it succeeded. Assistant/\n // thinking messages just stop streaming.\n ...(m.role === 'tool' ? { interrupted: true } : {}),\n // Freeze a still-running tool's duration if it never got a\n // tool_end (turn ended between steps), so \"Elapsed\" stops\n // ticking and shows the final \"Took\".\n endedAt: m.role === 'tool' && m.endedAt === undefined\n ? now\n : m.endedAt,\n }\n : m),\n }));\n this.agentEndTimeout = null;\n }, 300);\n break;\n case 'tool_start':\n if (this.agentEndTimeout) {\n clearTimeout(this.agentEndTimeout);\n this.agentEndTimeout = null;\n }\n const toolArgs = msg.args\n ? Object.entries(msg.args)\n .filter(([k, v]) => v !== undefined && v !== '')\n .map(([k, v]) => `${k}=${JSON.stringify(v)}`)\n .join(' ')\n : '';\n this.stateStore.update((s) => {\n const finalizedMessages = s.messages.map((m) => m.isStreaming && (m.role === 'assistant' || m.role === 'thinking')\n ? { ...m, isStreaming: false }\n : m);\n const startedAt = Date.now();\n const isForce = !!msg.forceCommand;\n // A `!command` / `!!command` already rendered an OPTIMISTIC bash bubble\n // locally at send time (so it appeared instantly, without waiting for\n // this server round-trip). Reconcile onto the OLDEST such pending bubble\n // instead of appending a duplicate: adopt the real startedAt and drop\n // the optimistic flag, keeping any output the user's bubble may already\n // carry empty (tool_update/tool_end will fill it). Fall back to append\n // when there is no pending optimistic bubble (agent tool call, or the\n // optimistic one was already reconciled).\n if (isForce) {\n const pending = finalizedMessages.find((m) => m.role === 'tool' && m.optimistic && m.isStreaming);\n if (pending) {\n return {\n ...s,\n messages: finalizedMessages.map((m) => m.id === pending.id\n ? {\n ...m,\n optimistic: false,\n toolName: msg.toolName,\n toolArgs,\n content: toolArgs\n ? `$ ${msg.toolName} ${toolArgs}`\n : `$ ${msg.toolName}`,\n startedAt,\n timestamp: startedAt,\n forceCommand: true,\n }\n : m),\n };\n }\n }\n const newMsg = {\n id: this.generateId(),\n role: 'tool',\n content: toolArgs\n ? `$ ${msg.toolName} ${toolArgs}`\n : `$ ${msg.toolName}`,\n timestamp: startedAt,\n isStreaming: true,\n toolName: msg.toolName,\n toolArgs: toolArgs,\n toolOutput: '',\n startedAt,\n ...(isForce ? { forceCommand: true } : {}),\n };\n return {\n ...s,\n messages: [...finalizedMessages, newMsg],\n };\n });\n break;\n case 'tool_update': {\n this.stateStore.update((s) => {\n const toolMsg = [...s.messages]\n .reverse()\n .find((m) => m.role === 'tool' &&\n m.toolName === msg.toolName &&\n m.isStreaming);\n if (toolMsg) {\n return {\n ...s,\n messages: s.messages.map((m) => m.id === toolMsg.id\n ? {\n ...m,\n content: m.content.includes('\\n')\n ? m.content + msg.delta\n : `${m.content}\\n${msg.delta}`,\n toolOutput: `${m.toolOutput}${msg.delta}`,\n }\n : m),\n };\n }\n return s;\n });\n break;\n }\n case 'tool_end': {\n const result = msg.result ? `${msg.result}` : '';\n // An abort (e.g. the web \"abort\" button killed the tool mid-run) surfaces\n // as isError with a trailing \"...aborted\" status. That is not a tool\n // FAILURE, so render it as the neutral interrupted state, not a red\n // error.\n const aborted = !!msg.isError && this.isAbortedToolResult(result);\n const effectiveIsError = !!msg.isError && !aborted;\n const toolImages = Array.isArray(msg.images) && msg.images.length > 0\n ? msg.images\n : undefined;\n this.stateStore.update((s) => {\n // Claim the OLDEST still-streaming tool of this name (FIFO). Parallel\n // tool calls share a name, so matching the LAST one (or any already\n // finalized one) would let two tool_end frames land on the SAME\n // message and leave the other tool stuck streaming: it would then be\n // finalized by the 'aborted'/agent_end sweep with no result and render\n // as a bogus green success. Preferring a streaming message means each\n // tool_end settles a distinct in-flight call. Fall back to the newest\n // non-error tool of this name only if none are still streaming.\n const toolMsg = s.messages.find((m) => m.role === 'tool' &&\n m.toolName === msg.toolName &&\n m.isStreaming) ??\n [...s.messages]\n .reverse()\n .find((m) => m.role === 'tool' &&\n m.toolName === msg.toolName &&\n !m.content.startsWith('Tool error:'));\n const endedAt = Date.now();\n if (toolMsg) {\n const errorPrefix = effectiveIsError ? 'Error: ' : '';\n return {\n ...s,\n messages: s.messages.map((m) => m.id === toolMsg.id\n ? {\n ...m,\n content: `${errorPrefix}${m.content}\\n${result}`,\n isStreaming: false,\n isError: effectiveIsError,\n interrupted: aborted,\n toolOutput: result,\n ...(toolImages ? { images: toolImages } : {}),\n endedAt,\n }\n : m),\n };\n }\n else {\n const content = effectiveIsError\n ? `Tool error: ${msg.toolName}\\n${result}`\n : `${msg.toolName}\\n${result}`;\n const message = {\n id: this.generateId(),\n role: 'tool',\n content,\n timestamp: endedAt,\n isStreaming: false,\n toolName: msg.toolName,\n toolArgs: '',\n toolOutput: result,\n ...(toolImages ? { images: toolImages } : {}),\n isError: effectiveIsError,\n interrupted: aborted,\n endedAt,\n };\n return {\n ...s,\n messages: [...s.messages, message],\n };\n }\n });\n break;\n }\n case 'aborted': {\n const abortedAt = Date.now();\n this.stateStore.update((s) => ({\n ...s,\n isStreaming: false,\n messages: s.messages.map((m) => m.isStreaming\n ? {\n ...m,\n isStreaming: false,\n // A tool still streaming when the turn is aborted was killed\n // with no result: mark it interrupted (neutral), never leave\n // it to fall through to a green success tick. Assistant/\n // thinking messages just stop streaming.\n ...(m.role === 'tool' ? { interrupted: true } : {}),\n endedAt: m.role === 'tool' && m.endedAt === undefined\n ? abortedAt\n : m.endedAt,\n }\n : m),\n }));\n break;\n }\n case 'session_created': {\n // Guard against a SUPERSEDED load. While a session was slow to load, the\n // user tapping a different session (or creating a new one) must win: a\n // late session_created for the abandoned load must not clobber what the\n // user is now looking at. A session_created is accepted only when it is\n // the reply we are actually waiting on:\n // - a session_load we issued -> matches pendingLoadFile, by FILE or by\n // ID (a load may be requested by session ID, e.g. the URL-hash deep\n // link `/#<sessionId>`; the server resolves it and always replies\n // with the resolved FILE, so a file-only comparison would reject the\n // load's own reply and hang the \"Loading session...\" spinner), OR\n // - a session_new we issued -> creatingSession is true (its target\n // file is unknown until this reply, so pendingLoadFile is null).\n // Anything else (pendingLoadFile set but a different file; or no pending\n // load/create at all yet a file different from the active one) is an\n // out-of-date or unsolicited reply and is dropped. The load watchdog was\n // already re-armed for the current target, so ignoring a stale reply\n // cannot strand the spinner.\n {\n const st = get(this.stateStore);\n const matchesPendingLoad = this.pendingLoadFile !== null &&\n (msg.sessionFile === this.pendingLoadFile ||\n msg.sessionId === this.pendingLoadFile);\n const isRequestedCreate = this.pendingLoadFile === null && st.creatingSession;\n // A load the user moved away from (e.g. the rejoin still in flight\n // when they created a new session) is never the create's reply.\n const abandoned = this.abandonedSessions.has(msg.sessionFile) ||\n this.abandonedSessions.has(msg.sessionId);\n if (!matchesPendingLoad && (!isRequestedCreate || abandoned)) {\n // Its message_history follows: drop that too, unless it is the\n // session already on screen.\n if (msg.sessionId && msg.sessionId !== st.sessionId) {\n this.abandonedSessions.add(msg.sessionId);\n }\n break;\n }\n }\n this.abandonedSessions.delete(msg.sessionFile);\n this.abandonedSessions.delete(msg.sessionId);\n // This reply matches the load we were waiting on (or the create we\n // requested): the load is resolved, so stop guarding against it.\n this.pendingLoadFile = null;\n // The server accepted the load: whatever follows (folder_missing, a\n // failed cold build) comes after an authoritative paint and must keep\n // the readable-but-blocked view, so it can no longer reject a hydration.\n this.hydratedFile = null;\n // The server has now applied this client's write verdict for the\n // session (it sets readOnly before sending session_created), so uploads\n // held across the reconnect can go out and be gated correctly.\n if (this.uploadsHeldForRejoin) {\n this.uploadsHeldForRejoin = false;\n // Release only uploads aimed at the session we actually rejoined. A\n // different session here means the user switched mid-hold; sending the\n // old target's upload now would be gated by THIS session's verdict.\n this.failUnsentUploads('The session changed before the upload could be sent', msg.sessionId);\n this.resendPendingUploads();\n }\n this.stateStore.update((s) => ({\n ...s,\n session: msg.sessionFile,\n sessionId: msg.sessionId,\n activeSessionFile: msg.sessionFile,\n activeCwd: msg.cwd,\n activeModel: msg.model,\n // Stamp the server that delivered this session (ADR 0013).\n serverKey: this.socketServerKey,\n // Its message_history follows; until then the paging state in the\n // store is not this session's.\n historyAuthoritative: false,\n isStreaming: msg.isStreaming ?? false,\n creatingSession: false,\n // The server forces read-only for sessions in a configured\n // sessions.readOnly folder (observe-only fleet view) AND, transiently,\n // for a folder conflict until the user clicks \"Continue anyway\".\n readOnly: msg.readOnly ?? false,\n // Folder-conflict warning banner. Set when attaching to a session in a\n // folder that already has another active session. `continued` starts\n // false (composer stays read-only, banner offers \"Continue anyway\");\n // `active` is refreshed by live folder_conflict updates.\n folderConflict: msg.folderConflict\n ? { cwd: msg.cwd, active: true, continued: false }\n : null,\n // The session's working folder is gone from this machine: the server\n // built no agent and refuses every send, so the composer is replaced\n // by a notice naming the path. Hard (no \"Continue anyway\"); the\n // authoritative `folder_missing` frame follows with the same cwd.\n folderMissing: msg.folderMissing ? { cwd: msg.cwd } : null,\n // The restore panel's state belongs to the folder we are leaving; the\n // authoritative `folder_missing` frame below re-creates it for this\n // session (carrying any job already running for its path).\n restore: null,\n // pending -> the history is painted now but the live agent is still\n // building; keep the composer disabled (agentPending) until\n // session_ready. A non-pending create (new session, warm reload) is\n // immediately sendable.\n agentPending: msg.pending === true,\n // Initial context-usage snapshot for the new session (null if unknown;\n // live updates arrive via 'context_usage').\n contextUsage: msg.contextUsage ?? null,\n // Reset skill-command autocomplete for the newly attached session; the\n // authoritative list is (re-)requested just below (already-live\n // session) or on session_ready (cold, still-building agent).\n skills: [],\n }));\n // A session that is ALREADY live -- a brand-new session (session_new) or\n // a warm attach -- has its agent (and resource loader) right now, but a\n // brand-new session never emits session_ready, so waiting for that alone\n // left `/skill:` autocomplete empty on a fresh session. Request the list\n // here whenever the agent is not pending; re-requesting is safe (the\n // server always replies with the full list).\n if (msg.pending !== true && msg.sessionId) {\n this.send({ type: 'skills_request', sessionId: msg.sessionId });\n }\n break;\n }\n case 'session_ready':\n // The live agent finished building for a previously-pending load. Enable\n // the composer and refresh the now-authoritative model/streaming/usage.\n this.stateStore.update((s) => {\n // Ignore a stale ready for a session we already switched away from.\n if (msg.sessionFile && s.activeSessionFile && msg.sessionFile !== s.activeSessionFile) {\n return s;\n }\n return {\n ...s,\n agentPending: false,\n activeModel: msg.model ?? s.activeModel,\n isStreaming: msg.isStreaming ?? s.isStreaming,\n contextUsage: msg.contextUsage ?? s.contextUsage,\n };\n });\n // The live agent (with its resource loader) now exists, so its skill\n // commands are resolvable. Ask for them to populate `/skill:` composer\n // autocomplete. Safe to re-request; the server replies with the full list.\n {\n const sid = get(this.stateStore).sessionId;\n if (sid)\n this.send({ type: 'skills_request', sessionId: sid });\n }\n break;\n case 'session_reloading':\n // A `/reload` was accepted (by us or another viewer): the live agent is\n // being rebuilt. Block the composer exactly like a cold load; the\n // session_ready (or session_error) that ends the reload clears it and\n // re-requests the skill list. Ignore a frame for a session we left.\n this.stateStore.update((s) => {\n if (s.sessionId && msg.sessionId && s.sessionId !== msg.sessionId)\n return s;\n return { ...s, agentPending: true };\n });\n break;\n case 'skills_list':\n // The set of `/skill:<name>` commands for the active session. Replace\n // outright; ignore a list for a session we already switched away from.\n this.stateStore.update((s) => {\n if (s.sessionId && msg.sessionId && s.sessionId !== msg.sessionId)\n return s;\n return { ...s, skills: Array.isArray(msg.skills) ? msg.skills : [] };\n });\n break;\n case 'context_usage':\n this.stateStore.update((s) => ({\n ...s,\n contextUsage: msg.contextUsage ?? null,\n }));\n break;\n case 'session_notice':\n // A non-fatal notice for the active session (e.g. a CLI took over while\n // this session was mid-turn here, discarding the in-flight tool call or\n // streaming reply). Keep the session attached; surface it as a\n // dismissible banner. Ignore a notice for a session we switched away from.\n this.stateStore.update((s) => {\n if (s.sessionId && msg.sessionId && s.sessionId !== msg.sessionId)\n return s;\n return { ...s, notice: { level: msg.level, message: msg.message } };\n });\n break;\n case 'bash_sudo_prompt':\n // A `!sudo ...` command on the server needs a password before it can\n // run. Surface a masked prompt for the active session only; ignore a\n // prompt for a session we already switched away from.\n this.stateStore.update((s) => {\n if (s.sessionId && msg.sessionId && s.sessionId !== msg.sessionId)\n return s;\n return {\n ...s,\n sudoPrompt: {\n promptId: msg.promptId,\n command: msg.command,\n sessionId: msg.sessionId,\n },\n };\n });\n break;\n case 'session_destroyed':\n if (get(this.stateStore).sessionId === msg.sessionId) {\n this.failHeldUploads('The session ended before the upload could be sent');\n }\n this.stateStore.update((s) => {\n if (s.sessionId === msg.sessionId) {\n return {\n ...s,\n messages: [],\n session: null,\n sessionId: null,\n activeSessionFile: null,\n activeCwd: null,\n activeModel: null,\n loadingSession: false,\n agentPending: false,\n folderMissing: null,\n restore: null,\n notice: null,\n sudoPrompt: null,\n };\n }\n return s;\n });\n break;\n case 'session_error': {\n // While held, the only request in flight is the rejoin: it failed, so the\n // held uploads can never be gated and sent. Fail them now rather than\n // leaving them (and every new upload) parked for the full timeout.\n // The rejoin's own errors carry no sessionId (a failed session_load or\n // its exception path); an error tagged with a session belongs to some\n // other request and must not fail the held uploads.\n if (!msg.sessionId) {\n this.failHeldUploads('Could not rejoin the session, so the upload was not sent');\n }\n // The server refused the load of a HYDRATED session outright. Only the\n // reply to the rejoin's own session_load counts: with no session\n // attached, the server's catch-all sends EVERY handler error untagged,\n // so the error must arrive while that load is still the pending one and\n // before any session_created (which clears hydratedFile).\n const rejectedHydration = !msg.sessionId &&\n this.hydratedFile !== null &&\n this.pendingLoadFile === this.hydratedFile;\n this.stateStore.update((s) => ({\n ...s,\n sessionError: msg.error,\n isStreaming: false,\n creatingSession: false,\n loadingSession: false,\n resyncing: false,\n // A failed (cold) agent build clears pending: the session stays\n // readable, but sending remains blocked (no live agent) and the error\n // is surfaced. This is the degrade-to-read-only path.\n agentPending: false,\n }));\n if (rejectedHydration)\n this.rejectHydration();\n break;\n }\n case 'folder_missing':\n // The server states, authoritatively, that this session's working folder\n // is not usable -- it does not exist on this machine, or a restore is\n // still materialising it -- and names the absolute path. No session_ready\n // is coming (no agent was built), so this is also the end of the load:\n // read-only, with an explanation. Ignore a frame for a session we already\n // switched away from.\n //\n // `job` is any restore the server is ALREADY running for that path, so a\n // reconnect or a second device paints the running clone from this one\n // frame. With no job the panel simply offers to start one; either way the\n // restore state exists from here on, so a job another device starts is\n // painted by the progress frames that follow.\n this.stateStore.update((s) => {\n if (s.sessionId && msg.sessionId && s.sessionId !== msg.sessionId)\n return s;\n return {\n ...s,\n readOnly: true,\n folderMissing: { cwd: msg.cwd },\n restore: {\n targetPath: msg.cwd,\n job: msg.job ?? null,\n joined: false,\n rejection: null,\n },\n };\n });\n break;\n case 'restore_started': {\n // The answer to OUR restore_start. `outcome: 'joined'` means a job was\n // already running for this path and we coalesced onto it, so `job.url` is\n // the url really in flight -- which the panel must show when it differs\n // from the one this client asked for, rather than pretending the edited\n // url was accepted.\n //\n // It is ALSO the answer to a `session_new` that chose to CLONE an\n // existing remote. That create has no restore state yet (no session, so\n // no folder-missing frame ever created one), so the job is ADOPTED here\n // as the create's own: the blocking \"Creating session...\" overlay gives\n // way to the same progress the restore panel renders, and the create\n // watchdog -- which fires long before a large repository finishes -- is\n // disarmed, because a watched job is no longer something to time out.\n const before = get(this.stateStore);\n if (before.creatingSession && !before.restore) {\n this.clearCreateWatchdog();\n this.stateStore.update((s) => ({\n ...s,\n creatingSession: false,\n restore: {\n targetPath: msg.targetPath,\n job: msg.job,\n joined: msg.outcome === 'joined',\n rejection: null,\n forSessionCreate: true,\n },\n }));\n break;\n }\n this.stateStore.update((s) => this.withRestore(s, msg.targetPath, (r) => ({\n ...r,\n job: msg.job,\n joined: msg.outcome === 'joined',\n rejection: null,\n })));\n break;\n }\n case 'restore_rejected':\n // Refused before anything was spawned: no job, no completion coming. Keep\n // whatever job state we had (a rejection answers OUR request, it does not\n // touch a job someone else is running) and surface the reason.\n this.stateStore.update((s) => this.withRestore(s, msg.targetPath, (r) => ({\n ...r,\n rejection: { reason: msg.reason, message: msg.message },\n })));\n break;\n case 'restore_progress':\n case 'restore_complete': {\n // Broadcast frames: the server sends them to every client whose folder\n // matches the job path, so they arrive whether or not THIS client started\n // the restore (a second device, or a reconnect mid-clone). Each carries\n // the whole job snapshot, so one frame is enough to repaint.\n //\n // The new-session clone ends differently from the panel's: there is\n // nothing to reload, so a job that SUCCEEDED hands the screen straight\n // back to the create the server is already continuing with (overlay +\n // watchdog re-armed for that last, ordinary step). A failed or cancelled\n // one ends the create; the server's session_error, carrying the mapped\n // cause, arrives beside this frame.\n const current = get(this.stateStore).restore;\n if (msg.type === 'restore_complete' &&\n current?.forSessionCreate &&\n current.targetPath === msg.targetPath) {\n const cloned = msg.job.state === 'done';\n this.stateStore.update((s) => ({\n ...s,\n restore: null,\n creatingSession: cloned,\n }));\n if (cloned)\n this.armCreateWatchdog();\n break;\n }\n this.stateStore.update((s) => this.withRestore(s, msg.targetPath, (r) => ({\n ...r,\n job: msg.job,\n rejection: null,\n })));\n break;\n }\n case 'folder_conflict':\n // Live update of whether another active session still exists in this\n // client's folder. The banner appears when a second session shows up in\n // the folder and disappears once it is gone. Applies only to the client's\n // OWN folder; a stale update for a different cwd is ignored.\n this.stateStore.update((s) => {\n if (!s.sessionId)\n return s;\n if (s.activeCwd && msg.cwd !== s.activeCwd)\n return s;\n // The server re-evaluates this client's read-only state on every\n // conflict update, so mirror it when reported. This is what releases\n // the composer once the conflict resolves (the banner alone cannot: it\n // disappears, taking its \"Continue anyway\" button with it) and what\n // keeps a hard sessions.readOnly folder locked. Older servers omit the\n // field, leaving read-only untouched as before.\n const readOnly = msg.readOnly ?? s.readOnly;\n if (!msg.active) {\n // No other session remains: fully resolved, drop the banner.\n return s.folderConflict || readOnly !== s.readOnly\n ? { ...s, folderConflict: null, readOnly }\n : s;\n }\n if (s.folderConflict) {\n // Already showing: just refresh, preserving the user's `continued`\n // choice (so we don't re-disable a composer they already enabled).\n return {\n ...s,\n readOnly,\n folderConflict: { ...s.folderConflict, cwd: msg.cwd, active: true },\n };\n }\n // A conflict appeared AFTER we were already attached (another client\n // opened a second session in our folder). Raise the banner. We were\n // sending fine until now, so treat it as already-`continued` rather\n // than yanking the composer into read-only underneath the user.\n return {\n ...s,\n readOnly,\n folderConflict: { cwd: msg.cwd, active: true, continued: true },\n };\n });\n break;\n case 'session_interrupted':\n this.stateStore.update((s) => ({\n ...s,\n isInterrupted: true,\n readOnly: true,\n messages: [],\n session: null,\n sessionId: null,\n activeSessionFile: null,\n activeCwd: null,\n activeModel: null,\n creatingSession: false,\n loadingSession: false,\n agentPending: false,\n notice: null,\n sudoPrompt: null,\n }));\n break;\n case 'message_history': {\n // Drop history for a session we already switched away from. session_created\n // sets sessionId for the load we accepted; a message_history whose\n // sessionId does not match belongs to a superseded load (a slow session A\n // that finished after the user tapped session B) and must not repaint the\n // now-active conversation. Only guard once we actually have an active\n // sessionId (the initial load has none yet until its own created lands).\n {\n const active = get(this.stateStore).sessionId;\n if (active && msg.sessionId && msg.sessionId !== active) {\n break;\n }\n // Or for a load the user abandoned, arriving before the new target's\n // own session_created (so no active sessionId guards it yet).\n if (msg.sessionId && this.abandonedSessions.has(msg.sessionId)) {\n break;\n }\n }\n // The server transcript is authoritative for what was actually persisted.\n // Reconcile it against any unconfirmed outbound messages: keep the ones\n // that ARE in history (delivered), and re-surface the ones that are NOT\n // as recoverable 'failed' items so a message a half-open socket swallowed\n // is never silently lost across a reload/resync.\n const sessionIdForPending = msg.sessionId;\n // Carry-over from the CURRENT store (this-tab sends still in flight) plus\n // anything a PREVIOUS tab persisted before a reload.\n const inFlight = get(this.stateStore).messages.filter((m) => m.role === 'user' && m.delivery !== undefined);\n const persisted = this.loadPersistedPending(sessionIdForPending);\n const candidates = [...persisted, ...inFlight];\n this.stateStore.update((s) => {\n const mapped = this.mapHistory(msg.messages, msg.sessionId, s.isStreaming);\n const totalCount = typeof msg.totalCount === 'number' ? msg.totalCount : mapped.length;\n const offset = typeof msg.offset === 'number' ? msg.offset : 0;\n const historyContents = new Set(mapped.filter((m) => m.role === 'user').map((m) => m.content));\n // Unconfirmed candidates whose content is NOT in the loaded history are\n // undelivered. De-dupe by content so two identical undelivered sends do\n // not multiply. Everything else the server persisted is already in\n // `mapped` (confirmed).\n const seen = new Set();\n const undelivered = [];\n for (const c of candidates) {\n if (historyContents.has(c.content))\n continue;\n if (seen.has(c.content))\n continue;\n seen.add(c.content);\n undelivered.push({ ...c, sessionId: sessionIdForPending, delivery: 'failed' });\n }\n return {\n ...s,\n messages: [...mapped, ...undelivered],\n historyTotalCount: totalCount,\n historyOffset: offset,\n historyAuthoritative: true,\n loadingMoreHistory: false,\n loadingSession: false,\n resyncing: false,\n };\n });\n // Clear watchdogs for anything now confirmed, and rewrite the persisted\n // store to exactly the still-undelivered set.\n for (const c of candidates)\n this.clearConfirm(c.id);\n this.persistPending(sessionIdForPending);\n break;\n }\n case 'message_history_prepend':\n this.stateStore.update((s) => {\n // Older window prepended ahead of currently-loaded messages. No\n // streaming-tail handling here (those messages are historical).\n const older = this.mapHistory(msg.messages, msg.sessionId, false);\n const offset = typeof msg.offset === 'number' ? msg.offset : 0;\n if (older.length === 0) {\n return { ...s, loadingMoreHistory: false, historyOffset: offset };\n }\n return {\n ...s,\n messages: [...older, ...s.messages],\n historyOffset: offset,\n loadingMoreHistory: false,\n };\n });\n break;\n case 'model_changed':\n this.stateStore.update((s) => ({\n ...s,\n activeModel: msg.model,\n }));\n break;\n }\n }\n /**\n * True when an errored tool result is the product of a USER ABORT (e.g. the\n * web \"abort\" button killed a running tool), rather than a genuine tool\n * failure. The pi tools append a trailing status line on abort (\"Command\n * aborted\" for bash, \"Operation aborted\" for edit/write, bare \"aborted\" for a\n * pre-execution abort). We match that trailing status so the UI can render a\n * neutral \"interrupted\" state instead of a red error: you cancelling a tool is\n * not the tool failing. Only meaningful when isError is already true; matched\n * as the LAST non-empty line to avoid false positives from command output that\n * merely contains the word \"aborted\".\n */\n isAbortedToolResult(result) {\n if (!result)\n return false;\n const lines = result.trimEnd().split('\\n');\n const last = (lines[lines.length - 1] || '').trim();\n return /^(command|operation)?\\s*aborted$/i.test(last);\n }\n /**\n * Map a server `HistoryMessage[]` window into UI `ChatMessage[]`. When\n * `applyStreamingTail` is true, the last assistant/thinking message and any\n * unmatched tool-call placeholders are marked streaming (used only for the\n * live tail window, not for prepended older history).\n */\n mapHistory(rawMessages, sessionId, applyStreamingTail) {\n const mapped = [];\n // A tool_call is rendered IN PLACE, at its position in the stream, as a tool\n // message that is initially result-less. Its matching tool_result fills it\n // in later. We track the still-open calls per tool name as indices into\n // `mapped`, so a call that never receives a result simply stays where it was\n // issued (correctly marked interrupted below) instead of being hoisted to\n // the very end of the transcript. The end-hoisting was the bug: dangling\n // tool calls from EARLIER in the conversation (e.g. an interrupted long-\n // running bash, later superseded by a new user turn) would all pile up as a\n // \"series of aborted tool calls\" AFTER the latest reply, even though the CLI\n // shows them inline where they happened.\n //\n // Matching is by tool-call id when present (the server forwards it on both\n // tool_call and tool_result), which pairs a result to its EXACT call even\n // when same-named calls interleave with some left dangling. When the id is\n // absent (older sessions, or the synthesized bashExecution pair) we fall\n // back to oldest-open-first per tool name.\n const openCalls = {};\n const openById = {};\n // Drop a resolved call's index from the name-FIFO list so an id match and a\n // later name-fallback can never both consume the same call.\n const removeFromNameQueue = (tName, idx) => {\n const q = openCalls[tName];\n if (!q)\n return;\n const at = q.indexOf(idx);\n if (at !== -1)\n q.splice(at, 1);\n };\n for (const m of rawMessages) {\n if (m.role === 'tool_call') {\n const tName = m.toolName || 'unknown';\n const args = m.content || '';\n const idx = mapped.length;\n mapped.push({\n id: this.generateId(),\n role: 'tool',\n content: args ? `$ ${tName} ${args}` : `$ ${tName}`,\n timestamp: m.timestamp,\n // No result yet. Marked as interrupted below if it stays unmatched;\n // the streaming tail promotes the last one back to streaming.\n isStreaming: false,\n toolName: tName,\n toolArgs: args,\n toolOutput: '',\n sessionId,\n // Keep the start so a matched result (or a still-running streaming\n // tail) can show a coherent duration / \"Elapsed\".\n ...(Number.isFinite(m.timestamp) ? { startedAt: m.timestamp } : {}),\n // Carry the force-command marker from history so a `!command` bash\n // tool call auto-expands on reload just like it does live.\n ...(m.forceCommand ? { forceCommand: true } : {}),\n });\n if (!openCalls[tName])\n openCalls[tName] = [];\n openCalls[tName].push(idx);\n if (typeof m.toolCallId === 'string' && m.toolCallId) {\n openById[m.toolCallId] = idx;\n }\n }\n else if (m.role === 'tool_result') {\n const tName = m.toolName || 'unknown';\n // Prefer an exact id match; else fill the OLDEST still-open call of this\n // name (FIFO), mirroring how parallel same-named calls resolve in order.\n let callIdx;\n if (typeof m.toolCallId === 'string' &&\n m.toolCallId &&\n openById[m.toolCallId] !== undefined) {\n callIdx = openById[m.toolCallId];\n delete openById[m.toolCallId];\n removeFromNameQueue(tName, callIdx);\n }\n else if (openCalls[tName] && openCalls[tName].length > 0) {\n callIdx = openCalls[tName].shift();\n // Keep openById consistent if this call had also registered an id.\n for (const [id, i] of Object.entries(openById)) {\n if (i === callIdx)\n delete openById[id];\n }\n }\n const isError = m.isError && !this.isAbortedToolResult(m.content);\n const interrupted = !!m.isError && this.isAbortedToolResult(m.content);\n if (callIdx !== undefined) {\n const call = mapped[callIdx];\n const tArgs = call.toolArgs || '';\n const startedAt = call.startedAt;\n mapped[callIdx] = {\n ...call,\n content: tArgs\n ? `$ ${tName} ${tArgs}\\n${m.content}`\n : `$ ${tName}\\n${m.content}`,\n isStreaming: false,\n toolOutput: m.content,\n ...(Array.isArray(m.images) && m.images.length > 0\n ? { images: m.images }\n : {}),\n // A user abort surfaces as an errored result with a trailing\n // \"...aborted\" status. Render it as interrupted (neutral), not a red\n // error: aborting a tool is not the tool failing.\n isError,\n interrupted,\n timestamp: m.timestamp,\n // Duration only when both timestamps are finite and coherent\n // (end >= start); otherwise leave unset rather than show a bogus one.\n ...(startedAt !== undefined &&\n Number.isFinite(startedAt) &&\n Number.isFinite(m.timestamp) &&\n m.timestamp >= startedAt\n ? { endedAt: m.timestamp }\n : {}),\n };\n }\n else {\n // A result with no preceding open call (shouldn't normally happen).\n // Render it in place as a standalone tool message so nothing is lost.\n mapped.push({\n id: this.generateId(),\n role: 'tool',\n content: `$ ${tName}\\n${m.content}`,\n timestamp: m.timestamp,\n isStreaming: false,\n toolName: tName,\n toolArgs: '',\n toolOutput: m.content,\n ...(Array.isArray(m.images) && m.images.length > 0\n ? { images: m.images }\n : {}),\n isError,\n interrupted,\n sessionId,\n });\n }\n }\n else {\n mapped.push({\n id: this.generateId(),\n role: m.role,\n content: m.content,\n timestamp: m.timestamp,\n isStreaming: false,\n toolName: m.toolName,\n sessionId,\n // Carry the source entry id (set on user messages by the server) so the\n // UI can offer \"Fork from here\" on each user message.\n ...(typeof m.entryId === 'string' && m.entryId ? { entryId: m.entryId } : {}),\n });\n }\n }\n // Any call still open (issued a toolCall, never got a tool_result) is FROZEN\n // in place with no result. Meaning depends on context:\n // - streaming tail (applyStreamingTail): only the MOST RECENT open call is\n // plausibly still running; keep it streaming so the UI ticks \"Elapsed\".\n // Earlier open calls in the same window are already superseded and are\n // interrupted.\n // - otherwise: its outcome is unknown (e.g. a CLI takeover / interruption\n // killed it mid-run), so mark it `interrupted` for a neutral \"no result\"\n // state instead of a bogus green success tick.\n const allOpen = [];\n for (const idxs of Object.values(openCalls))\n allOpen.push(...idxs);\n allOpen.sort((a, b) => a - b);\n const lastOpenIdx = applyStreamingTail && allOpen.length > 0\n ? allOpen[allOpen.length - 1]\n : -1;\n for (const idx of allOpen) {\n if (idx === lastOpenIdx) {\n mapped[idx] = { ...mapped[idx], isStreaming: true };\n }\n else {\n mapped[idx] = { ...mapped[idx], interrupted: true };\n }\n }\n if (applyStreamingTail && mapped.length > 0) {\n const lastIndex = mapped.length - 1;\n const lastMsg = mapped[lastIndex];\n if (lastMsg.role === 'assistant' || lastMsg.role === 'thinking') {\n mapped[lastIndex] = {\n ...lastMsg,\n isStreaming: true,\n };\n }\n }\n return mapped;\n }\n /**\n * Request the previous window of older history for the active session.\n * No-op when there is nothing older to load or a request is already in\n * flight.\n */\n loadMoreHistory() {\n const s = get(this.stateStore);\n if (!s.sessionId)\n return;\n // The offset may come from the cache or a dropped socket: never page from\n // it until the server's own history has replaced it.\n if (!s.historyAuthoritative)\n return;\n if (s.loadingMoreHistory)\n return;\n if (s.historyOffset <= 0)\n return;\n this.stateStore.update((st) => ({\n ...st,\n loadingMoreHistory: true,\n }));\n this.send({\n type: 'history_load_more',\n sessionId: s.sessionId,\n beforeOffset: s.historyOffset,\n });\n }\n // Returns true only when the frame was actually handed to an OPEN socket.\n // A non-OPEN (null / CONNECTING / CLOSING / half-open) socket silently\n // dropping the frame is what made messages vanish: they rendered locally but\n // never reached the server, so they were gone after a reload. Callers that\n // carry user intent (sendMessage) must check this and surface the failure.\n send(msg) {\n if (this.ws && this.ws.readyState === 1 /* OPEN */) {\n try {\n this.ws.send(JSON.stringify(msg));\n return true;\n }\n catch {\n return false;\n }\n }\n return false;\n }\n // Build the outbound `message` frame. The optional conversationMode flag is the\n // per-turn spoken-conversation SIGNAL: it is a FIELD on this existing payload\n // (no new message type), and it is OMITTED when off so a normal send is\n // byte-identical to before and an older server simply ignores it.\n messageFrame(text, sessionId, options) {\n return {\n type: 'message',\n message: text,\n sessionId,\n ...(options?.conversationMode ? { conversationMode: true } : {}),\n };\n }\n // Returns true only if the message actually went out over an OPEN socket.\n // Callers MUST use the return value to decide whether to clear the input:\n // clearing on a false return is what loses the user's text on a dropped send.\n //\n // `options.conversationMode` tells the agent, for this turn only, that a spoken\n // conversation is active (so it also emits a short `say` reply). The caller owns\n // that decision: the web app stamps it from its conversation-mode knobs.\n sendMessage(text, options) {\n const s = get(this.stateStore);\n if (!s.sessionId)\n return false;\n // The session's transcript is loaded but its live agent is still building\n // (cold, fast-first load). Reading is fine; sending is not possible yet, and\n // a message sent now would have no agent to receive it. Surface a clear,\n // recoverable hint and keep the text (the composer is disabled anyway, but a\n // programmatic caller could still reach here).\n if (s.agentPending) {\n this.stateStore.update((st) => ({\n ...st,\n sessionError: st.sessionError ?? 'Preparing the session agent; please wait a moment, then resend.',\n }));\n return false;\n }\n // Guard against sending on a dead / half-open socket. getIsConnected()\n // checks the real readyState (not the store's connected flag, which can lag\n // a half-open socket the liveness watchdog has not reaped yet). Sending here\n // would be silently dropped, the message would appear locally, then vanish\n // on reload. Surface a recoverable error and make sure we are reconnecting\n // instead of optimistically rendering a message that never left.\n if (!this.getIsConnected()) {\n this.stateStore.update((st) => ({\n ...st,\n sessionError: 'Not connected to the relay; your message was not sent. Reconnecting, then please resend.',\n }));\n if (!this.ws && !this.reconnectTimer) {\n this.scheduleReconnect();\n }\n return false;\n }\n // Send first; only commit the optimistic local echo + clear the error once\n // the frame is confirmed handed to an OPEN socket. This way a send that\n // fails (a narrow race between the readyState check and send) leaves no\n // phantom local message and keeps the input intact for the caller to retry.\n const ok = this.send(this.messageFrame(text, s.sessionId, options));\n if (!ok) {\n this.stateStore.update((st) => ({\n ...st,\n sessionError: 'Message failed to send (connection dropped). Please resend once reconnected.',\n }));\n return false;\n }\n // A `!command` / `!!command` is intercepted by the server and run as a bash\n // tool call, NOT delivered to the agent. The server never echoes it back as a\n // user message, and the bash tool_start/tool_end events are the real, durable\n // feedback (and are recorded in history). So do NOT add any local USER echo\n // for it: a user bubble here would be a transient duplicate that vanishes on\n // reload (bash runs are not part of the user-message transcript) and, if\n // delivery-tracked, would wrongly time out into a retry/discard banner.\n //\n // We DO, however, render an optimistic bash TOOL bubble immediately so the\n // command shows up instantly instead of only after the server round-trip\n // (client -> server -> tool_start -> client). It is tagged `optimistic` so\n // the real `tool_start` reconciles onto it (no duplicate) and is NOT\n // delivery-tracked (no watchdog/banner). Skip the optimistic bubble for\n // `!sudo ...`: the server defers those behind a password prompt and does not\n // emit `tool_start` until the password arrives, so a pending bubble would sit\n // there streaming (and never reconcile if the prompt is cancelled).\n if (text.trimStart().startsWith('!')) {\n const raw = text.trimStart();\n const isExcluded = raw.startsWith('!!');\n const command = (isExcluded ? raw.slice(2) : raw.slice(1)).trim();\n const isSudo = /^sudo(\\s|$)/.test(command);\n if (command && !isSudo) {\n const toolArgs = `command=${JSON.stringify(command)}`;\n const startedAt = Date.now();\n const optimisticTool = {\n id: this.generateId(),\n role: 'tool',\n content: `$ bash ${toolArgs}`,\n timestamp: startedAt,\n isStreaming: true,\n toolName: 'bash',\n toolArgs,\n toolOutput: '',\n startedAt,\n forceCommand: true,\n optimistic: true,\n };\n this.stateStore.update((st) => ({\n ...st,\n sessionError: null,\n messages: [...st.messages, optimisticTool],\n }));\n return true;\n }\n this.stateStore.update((st) => ({ ...st, sessionError: null }));\n return true;\n }\n // The frame was handed to an OPEN socket, but that is NOT proof of delivery:\n // a half-open TCP connection accepts send() (buffers locally, no throw) yet\n // the bytes never reach the server. So commit the echo as delivery:'sending'\n // (unconfirmed) and arm a watchdog + persist it, so it is recoverable on\n // reload and flips to 'failed' if the server never echoes it back.\n const message = {\n id: this.generateId(),\n role: 'user',\n content: text,\n timestamp: Date.now(),\n isStreaming: false,\n sessionId: s.sessionId,\n delivery: 'sending',\n };\n this.stateStore.update((st) => ({\n ...st,\n sessionError: null,\n messages: [...st.messages, message],\n }));\n this.armConfirm(message.id);\n this.persistPending(s.sessionId);\n return true;\n }\n // Re-materialize queued steers the message list does not have. A queued\n // message lives ONLY in the agent's memory until pi injects it at the next\n // step: it is not in the session file, so message_history cannot contain it.\n // On attach (a reload, or a second device) the server sends the queue as a\n // snapshot; without this the text would be invisible until it was delivered,\n // even though it was still going to be sent. Any queued entry with no matching\n // user message is appended so the UI can render it with the \"Queued\" badge and\n // the session-level cancel.\n //\n // Matching is by CONTENT, because the queue is a list of strings (pi exposes\n // no per-entry id). Occurrences are COUNTED, so a text queued twice restores\n // two bubbles, and a locally-sent (optimistic) steer already on screen is not\n // duplicated by the snapshot that follows it.\n withRestoredQueuedMessages(messages, steering) {\n if (steering.length === 0)\n return messages;\n const have = new Map();\n for (const m of messages) {\n if (m.role !== 'user')\n continue;\n have.set(m.content, (have.get(m.content) ?? 0) + 1);\n }\n const restored = [];\n for (const text of steering) {\n const remaining = have.get(text) ?? 0;\n if (remaining > 0) {\n have.set(text, remaining - 1);\n continue;\n }\n restored.push({\n id: this.generateId(),\n role: 'user',\n content: text,\n timestamp: Date.now(),\n isStreaming: false,\n restoredFromQueue: true,\n // NOT delivery-tracked: the server already holds this message, so it is\n // delivered as far as we are concerned. Tagging it pending would arm a\n // confirmation watchdog and wrongly offer \"Retry\" for a message that is\n // queued and will be sent.\n });\n }\n return restored.length > 0 ? [...messages, ...restored] : messages;\n }\n // ==========================================================================\n // Outbound-message delivery confirmation + recovery.\n //\n // An optimistic user echo is unconfirmed until the server echoes it back. This\n // machinery makes an unconfirmed message survive a reload and surface a retry\n // affordance instead of being silently lost when a half-open socket swallowed\n // the frame.\n // ==========================================================================\n pendingKey(sessionId) {\n return WhereverClient.PENDING_PREFIX + sessionId;\n }\n // Persist the current session's still-unconfirmed (delivery-tagged) user\n // messages so a reload can recover them. Cleared to empty when none remain.\n persistPending(sessionId) {\n if (!sessionId || typeof localStorage === 'undefined')\n return;\n const pending = get(this.stateStore).messages.filter((m) => m.role === 'user' && m.delivery !== undefined);\n try {\n if (pending.length === 0) {\n localStorage.removeItem(this.pendingKey(sessionId));\n }\n else {\n localStorage.setItem(this.pendingKey(sessionId), JSON.stringify(pending.map((m) => ({\n id: m.id,\n content: m.content,\n timestamp: m.timestamp,\n // Persist as 'failed': a reload cannot know if it ever landed, so\n // it must be presented as needs-attention, never as delivered.\n delivery: 'failed',\n }))));\n }\n }\n catch { }\n }\n // Load persisted unconfirmed messages for a session (used on load/resync to\n // re-surface anything a previous tab left in limbo).\n loadPersistedPending(sessionId) {\n if (typeof localStorage === 'undefined')\n return [];\n try {\n const raw = localStorage.getItem(this.pendingKey(sessionId));\n if (!raw)\n return [];\n const arr = JSON.parse(raw);\n if (!Array.isArray(arr))\n return [];\n return arr\n .filter((m) => m && typeof m.content === 'string')\n .map((m) => ({\n id: typeof m.id === 'string' ? m.id : this.generateId(),\n role: 'user',\n content: m.content,\n timestamp: typeof m.timestamp === 'number' ? m.timestamp : Date.now(),\n isStreaming: false,\n sessionId,\n delivery: 'failed',\n }));\n }\n catch {\n return [];\n }\n }\n armConfirm(messageId) {\n this.clearConfirm(messageId);\n if (typeof setTimeout !== 'function')\n return;\n const timer = setTimeout(() => {\n this.confirmTimers.delete(messageId);\n // Still unconfirmed after the window: mark it failed so the UI offers a\n // retry. Delivery is genuinely uncertain (a half-open socket may have\n // eaten it), so we do NOT auto-resend: that risks a duplicate. The user\n // decides.\n let sessionId = null;\n this.stateStore.update((st) => {\n const m = st.messages.find((x) => x.id === messageId);\n if (!m || m.delivery !== 'sending')\n return st;\n sessionId = st.sessionId;\n return {\n ...st,\n messages: st.messages.map((x) => x.id === messageId ? { ...x, delivery: 'failed' } : x),\n };\n });\n if (sessionId)\n this.persistPending(sessionId);\n }, WhereverClient.CONFIRM_MS);\n if (timer && typeof timer.unref === 'function') {\n timer.unref();\n }\n this.confirmTimers.set(messageId, timer);\n }\n clearConfirm(messageId) {\n const t = this.confirmTimers.get(messageId);\n if (t) {\n clearTimeout(t);\n this.confirmTimers.delete(messageId);\n }\n }\n // Mark the oldest still-unconfirmed user message with this content as\n // delivered (the server echoed it back). Content-matched because the server\n // echo carries no client message id. Returns true if one was confirmed.\n //\n // Skill invocations need a looser match: the client optimistically echoes the\n // RAW `/skill:<name> <args>`, but the server echoes the EXPANDED skill block\n // (pi inlines the skill body before storing/echoing). Exact-content matching\n // would miss, leaving the raw bubble orphaned as \"failed\" AND appending the\n // expanded echo as a duplicate. So fall back to matching a pending message\n // whose skill-invocation IDENTITY (name + args) equals the echo's, and REWRITE\n // its content to the confirmed (expanded) form so it renders as the skill chip\n // and the server's own echo is then deduped against it.\n confirmDeliveredByContent(content) {\n let confirmedId = null;\n let sessionId = null;\n const echoIdentity = skillInvocationIdentity(content);\n this.stateStore.update((st) => {\n let target = st.messages.find((m) => m.role === 'user' && m.delivery !== undefined && m.content === content);\n // Skill-identity fallback: match the RAW optimistic echo to this EXPANDED\n // server echo when they are the same invocation.\n if (!target && echoIdentity) {\n target = st.messages.find((m) => m.role === 'user' &&\n m.delivery !== undefined &&\n skillInvocationIdentity(m.content) === echoIdentity);\n }\n if (!target)\n return st;\n confirmedId = target.id;\n sessionId = st.sessionId;\n return {\n ...st,\n messages: st.messages.map((m) => m.id === target.id\n ? {\n ...m,\n delivery: undefined,\n // Adopt the expanded content so the skill chip renders (and the\n // server's message_end echo dedupes against it instead of\n // appending a second bubble).\n ...(echoIdentity ? { content } : {}),\n }\n : m),\n };\n });\n if (confirmedId) {\n this.clearConfirm(confirmedId);\n this.persistPending(sessionId);\n return true;\n }\n return false;\n }\n // Retry a failed (or sending) outbound message: re-send its frame and re-arm\n // confirmation. Returns false if it could not be handed to an OPEN socket (the\n // message stays failed/recoverable).\n //\n // A resend starts a FRESH turn, so the caller re-stamps the per-turn\n // conversation-mode signal from the knobs as they are NOW (the mode may have\n // been flipped since the original send).\n resendMessage(messageId, options) {\n const s = get(this.stateStore);\n const m = s.messages.find((x) => x.id === messageId && x.role === 'user');\n if (!m || !s.sessionId)\n return false;\n if (!this.getIsConnected()) {\n if (!this.ws && !this.reconnectTimer)\n this.scheduleReconnect();\n return false;\n }\n const ok = this.send(this.messageFrame(m.content, s.sessionId, options));\n if (!ok)\n return false;\n this.stateStore.update((st) => ({\n ...st,\n sessionError: null,\n messages: st.messages.map((x) => x.id === messageId ? { ...x, delivery: 'sending', timestamp: Date.now() } : x),\n }));\n this.armConfirm(messageId);\n this.persistPending(s.sessionId);\n return true;\n }\n // Drop a failed outbound message the user chooses not to resend. Removes it\n // from the transcript and from the persisted-pending store.\n discardMessage(messageId) {\n let sessionId = null;\n this.clearConfirm(messageId);\n this.stateStore.update((st) => {\n sessionId = st.sessionId;\n return {\n ...st,\n messages: st.messages.filter((m) => m.id !== messageId),\n };\n });\n if (sessionId)\n this.persistPending(sessionId);\n }\n abort() {\n const s = get(this.stateStore);\n if (!s.sessionId)\n return;\n this.send({ type: 'abort', sessionId: s.sessionId });\n }\n // The web `/reload`: ask the server to rebuild the active session's agent so\n // it re-reads settings, extensions, skills, prompts and context files. Nothing\n // is changed locally: the server answers session_reloading (block the\n // composer), then session_ready, or a session_notice when it refuses (the\n // agent is busy, a CLI bridge owns the session, read-only).\n reloadResources() {\n const s = get(this.stateStore);\n if (!s.sessionId)\n return;\n this.send({ type: 'session_reload', sessionId: s.sessionId });\n }\n // Cancel the queued mid-stream steer messages for the active session without\n // aborting the in-flight turn. Optimistically clears our local pending-steer\n // set so the \"Cancel\" affordance disappears immediately; the server's fresh\n // queue_update (after clearQueue) reconciles the authoritative state.\n cancelSteer() {\n const s = get(this.stateStore);\n if (!s.sessionId)\n return;\n this.send({ type: 'cancel_steer', sessionId: s.sessionId });\n this.stateStore.update((st) => ({ ...st, pendingSteering: [] }));\n }\n /**\n * Apply `mutate` to the restore state for `targetPath`, or ignore the frame.\n *\n * Restore frames are addressed by PATH (the server's job key) rather than by\n * session id, because the server derives who gets them from a path match. This\n * is where a frame for a folder this client is no longer looking at is dropped\n * -- the one still in flight when the user switched sessions.\n */\n withRestore(s, targetPath, mutate) {\n const current = s.restore;\n if (!current || current.targetPath !== targetPath)\n return s;\n return { ...s, restore: mutate(current) };\n }\n /**\n * Paint a conversation from the web's on-device cache before the socket is up\n * (ADR 0013), so a reload after the OS killed the PWA shows it at once. Call\n * it, then `connect(cfg, true)`: onOpen's normal rejoin issues the\n * `session_load` and its `message_history` replaces the cached messages.\n *\n * A no-op unless the client holds nothing that could be clobbered: no active\n * session, no load in flight, not connected. The painted session is\n * `resyncing` (sending blocked) and NOT `historyAuthoritative`. `agentPending`,\n * `folderConflict`, `sudoPrompt` and `readOnly` stay at their defaults: they\n * are verdicts the server re-states on the rejoin. `pendingLoadFile` is NOT\n * set here (the rejoin sets it when it actually sends the load).\n *\n * Delivery-tagged user messages in the snapshot are dropped: undelivered\n * outbound messages are recovered only from localStorage on the history\n * reply (`loadPersistedPending`), so a cached copy would double-surface them.\n */\n hydrateCachedSession(snapshot) {\n const s = get(this.stateStore);\n if (s.activeSessionFile || this.pendingLoadFile !== null || s.connected)\n return;\n const messages = snapshot.messages.filter((m) => !(m.role === 'user' && m.delivery !== undefined));\n this.hydratedFile = snapshot.sessionFile;\n this.stateStore.update((st) => ({\n ...st,\n session: snapshot.sessionFile,\n sessionId: snapshot.sessionId,\n activeSessionFile: snapshot.sessionFile,\n activeCwd: snapshot.cwd,\n activeModel: snapshot.model,\n messages,\n historyTotalCount: snapshot.historyTotalCount ?? messages.length,\n historyOffset: snapshot.historyOffset ?? 0,\n historyAuthoritative: false,\n resyncing: true,\n isStreaming: false,\n serverKey: snapshot.serverKey ?? serverKey(this.config),\n }));\n }\n // The server refused the hydrated session's load: clear the cached view (the\n // session_error reducer already surfaced the error) and tell the listeners,\n // so the web evicts the record and drops the hash. Synthesized locally; it is\n // never a server frame.\n rejectHydration() {\n const sessionId = get(this.stateStore).sessionId;\n this.hydratedFile = null;\n this.pendingLoadFile = null;\n this.stateStore.update((s) => ({\n ...s,\n messages: [],\n session: null,\n sessionId: null,\n activeSessionFile: null,\n activeCwd: null,\n activeModel: null,\n historyTotalCount: 0,\n historyOffset: 0,\n historyAuthoritative: false,\n serverKey: null,\n resyncing: false,\n }));\n if (!sessionId)\n return;\n const event = { type: 'hydration_rejected', sessionId };\n for (const listener of this.listeners) {\n try {\n listener(event);\n }\n catch (err) {\n console.error(\"Error in message listener:\", err);\n }\n }\n }\n joinSession(sessionFile, cwd, model) {\n this.stateStore.update((s) => ({\n ...s,\n folderConflict: null,\n // Both folder verdicts belong to the session being left; the load we are\n // starting re-states its own (the server re-checks on every load).\n folderMissing: null,\n restore: null,\n sessionError: null,\n loadingSession: true,\n agentPending: false,\n }));\n this.abandonPendingLoad(sessionFile);\n this.pendingLoadFile = sessionFile;\n this.sendSessionLoad(sessionFile, cwd, model);\n this.armLoadWatchdog();\n }\n // The in-flight load (if any) is being superseded by a new request: remember\n // it so its late reply is dropped (see abandonedSessions). `next` is the load\n // replacing it, which must not be dropped even if it was abandoned before.\n abandonPendingLoad(next, { keepShownSession = false } = {}) {\n if (this.pendingLoadFile && this.pendingLoadFile !== next) {\n this.abandonedSessions.add(this.pendingLoadFile);\n }\n // A load whose session_created was accepted but whose message_history is\n // still arriving (a rejoin's multi-MB history can take seconds, exactly\n // while the user is most likely to tap away): pendingLoadFile is already\n // null, so remember its sessionId instead, or its history would paint over\n // the next target and disarm that target's watchdog.\n // keepShownSession: a bare create (composer `/new`) keeps showing the\n // current session until the new one's session_created, after which the\n // active-id guard drops its history anyway; abandoning it here would only\n // blank it if the create then failed.\n const s = get(this.stateStore);\n if (!keepShownSession &&\n s.sessionId &&\n !s.historyAuthoritative &&\n s.activeSessionFile !== next &&\n s.sessionId !== next) {\n this.abandonedSessions.add(s.sessionId);\n }\n if (next)\n this.abandonedSessions.delete(next);\n }\n // Send a user-requested session_load, or queue it for the next open socket\n // when there is none (see queuedSessionRequest).\n sendSessionLoad(sessionFile, cwd, model) {\n const sent = this.send({ type: 'session_load', sessionFile, cwd, model });\n this.queuedSessionRequest = sent ? null : { type: 'load', sessionFile, cwd, model };\n }\n // Switch from the currently-active session (if any) straight to another one in\n // a single, atomic step. Leaving + loading used to be done by the UI as two\n // calls separated by a 100ms setTimeout; that gap could strand the loading\n // state (a tap landing mid-switch, a leave whose load never fired) and leave\n // the \"Loading session...\" spinner hanging with an open sidebar. Doing both\n // here, synchronously, means there is never an in-between state and the\n // watchdog is always (re)armed for the new load, so a superseded or lost load\n // can never strand the UI: the latest tap always wins.\n switchSession(sessionFile, cwd, model) {\n const s = get(this.stateStore);\n // Tapping the already-active session is a no-op (don't tear it down just to\n // reload the same history).\n if (s.activeSessionFile === sessionFile && !s.loadingSession && !s.resyncing) {\n return;\n }\n this.abandonUnsentUploads();\n if (s.sessionId) {\n this.send({ type: 'session_leave', sessionId: s.sessionId });\n }\n // Before the reset below, which forgets the session being left.\n this.abandonPendingLoad(sessionFile);\n // Reset to a clean loading state for the target session in one update so the\n // old conversation clears immediately and the spinner reflects the new load.\n this.stateStore.update((st) => ({\n ...st,\n messages: [],\n session: null,\n sessionId: null,\n activeSessionFile: null,\n activeCwd: null,\n activeModel: null,\n readOnly: false,\n folderConflict: null,\n folderMissing: null,\n restore: null,\n sessionError: null,\n notice: null,\n sudoPrompt: null,\n creatingSession: false,\n resyncing: false,\n agentPending: false,\n contextUsage: null,\n pendingSteering: [],\n loadingSession: true,\n }));\n this.resumeSessionFile = null;\n this.resumeCwd = undefined;\n this.resumeModel = undefined;\n this.hydratedFile = null;\n // Switching supersedes any in-flight create; disarm its watchdog so it can't\n // later fire against the newly loaded session.\n this.clearCreateWatchdog();\n this.pendingLoadFile = sessionFile;\n this.sendSessionLoad(sessionFile, cwd, model);\n this.armLoadWatchdog();\n }\n // Fork the given session at a specific user-message entry, mirroring pi's\n // `/fork` (position 'before'). The server creates a new branched session file\n // and replies with `session_forked` (carrying the new file path + the chosen\n // message's text). The app layer listens for that reply, switches to the new\n // session, and pre-fills the composer. This method only issues the request;\n // it does not itself change the active session.\n forkSession(sessionId, entryId) {\n if (!sessionId || !entryId)\n return false;\n return this.send({ type: 'session_fork', sessionId, entryId });\n }\n createSession(cwd, model, gitInit, createRemote, repoVisibility, cloneRemote) {\n this.abandonUnsentUploads();\n this.stateStore.update((s) => ({\n ...s,\n folderConflict: null,\n // Creating a session creates its folder, so no missing-folder lock can\n // survive into it.\n folderMissing: null,\n restore: null,\n sessionError: null,\n creatingSession: true,\n loadingSession: false,\n }));\n // A new session supersedes any in-flight load: its session_created must not\n // be rejected by a stale pendingLoadFile, and a late load reply for the old\n // target must not clobber the new session.\n this.abandonPendingLoad(undefined, { keepShownSession: true });\n this.pendingLoadFile = null;\n this.hydratedFile = null;\n // A create supersedes any rejoin the next socket would otherwise make.\n this.resumeSessionFile = null;\n this.resumeCwd = undefined;\n this.resumeModel = undefined;\n const frame = {\n type: 'session_new',\n cwd,\n model,\n gitInit,\n createRemote,\n repoVisibility,\n cloneRemote,\n };\n this.queuedSessionRequest = this.send(frame) ? null : { type: 'create', frame };\n // Never let the blocking \"Creating session...\" overlay hang if the reply is\n // lost. Symmetrical with armLoadWatchdog for session_load.\n this.armCreateWatchdog();\n }\n leaveSession() {\n this.abandonUnsentUploads();\n const s = get(this.stateStore);\n // Leaving abandons any in-flight create too, so disarm its watchdog even when\n // there is no sessionId yet (a create that has not resolved).\n this.clearCreateWatchdog();\n // Leaving cancels whatever would otherwise (re)attach a session later: a\n // request queued while the socket was down, the rejoin of the session being\n // left, and the reply of a load still in flight. Done even with no\n // sessionId yet (a load or rejoin that has not resolved), since that is\n // exactly when a late reply would pull the user back.\n this.queuedSessionRequest = null;\n this.abandonPendingLoad();\n if (!s.sessionId && !s.activeSessionFile && this.pendingLoadFile === null && !this.resumeSessionFile) {\n if (s.creatingSession) {\n this.stateStore.update((st) => ({\n ...st,\n creatingSession: false,\n }));\n }\n return;\n }\n if (s.sessionId)\n this.send({ type: 'session_leave', sessionId: s.sessionId });\n this.stateStore.update((s) => ({\n ...s,\n messages: [],\n session: null,\n sessionId: null,\n activeSessionFile: null,\n activeCwd: null,\n activeModel: null,\n readOnly: false,\n folderMissing: null,\n restore: null,\n notice: null,\n sudoPrompt: null,\n creatingSession: false,\n loadingSession: false,\n resyncing: false,\n agentPending: false,\n contextUsage: null,\n pendingSteering: [],\n }));\n this.clearLoadWatchdog();\n this.pendingLoadFile = null;\n this.hydratedFile = null;\n this.resumeSessionFile = null;\n this.resumeCwd = undefined;\n this.resumeModel = undefined;\n }\n // --- RESTORE: materialise the active session's missing working folder -----\n //\n // \"Restore\" here means making the missing FOLDER exist again (clone it back,\n // or create it), never the unrelated re-materialising of queued steers/drafts\n // after a reload. See CONTEXT.md; the whole family is namespaced `restore*`.\n /**\n * Ask the server to restore the folder of the folder-missing session this\n * client is looking at: CLONE `url` into it, or CREATE it.\n *\n * The job is server-owned and keyed by that path, so this may well JOIN a job\n * another device (or this client's previous, dropped socket) already started;\n * the server's `restore_started` says which, and carries the url really in\n * flight. Returns false when there is no missing folder to restore, or when a\n * clone was asked for with no url.\n */\n startRestore(action, url, gitInit) {\n const s = get(this.stateStore);\n const targetPath = s.restore?.targetPath ?? s.folderMissing?.cwd;\n if (!targetPath)\n return false;\n const trimmedUrl = url?.trim();\n if (action === 'clone' && !trimmedUrl)\n return false;\n // Record what WE asked for before the answer lands, so the panel can compare\n // it with the url the (possibly joined) job is really cloning.\n this.stateStore.update((st) => {\n const previous = st.restore?.targetPath === targetPath ? st.restore.job : null;\n return {\n ...st,\n restore: {\n targetPath,\n // A RUNNING job is the one this request will join, so it stays on\n // screen. A terminal one belonged to the attempt being retried: drop\n // it, so the panel shows this request in flight rather than the\n // previous failure until the server answers.\n job: previous && previous.state === 'running' ? previous : null,\n joined: false,\n requestedUrl: trimmedUrl,\n rejection: null,\n },\n };\n });\n return this.send({\n type: 'restore_start',\n targetPath,\n action,\n ...(trimmedUrl ? { url: trimmedUrl } : {}),\n ...(gitInit !== undefined ? { gitInit } : {}),\n });\n }\n /**\n * Cancel the restore running for this session's folder. The server settles the\n * job authoritatively and broadcasts the `cancelled` completion to every client\n * watching that folder (this one included), so no state is guessed here.\n */\n cancelRestore() {\n const s = get(this.stateStore);\n const targetPath = s.restore?.targetPath;\n if (!targetPath)\n return false;\n return this.send({ type: 'restore_cancel', targetPath });\n }\n /**\n * Re-load the active session file.\n *\n * This is how a completed restore goes LIVE: whether a session has a live agent\n * is a load-time decision, and the load that found the folder missing\n * deliberately built none. Re-loading is therefore the honest way to get one,\n * not a refresh hint. Returns false when there is no active session file.\n */\n reloadSession() {\n const s = get(this.stateStore);\n const sessionFile = s.activeSessionFile;\n if (!sessionFile)\n return false;\n this.joinSession(sessionFile, s.activeCwd ?? undefined);\n return true;\n }\n // \"Continue anyway\" on the folder-conflict warning banner: ask the server to\n // lift read-only for this client's current session (both sessions in the\n // folder then run concurrently; the other is NOT aborted). Optimistically\n // enable the composer and mark the banner `continued` so it drops its button\n // but stays as a passive warning until the other session leaves the folder.\n continueFolderConflict() {\n const s = get(this.stateStore);\n if (!s.folderConflict || !s.sessionId)\n return;\n // \"Continue anyway\" answers a folder CONFLICT only. A missing folder is a\n // hard lock (there is nothing to drive, and no agent was built), and the\n // server refuses to lift it, so do not flash an enabled composer here.\n if (s.folderMissing)\n return;\n this.send({\n type: 'folder_conflict_continue',\n sessionId: s.sessionId,\n });\n this.stateStore.update((s) => ({\n ...s,\n readOnly: false,\n folderConflict: s.folderConflict\n ? { ...s.folderConflict, continued: true }\n : null,\n }));\n }\n ping() {\n this.send({ type: 'ping' });\n }\n clearMessages() {\n this.stateStore.update((s) => ({ ...s, messages: [] }));\n }\n dismissSessionError() {\n this.stateStore.update((s) => ({ ...s, sessionError: null }));\n }\n dismissNotice() {\n this.stateStore.update((s) => ({ ...s, notice: null }));\n }\n // Answer a pending `!sudo ...` prompt with the password the user typed. The\n // password is sent straight to the server (never stored in client state) and\n // the prompt is cleared. No-op if there is no matching pending prompt.\n sendSudoPassword(password) {\n const s = get(this.stateStore);\n const prompt = s.sudoPrompt;\n if (!prompt)\n return;\n this.send({\n type: 'bash_sudo_password',\n sessionId: prompt.sessionId,\n promptId: prompt.promptId,\n password,\n });\n this.stateStore.update((st) => ({ ...st, sudoPrompt: null }));\n }\n // Dismiss a pending `!sudo ...` prompt without running the command. Tells the\n // server to drop the deferred command and clears the local prompt.\n cancelSudoPrompt() {\n const s = get(this.stateStore);\n const prompt = s.sudoPrompt;\n this.stateStore.update((st) => ({ ...st, sudoPrompt: null }));\n if (!prompt)\n return;\n this.send({\n type: 'bash_sudo_cancel',\n sessionId: prompt.sessionId,\n promptId: prompt.promptId,\n });\n }\n changeModel(model) {\n this.send({ type: 'model_change', model });\n }\n setConfig(updates) {\n this.config = {\n ...this.config,\n ...updates,\n };\n this.stateStore.update((s) => {\n const next = { ...s };\n if (updates.hideThinking !== undefined)\n next.hideThinking = !!updates.hideThinking;\n if (updates.hideTools !== undefined)\n next.hideTools = !!updates.hideTools;\n return next;\n });\n }\n onMessage(cb) {\n this.listeners.add(cb);\n return () => {\n this.listeners.delete(cb);\n };\n }\n /**\n * Upload a file over the WebSocket. Resolves with the server's saved path;\n * rejects on failure (an `Error`, with `code: 'not_readable'` when the byte\n * source can no longer be read) or with \"Upload cancelled\" when\n * `options.signal` aborts. Progress (`{acked, size, state, error?}`) goes to\n * `options.onProgress` and to `uploadsStore`.\n *\n * The protocol is chosen when the upload is SENT, from that socket's\n * `connected.capabilities`: chunked (`upload.v1`) when advertised, else the\n * legacy base64 `file_upload` frame (see PendingUpload). The legacy path\n * refuses files over 72 MiB from `source.size`, before reading anything.\n */\n uploadFileViaWebSocket(sessionId, filename, source, options) {\n return new Promise((resolve, reject) => {\n const signal = options?.signal;\n if (signal?.aborted) {\n options?.onProgress?.({ acked: 0, size: source.size, state: 'aborted' });\n reject(new Error('Upload cancelled'));\n return;\n }\n const uploadId = generateUploadId();\n const upload = {\n uploadId,\n sessionId,\n filename,\n mime: options?.mime || undefined,\n source,\n onProgress: options?.onProgress,\n resolve,\n reject,\n timer: null,\n sentOn: null,\n protocol: null,\n state: 'queued',\n acked: 0,\n frame: null,\n preparing: false,\n sends: 0,\n begun: false,\n awaitingBegin: false,\n nextOffset: 0,\n inFlight: [],\n realigning: false,\n finishing: false,\n reading: false,\n readGen: 0,\n rate: null,\n lastAckAt: 0,\n };\n this.pendingUploads.set(uploadId, upload);\n this.reportUpload(upload);\n // Cancelling (e.g. the chip was removed) settles the promise and drops\n // the upload so it is not re-sent on the next reconnect. A chunked upload\n // the server knows about is told to drop its partial; a legacy frame\n // already handed to the socket cannot be recalled.\n signal?.addEventListener('abort', () => this.abortUpload(uploadId), { once: true });\n // Sent now when the socket is OPEN, its capabilities are known and it is\n // not mid-rejoin. Otherwise the upload waits in pendingUploads and is\n // sent once those hold.\n if (!this.trySendUpload(uploadId))\n this.ensureUploadTimer(uploadId);\n });\n }\n // Number of uploads still waiting for a server reply (sent or parked).\n pendingUploadCount() {\n return this.pendingUploads.size;\n }\n /** Drop a SETTLED upload's entry from uploadsStore (in-flight ones stay). */\n forgetUpload(uploadId) {\n if (this.pendingUploads.has(uploadId))\n return;\n this.uploadsStore.update((all) => {\n if (!(uploadId in all))\n return all;\n const next = { ...all };\n delete next[uploadId];\n return next;\n });\n }\n // Hand the upload to the current socket if it can go now. True when it is on\n // the wire (or settled: nothing left to wait for), false when it waits.\n trySendUpload(uploadId) {\n const upload = this.pendingUploads.get(uploadId);\n if (!upload || this.uploadsHeldForRejoin)\n return false;\n if (!this.ws || this.ws.readyState !== 1 /* OPEN */)\n return false;\n // Capabilities unknown: HOLD (see socketCapabilities).\n if (this.socketCapabilities === null)\n return false;\n const chunked = this.socketCapabilities.includes(UPLOAD_CAPABILITY);\n if (upload.protocol === null)\n upload.protocol = chunked ? 'chunked' : 'legacy';\n if (upload.protocol === 'chunked') {\n if (!chunked) {\n this.failUpload(uploadId, 'The server no longer supports resumable uploads, retry');\n return true;\n }\n return this.beginChunkedUpload(upload);\n }\n return this.sendLegacyUpload(upload);\n }\n sendLegacyUpload(upload) {\n if (upload.sends >= WhereverClient.MAX_UPLOAD_SENDS) {\n // Every previous attempt lost its socket mid-transfer: stop retrying.\n this.failUpload(upload.uploadId, 'Upload failed: the connection dropped during the transfer each time (the file may be too large or the connection too slow)');\n return true;\n }\n if (!upload.frame) {\n // Checked from the size BEFORE reading, so a huge video is never loaded\n // and encoded just to be refused (and never crashes the tab).\n if (upload.source.size > WhereverClient.MAX_LEGACY_UPLOAD_BYTES) {\n this.failUpload(upload.uploadId, 'File too large to upload over the WebSocket (max 72 MB)');\n return true;\n }\n if (!upload.preparing) {\n upload.preparing = true;\n this.prepareLegacyFrame(upload);\n }\n return false;\n }\n if (!this.send(upload.frame))\n return false;\n upload.sends++;\n upload.sentOn = this.ws;\n // On the wire: stop the waiting clock (transmission time is not bounded).\n this.stopUploadTimer(upload);\n this.reportUpload(upload, 'sending');\n return true;\n }\n // Read and base64-encode the whole file once, then send it if still wanted.\n prepareLegacyFrame(upload) {\n this.readLegacyBase64(upload.source).then((data) => {\n if (this.pendingUploads.get(upload.uploadId) !== upload)\n return;\n upload.preparing = false;\n upload.frame = {\n type: 'file_upload',\n uploadId: upload.uploadId,\n sessionId: upload.sessionId,\n filename: upload.filename,\n data,\n };\n if (!this.trySendUpload(upload.uploadId))\n this.ensureUploadTimer(upload.uploadId);\n }, (err) => {\n if (this.pendingUploads.get(upload.uploadId) !== upload)\n return;\n const e = err instanceof UploadReadError ? err : uploadReadError(err);\n this.failUpload(upload.uploadId, e.message, e.code);\n });\n }\n // base64 over reads of LEGACY_READ_BYTES (a multiple of 3, so no padding in\n // the middle), platform-neutral (btoa). MAX_UPLOAD_BASE64_CHARS is a\n // backstop for a source that yields more than its size claimed.\n async readLegacyBase64(source) {\n const parts = [];\n let chars = 0;\n for (let offset = 0; offset < source.size; offset += LEGACY_READ_BYTES) {\n const length = Math.min(LEGACY_READ_BYTES, source.size - offset);\n let bytes;\n try {\n bytes = await source.read(offset, length);\n }\n catch (err) {\n throw uploadReadError(err);\n }\n chars += 4 * Math.ceil(bytes.length / 3);\n if (chars > WhereverClient.MAX_UPLOAD_BASE64_CHARS) {\n throw new UploadReadError('File too large to upload over the WebSocket (max 72 MB)');\n }\n if (bytes.length !== length)\n throw shortReadError();\n parts.push(btoa(bytesToBinaryString(bytes)));\n }\n return parts.join('');\n }\n // (Re)start a chunked upload on the current socket: the begin's answer says\n // where to continue (or that it is already done).\n beginChunkedUpload(upload) {\n const sent = this.send({\n type: 'upload_begin',\n uploadId: upload.uploadId,\n sessionId: upload.sessionId,\n filename: upload.filename,\n size: upload.source.size,\n ...(upload.mime ? { mime: upload.mime } : {}),\n });\n if (!sent)\n return false;\n upload.begun = true;\n upload.sentOn = this.ws;\n upload.awaitingBegin = true;\n upload.inFlight = [];\n upload.realigning = false;\n upload.finishing = false;\n upload.readGen++;\n // Transmitting: the waiting clock stops (it bounds waiting, not sending).\n this.stopUploadTimer(upload);\n this.reportUpload(upload, 'sending');\n return true;\n }\n // `upload_offset`: the server's offset for a chunked upload, answering a begin\n // or a chunk. Progress is ONLY ever this value, never what was sent.\n handleUploadOffset(msg) {\n const upload = this.pendingUploads.get(msg.uploadId);\n if (!upload || upload.protocol !== 'chunked' || !this.isUploadOnWire(upload))\n return;\n if (msg.done) {\n this.completeUpload(upload.uploadId, { savedPath: msg.savedPath, filename: upload.filename });\n return;\n }\n const offset = msg.offset;\n const size = upload.source.size;\n if (!Number.isSafeInteger(offset) || offset < 0 || offset > size)\n return;\n const now = Date.now();\n if (upload.awaitingBegin) {\n upload.awaitingBegin = false;\n upload.nextOffset = offset;\n upload.lastAckAt = now;\n }\n else {\n const chunk = upload.inFlight.shift();\n if (!chunk)\n return; // nothing of ours is awaiting an answer\n if (!upload.realigning && offset === chunk.offset + chunk.length) {\n // Time this chunk from when it could start being serviced: its send, or\n // the previous ack if it was queued behind that one.\n const elapsed = Math.max(1, now - Math.max(chunk.sentAt, upload.lastAckAt));\n const sample = chunk.length / elapsed;\n upload.rate =\n upload.rate === null ? sample : upload.rate * (1 - UPLOAD_RATE_ALPHA) + sample * UPLOAD_RATE_ALPHA;\n upload.lastAckAt = now;\n }\n else if (!upload.realigning) {\n // Out of step with the server: discard any read meant for the old\n // position and wait for the rest of the in-flight acks.\n upload.realigning = true;\n upload.readGen++;\n }\n if (upload.realigning && upload.inFlight.length === 0) {\n upload.realigning = false;\n upload.nextOffset = offset;\n upload.lastAckAt = now;\n }\n }\n upload.acked = offset;\n this.reportUpload(upload);\n this.pumpUpload(upload);\n }\n uploadWindow(upload) {\n if (upload.rate === null)\n return UPLOAD_WINDOW_MIN;\n const bytes = upload.rate * 1000 * UPLOAD_WINDOW_SECONDS;\n return Math.min(UPLOAD_WINDOW_MAX, Math.max(UPLOAD_WINDOW_MIN, Math.floor(bytes)));\n }\n // Send the next chunk if the window allows, or finish once every byte is\n // acked. One source read at a time; each completed send pumps again.\n pumpUpload(upload) {\n if (this.pendingUploads.get(upload.uploadId) !== upload)\n return;\n if (upload.reading || upload.awaitingBegin || upload.realigning || upload.finishing)\n return;\n if (!this.isUploadOnWire(upload))\n return;\n const size = upload.source.size;\n if (upload.acked === size && upload.inFlight.length === 0) {\n if (!this.send({ type: 'upload_finish', uploadId: upload.uploadId, sessionId: upload.sessionId }))\n return;\n upload.finishing = true;\n this.reportUpload(upload, 'finishing');\n return;\n }\n if (upload.nextOffset >= size)\n return;\n const window = this.uploadWindow(upload);\n const length = Math.min(window, UPLOAD_CHUNK_MAX, size - upload.nextOffset);\n const inFlightBytes = upload.inFlight.reduce((n, c) => n + c.length, 0);\n if (inFlightBytes + length > window)\n return;\n const offset = upload.nextOffset;\n const gen = upload.readGen;\n const socket = this.ws;\n upload.reading = true;\n Promise.resolve()\n .then(() => upload.source.read(offset, length))\n .then((bytes) => {\n if (this.pendingUploads.get(upload.uploadId) !== upload)\n return;\n upload.reading = false;\n // The socket or the alignment changed while reading: drop the bytes.\n if (gen !== upload.readGen || socket !== this.ws || !this.isUploadOnWire(upload)) {\n this.pumpUpload(upload);\n return;\n }\n if (bytes.length !== length) {\n const e = shortReadError();\n this.failUpload(upload.uploadId, e.message, e.code);\n return;\n }\n // A socket that refuses the frame is closing; its close handler\n // pauses the upload.\n if (!this.sendBinary(encodeChunkFrame(upload.uploadId, offset, bytes)))\n return;\n upload.inFlight.push({ offset, length, sentAt: Date.now() });\n upload.nextOffset = offset + length;\n this.pumpUpload(upload);\n }, (err) => {\n if (this.pendingUploads.get(upload.uploadId) !== upload)\n return;\n const e = uploadReadError(err);\n this.failUpload(upload.uploadId, e.message, e.code);\n });\n }\n sendBinary(bytes) {\n if (this.ws && this.ws.readyState === 1 /* OPEN */) {\n try {\n this.ws.send(bytes);\n return true;\n }\n catch {\n return false;\n }\n }\n return false;\n }\n // Record (and announce) an upload's progress. `state` defaults to the current.\n reportUpload(upload, state, error) {\n if (state)\n upload.state = state;\n const progress = {\n acked: upload.acked,\n size: upload.source.size,\n state: upload.state,\n ...(error ? { error } : {}),\n };\n this.uploadsStore.update((all) => ({ ...all, [upload.uploadId]: progress }));\n if (upload.onProgress) {\n try {\n upload.onProgress({ ...progress });\n }\n catch (err) {\n console.error('Upload onProgress failed:', err);\n }\n }\n }\n completeUpload(uploadId, result) {\n const upload = this.takePendingUpload(uploadId);\n if (!upload)\n return;\n upload.acked = upload.source.size;\n this.reportUpload(upload, 'done');\n upload.resolve(result);\n }\n failUpload(uploadId, message, code) {\n const upload = this.takePendingUpload(uploadId);\n if (!upload)\n return;\n const err = new Error(message);\n if (code)\n err.code = code;\n this.reportUpload(upload, 'failed', code ? { message, code } : { message });\n upload.reject(err);\n }\n abortUpload(uploadId) {\n const upload = this.takePendingUpload(uploadId);\n if (!upload)\n return;\n // Best effort: with no open socket the partial is left to the server's GC.\n if (upload.protocol === 'chunked' && upload.begun) {\n this.send({ type: 'upload_abort', uploadId, sessionId: upload.sessionId });\n }\n this.reportUpload(upload, 'aborted');\n upload.reject(new Error('Upload cancelled'));\n }\n isUploadOnWire(pending) {\n return pending.sentOn !== null && pending.sentOn === this.ws;\n }\n // The socket carrying uploads went away (by close, suspend, or the liveness\n // teardown, the latter two bypassing onClose). Every upload is waiting again:\n // forget where it was sent, pause it, and restart its waiting clock, so no\n // upload can be left without a timer. A chunked upload forgets its in-flight\n // chunks: the next begin tells it what the server really has.\n uploadsLostSocket() {\n for (const [id, upload] of this.pendingUploads) {\n const wasOnWire = upload.sentOn !== null;\n upload.sentOn = null;\n if (upload.protocol === 'chunked') {\n upload.awaitingBegin = false;\n upload.inFlight = [];\n upload.realigning = false;\n upload.finishing = false;\n upload.readGen++;\n }\n if (wasOnWire && upload.state !== 'paused')\n this.reportUpload(upload, 'paused');\n // Arm only a clock that is not already running. Re-arming on every loss\n // restarted the deadline on each failed reconnect attempt (at most 15 s\n // apart), so an upload against an unreachable server waited forever.\n this.ensureUploadTimer(id);\n }\n }\n // Fail uploads that have not reached the current socket (parked or held),\n // optionally sparing those aimed at `keepSessionId`.\n failUnsentUploads(reason, keepSessionId) {\n for (const [id, upload] of [...this.pendingUploads]) {\n if (this.isUploadOnWire(upload))\n continue;\n if (keepSessionId && upload.sessionId === keepSessionId)\n continue;\n this.failUpload(id, reason);\n }\n }\n failHeldUploads(reason) {\n if (!this.uploadsHeldForRejoin)\n return;\n this.uploadsHeldForRejoin = false;\n this.failUnsentUploads(reason);\n }\n // Switching / creating / leaving a session: an upload not yet on the wire\n // would otherwise be released by the NEXT session's session_created and be\n // gated by the wrong session's verdict. One already on the wire is left to\n // its reply (the server answers on this socket regardless of attachment).\n abandonUnsentUploads() {\n this.uploadsHeldForRejoin = false;\n this.failUnsentUploads('The session changed before the upload could be sent');\n }\n // Start the waiting clock unless one is already running (keeps the deadline).\n ensureUploadTimer(uploadId) {\n const pending = this.pendingUploads.get(uploadId);\n if (pending && !pending.timer)\n this.armUploadTimer(uploadId);\n }\n stopUploadTimer(upload) {\n if (upload.timer)\n clearTimeout(upload.timer);\n upload.timer = null;\n }\n armUploadTimer(uploadId) {\n const pending = this.pendingUploads.get(uploadId);\n if (!pending || typeof setTimeout !== 'function')\n return;\n if (pending.timer)\n clearTimeout(pending.timer);\n pending.timer = setTimeout(() => {\n this.failUpload(uploadId, 'Upload timed out (no connection to the server)');\n }, WhereverClient.UPLOAD_TIMEOUT_MS);\n if (pending.timer && typeof pending.timer.unref === 'function') {\n pending.timer.unref();\n }\n }\n takePendingUpload(uploadId) {\n const pending = this.pendingUploads.get(uploadId);\n if (!pending)\n return undefined;\n this.pendingUploads.delete(uploadId);\n if (pending.timer)\n clearTimeout(pending.timer);\n return pending;\n }\n resendPendingUploads() {\n for (const [id, pending] of [...this.pendingUploads]) {\n if (this.isUploadOnWire(pending))\n continue;\n if (!this.trySendUpload(id))\n this.ensureUploadTimer(id);\n }\n }\n rejectPendingUploads(reason) {\n for (const id of [...this.pendingUploads.keys()]) {\n this.failUpload(id, reason);\n }\n }\n generateId() {\n return Math.random().toString(36).substring(2) + Date.now().toString(36);\n }\n getIsConnected() {\n return this.ws && this.ws.readyState === 1;\n }\n}\n//# sourceMappingURL=client.js.map","// Conversation mode is a saved PRESET over a set of independent boolean knobs.\n// A single \"Conversation Mode\" master toggle flips the configured bundle ON and\n// GATES the purely-conversation knobs; when it is off those knobs are dormant\n// and the default typing-first experience is unchanged. This module is the pure\n// registry + gating logic: which knobs exist, where each one's single canonical\n// persisted home is, and whether a given knob is currently ACTIVE. The actual\n// localStorage read/write + reactive stores live in wherever.ts (mirroring the\n// beepDefault persisted-flag pattern); the behaviours the knobs drive (TTS, the\n// say card, collapse-long-replies, hands-free mic re-open) are SEPARATE tasks\n// that READ these knobs. This task owns the registry + toggle + persistence +\n// gating only.\n\n/**\n * The full set of conversation-mode knobs.\n *\n * - `conversationMode` is the MASTER toggle; the others are the bundle it gates.\n * - `autoSendOnSpeechEnd` is NOT a new flag: it IS the pre-existing `directSend`\n * (send-on-speech-end) surfaced as a conversation knob. It therefore keeps the\n * existing `wherever-speech-direct-send` home (see KNOB_STORAGE) and its\n * standalone behaviour is NOT suppressed when the master is off (story 14).\n */\nexport const CONVERSATION_KNOBS = [\n\t'conversationMode',\n\t'autoSendOnSpeechEnd',\n\t'speakReplies',\n\t'collapseLongReplies',\n\t'micReopensAfterReply',\n] as const;\n\nexport type ConversationKnob = (typeof CONVERSATION_KNOBS)[number];\n\nexport type ConversationKnobs = Record<ConversationKnob, boolean>;\n\n/**\n * The purely-conversation knobs: those the master toggle gates. Deliberately\n * EXCLUDES `autoSendOnSpeechEnd` (= directSend), whose standalone effect must\n * survive the master being off, and `conversationMode` itself (the master).\n */\nexport const GATED_KNOBS = [\n\t'speakReplies',\n\t'collapseLongReplies',\n\t'micReopensAfterReply',\n] as const;\n\nexport type GatedKnob = (typeof GATED_KNOBS)[number];\n\n/**\n * The single canonical persisted home for each knob. Exactly one home per knob;\n * no knob is stored in two places and no key is shared by two knobs.\n *\n * - `store: 'speech'` knobs live under a `wherever-speech-*` localStorage key\n * (the SpeechButton pref pattern). Only `autoSendOnSpeechEnd` uses this, and\n * it reuses the EXISTING `wherever-speech-direct-send` key so it is the SAME\n * underlying value as `directSend` (no forked second flag).\n * - `store: 'config'` knobs live as a boolean field in the single\n * `wherever-config` localStorage entry via getConfig()/saveConfig() (the\n * beepDefault pattern).\n *\n * NOTE for `conversationMode` (the master): its config field is the per-session\n * DEFAULT, not the effective value. The master is scoped PER CONVERSATION (see\n * resolveConversationMode + the override map in wherever.ts), so the config field\n * answers \"what should a conversation that has not been toggled use?\".\n */\nexport const KNOB_STORAGE: {\n\treadonly [K in ConversationKnob]:\n\t\t| {store: 'speech'; key: string}\n\t\t| {store: 'config'; field: K};\n} = {\n\tconversationMode: {store: 'config', field: 'conversationMode'},\n\tautoSendOnSpeechEnd: {store: 'speech', key: 'wherever-speech-direct-send'},\n\tspeakReplies: {store: 'config', field: 'speakReplies'},\n\tcollapseLongReplies: {store: 'config', field: 'collapseLongReplies'},\n\tmicReopensAfterReply: {store: 'config', field: 'micReopensAfterReply'},\n};\n\nfunction isGated(knob: ConversationKnob): knob is GatedKnob {\n\treturn (GATED_KNOBS as readonly string[]).includes(knob);\n}\n\n/**\n * Whether a knob is currently ACTIVE, i.e. its effect should apply right now.\n *\n * - A purely-conversation (gated) knob is active only when BOTH the master\n * `conversationMode` is on AND the knob itself is set. With the master off it\n * is dormant (no TTS, no collapse, no mic re-open) so behaviour matches the\n * typing-first default.\n * - `autoSendOnSpeechEnd` (= directSend) is NOT gated: its own value alone\n * decides, regardless of the master, so a standalone-set directSend still\n * auto-sends with the mode off (story 14) and today's behaviour is preserved.\n * - `conversationMode` (the master) is active exactly when it is set.\n */\nexport function isKnobActive(\n\tknob: ConversationKnob,\n\tknobs: ConversationKnobs,\n): boolean {\n\tif (isGated(knob)) {\n\t\treturn knobs.conversationMode && knobs[knob];\n\t}\n\t// autoSendOnSpeechEnd and conversationMode: ungated, own value decides.\n\treturn knobs[knob];\n}\n\n/**\n * Whether an outgoing user message should carry the per-turn conversation-mode\n * SIGNAL (the optional `conversationMode` field on the existing `message` WS\n * payload), which tells the agent a spoken conversation is active so it adds a\n * short `say` reply to its written answer.\n *\n * True iff BOTH the master `conversationMode` and `speakReplies` are active: a\n * \"please also speak\" hint is pointless when spoken output is off. That is exactly\n * the existing gate for `speakReplies`, so this REUSES isKnobActive rather than\n * re-deriving the rule (one definition of \"spoken replies are on right now\").\n */\nexport function shouldSignalConversationMode(\n\tknobs: ConversationKnobs,\n): boolean {\n\treturn isKnobActive('speakReplies', knobs);\n}\n\n/**\n * Flip the master toggle ON. Conversation mode is a saved bundle of the user's\n * independently-configured knobs, so turning it on turns the master on and\n * leaves every other knob at its configured value (it does NOT force them all\n * on). The configured gated knobs then become active via isKnobActive.\n */\nexport function bundleOn(knobs: ConversationKnobs): ConversationKnobs {\n\treturn {...knobs, conversationMode: true};\n}\n\n/**\n * The effective master toggle for ONE conversation.\n *\n * The master is PER CONVERSATION, not global: a spoken exchange is a property of\n * the conversation you are having, not of the app. Turning it on in the bar while\n * talking to one session must not start speaking replies in every other session\n * (and, on the wire, must not stamp the conversation-mode signal on messages sent\n * from them). So each session can hold its OWN explicit choice, and the config\n * flag is the DEFAULT a session uses until it is toggled.\n *\n * \"Unset\" is a real, distinct state, exactly as it is for the waiting-for-human\n * beep (whose per-session override this mirrors deliberately):\n * - a session with NO override FOLLOWS the default, live: change the default and\n * that session changes with it;\n * - once toggled, the session's own choice STICKS and later default changes do\n * not move it, until it is cleared back to \"follow default\".\n *\n * The gated knobs (speakReplies, collapseLongReplies, micReopensAfterReply) stay\n * GLOBAL settings: they describe HOW a spoken conversation behaves, and the user\n * configures that once. Only WHETHER this conversation is a spoken one is per\n * conversation.\n */\nexport function resolveConversationMode(\n\toverride: boolean | undefined,\n\tdefaultOn: boolean,\n): boolean {\n\treturn override === undefined ? defaultOn : override;\n}\n","/**\n * Compose the message text that carries uploaded-file references to the agent.\n *\n * Uploads are server-side: the browser POSTs the bytes, the server writes them\n * to the upload dir and returns the saved path. The agent only ever learns\n * about a file through a `[Uploaded file: <path>]` line in the user message,\n * so this is the single place that shape is defined.\n *\n * Shared by the chat composer (upload first, then send) and the search flow\n * (create the session first, THEN upload, then send the query), which is why it\n * takes plain paths rather than the composer's attachment records.\n */\nexport function buildAttachmentMessage(text: string, paths: string[]): string {\n\tconst trimmed = text.trim();\n\tif (paths.length === 0) return trimmed;\n\tconst fileLines = paths.map((p) => `[Uploaded file: ${p}]`).join('\\n');\n\t// With no prose of their own, the files ARE the message: name them\n\t// explicitly so the agent has an instruction rather than bare paths.\n\treturn trimmed\n\t\t? `${trimmed}\\n\\n${fileLines}`\n\t\t: `I have uploaded the following file(s) for you:\\n${fileLines}`;\n}\n","// Single source of truth for \"which top-level view are we in\", derived from the\n// session lifecycle flags. Both the message area (ChatMessageList) and the\n// bottom composer (+page.svelte) key off this so they can never disagree -- the\n// bug being fixed was the composer showing the search input while the message\n// area showed \"Loading session...\" because each computed the no-session state\n// independently.\n\nexport interface SessionViewInputs {\n\tconnected: boolean;\n\t/** A session's transcript is loaded (activeSessionFile is set). */\n\thasSession: boolean;\n\t/** A fresh session load is in flight (loadingSession). */\n\tloading: boolean;\n\t/** A reconnect is rejoining a cached session (resyncing). */\n\tresyncing: boolean;\n\t/** A URL hash points at a session we are about to open. */\n\thasSessionHash: boolean;\n\t/**\n\t * The last session load failed (an error is showing, nothing is loading and\n\t * no session is active). A hash that is still present is then NOT a pending\n\t * open: it would otherwise keep the \"Loading session...\" spinner up forever.\n\t */\n\tloadFailed?: boolean;\n}\n\n/**\n * True when a session is being opened (or reopened) but its transcript is not\n * yet on screen: a fresh load, a resync, or a hash that will drive a load. In\n * this window sessionFile is briefly null, but this is NOT the search / new-\n * session home state -- the message area shows a \"Loading session...\" spinner,\n * so the composer must NOT present the search input.\n */\nexport function isSessionPendingOpen(i: SessionViewInputs): boolean {\n\treturn i.loading || i.resyncing || (i.hasSessionHash && !i.loadFailed);\n}\n\n/**\n * True only at the genuine no-session home state where the composer acts as the\n * web-search input: connected, a search folder configured, no active session,\n * and no session mid-open. Mirrors the message area's empty-state condition so\n * the two views stay consistent.\n */\nexport function isSearchActive(\n\ti: SessionViewInputs & {searchConfigured: boolean},\n): boolean {\n\treturn (\n\t\ti.connected &&\n\t\ti.searchConfigured &&\n\t\t!i.hasSession &&\n\t\t!isSessionPendingOpen(i)\n\t);\n}\n\nexport interface HashJoinInputs {\n\tconnected: boolean;\n\t/** Session id from the URL hash ('' when there is none). */\n\thashId: string;\n\t/** The active session's id (null when none). */\n\tcurrentSessionId: string | null;\n\tloading: boolean;\n\tresyncing: boolean;\n\t/**\n\t * A new session is being created. The hash may still name the session the\n\t * user left (it is only rewritten while connected), and joining it would pull\n\t * the user back from the session they asked for.\n\t */\n\tcreating?: boolean;\n\t/**\n\t * The hash id the auto-join last issued a load for, still unresolved by a\n\t * success. Reset on disconnect, on success, and on a hash change.\n\t */\n\tattemptedHashId: string | null;\n}\n\n/**\n * What the URL-hash auto-join should do now.\n * - 'skip': nothing to do (no hash, not connected, already on it, or a load or\n * resync is in flight).\n * - 'join': issue a load for the hash session.\n * - 'failed': we already tried THIS hash id and the load ended without the\n * session becoming active (an untagged session_error such as \"session not\n * found\", or the load watchdog). Do NOT retry: without this the effect\n * re-joined every ~300 ms forever, since the error clears `loading` (which\n * re-runs the effect) while nothing clears the hash.\n */\nexport function decideHashJoin(i: HashJoinInputs): 'skip' | 'join' | 'failed' {\n\tif (!i.connected || !i.hashId) return 'skip';\n\tif (i.currentSessionId === i.hashId || i.loading || i.resyncing || i.creating)\n\t\treturn 'skip';\n\t// Only a failure when nothing is active: a session that IS active (e.g. the\n\t// hash names it by file path rather than id, so the ids never match) must\n\t// not be treated as a failed load, which would clear the hash and leave it.\n\tif (i.attemptedHashId === i.hashId)\n\t\treturn i.currentSessionId ? 'skip' : 'failed';\n\treturn 'join';\n}\n\nexport interface StaleHashInputs {\n\tconnected: boolean;\n\t/** Session id or file from the URL hash ('' when there is none). */\n\thashId: string;\n\t/** The session the user is switching to; undefined for a leave. */\n\ttarget?: string;\n}\n\n/**\n * Whether a leave or switch must drop the URL hash itself.\n *\n * While connected the page rewrites the hash as the session changes, so there\n * is nothing to do. While disconnected it cannot (an empty session then is a\n * boot, not a leave), so a hash still naming the session the user moved away\n * from would be auto-joined once connected: after a leave, or after the switched\n * to session failed to load, pulling the user back to the old session. A hash\n * already naming the switch target is kept.\n */\nexport function shouldDropStaleHash(i: StaleHashInputs): boolean {\n\treturn !i.connected && !!i.hashId && i.hashId !== i.target;\n}\n","/**\n * The `uploads.method: 'post'` upload: one `POST /session/upload` over\n * XMLHttpRequest, mapped onto the same `onProgress({acked, size, state,\n * error?})` contract as the WebSocket paths, so the composer chip renders it\n * identically.\n *\n * XMLHttpRequest rather than `fetch` because `fetch` has no upload progress;\n * `xhr.upload.onprogress` does. The XHR is injected (`createXhr`) so the\n * mapping is unit-tested without a browser.\n *\n * Decisions (recorded here, the choice site; linked from the task's done record):\n * - Over POST, `acked` is `upload.onprogress`'s `loaded`: the bytes the browser\n * has handed to the network, not bytes the server confirmed (the WebSocket\n * paths' meaning). It is the only progress signal HTTP gives, and the task\n * prescribes it. The bar can therefore sit at 100% `sending` while the server\n * finishes writing; `done` only follows the server's 2xx reply.\n * - The `File` is sent as-is (streamed by the browser) instead of being read\n * into one `ArrayBuffer` first, as the old `fetch` path did, so a large file\n * is never held in memory. The price is that an OS-invalidated pick no longer\n * throws `NotReadableError` up front; it surfaces as a network error. So on\n * `error`, the source is probed (`probeReadable`, one byte) and an unreadable\n * file reports `code: 'not_readable'` (\"pick it again\"), as before.\n * - XHR does not settle a promise by itself, so every terminal event (`load`,\n * `error`, `abort`, `timeout`) settles it, exactly once; events after that are\n * ignored. There is no resume over POST: a failure is retried from zero.\n */\nimport type {UploadError, UploadProgress} from '@wherever-dev/client';\n\n/** The parts of XMLHttpRequest this module uses. */\nexport interface PostUploadXhr {\n\topen(method: string, url: string): void;\n\tsetRequestHeader(name: string, value: string): void;\n\tsend(body: any): void;\n\tabort(): void;\n\treadonly status: number;\n\treadonly responseText: string;\n\tupload: {onprogress: ((e: {loaded: number}) => void) | null};\n\tonload: (() => void) | null;\n\tonerror: (() => void) | null;\n\tonabort: (() => void) | null;\n\tontimeout: (() => void) | null;\n}\n\nexport interface PostUploadResult {\n\tsavedPath: string;\n\tfilename: string;\n}\n\nexport const NOT_READABLE_MESSAGE =\n\t'The file is no longer readable, pick it again';\n\nfunction abortError(): Error {\n\treturn Object.assign(new Error('Upload cancelled'), {name: 'AbortError'});\n}\n\nexport function postUpload(opts: {\n\turl: string;\n\tbody: unknown;\n\tsize: number;\n\tsignal?: AbortSignal;\n\tonProgress?: (p: UploadProgress) => void;\n\tcreateXhr?: () => PostUploadXhr;\n\t/** Resolves false when the source can no longer be read (see the module comment). */\n\tprobeReadable?: () => Promise<boolean>;\n}): Promise<PostUploadResult> {\n\tconst {size, signal} = opts;\n\tlet acked = 0;\n\tconst report = (state: UploadProgress['state'], error?: UploadError) =>\n\t\topts.onProgress?.({acked, size, state, ...(error ? {error} : {})});\n\n\treturn new Promise<PostUploadResult>((resolve, reject) => {\n\t\tif (signal?.aborted) {\n\t\t\treport('aborted');\n\t\t\treject(abortError());\n\t\t\treturn;\n\t\t}\n\t\tconst xhr = (\n\t\t\topts.createXhr ?? (() => new XMLHttpRequest() as PostUploadXhr)\n\t\t)();\n\t\tlet settled = false;\n\t\tconst onSignal = () => xhr.abort();\n\t\tconst finish = () => {\n\t\t\tsettled = true;\n\t\t\tsignal?.removeEventListener('abort', onSignal);\n\t\t};\n\t\tconst fail = (message: string, code?: UploadError['code']) => {\n\t\t\tif (settled) return;\n\t\t\tfinish();\n\t\t\tconst error: UploadError = code ? {message, code} : {message};\n\t\t\treport('failed', error);\n\t\t\treject(Object.assign(new Error(message), code ? {code} : {}));\n\t\t};\n\n\t\txhr.upload.onprogress = (e) => {\n\t\t\tif (settled) return;\n\t\t\tacked = Math.max(0, Math.min(size, e.loaded));\n\t\t\treport('sending');\n\t\t};\n\t\txhr.onload = () => {\n\t\t\tif (settled) return;\n\t\t\tlet data: any;\n\t\t\ttry {\n\t\t\t\tdata = JSON.parse(xhr.responseText);\n\t\t\t} catch {\n\t\t\t\tdata = undefined;\n\t\t\t}\n\t\t\tif (xhr.status < 200 || xhr.status >= 300) {\n\t\t\t\tfail(\n\t\t\t\t\t(data && typeof data.error === 'string' && data.error) ||\n\t\t\t\t\t\t`Upload failed with status ${xhr.status}`,\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!data || typeof data.savedPath !== 'string') {\n\t\t\t\tfail('Upload failed: the server sent an unreadable reply');\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tfinish();\n\t\t\tacked = size;\n\t\t\treport('done');\n\t\t\tresolve(data);\n\t\t};\n\t\txhr.onerror = () => {\n\t\t\tif (settled) return;\n\t\t\tconst probe = opts.probeReadable ?? (async () => true);\n\t\t\tprobe()\n\t\t\t\t.catch(() => false)\n\t\t\t\t.then((readable) =>\n\t\t\t\t\treadable\n\t\t\t\t\t\t? fail('Upload failed (network error)')\n\t\t\t\t\t\t: fail(NOT_READABLE_MESSAGE, 'not_readable'),\n\t\t\t\t);\n\t\t};\n\t\txhr.ontimeout = () => fail('Upload timed out');\n\t\txhr.onabort = () => {\n\t\t\tif (settled) return;\n\t\t\tfinish();\n\t\t\treport('aborted');\n\t\t\treject(abortError());\n\t\t};\n\n\t\tsignal?.addEventListener('abort', onSignal);\n\t\txhr.open('POST', opts.url);\n\t\t// `text/plain`, as the `fetch` path sent: a CORS-safelisted type keeps\n\t\t// this a simple request (the server reads the raw body regardless).\n\t\txhr.setRequestHeader('Content-Type', 'text/plain');\n\t\treport('sending');\n\t\txhr.send(opts.body);\n\t});\n}\n\n/** Can the first byte of `file` still be read? (an OS-invalidated pick cannot). */\nexport async function fileStillReadable(file: Blob): Promise<boolean> {\n\ttry {\n\t\tawait file.slice(0, 1).arrayBuffer();\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n","/**\n * The web client's timezone report (spec `assistant-session-and-channels`,\n * ADR 0015: a job without its own `tz` follows the user's CURRENT timezone).\n *\n * Sent on every connect (`wherever.ts`, on the server's `connected` frame). The\n * server makes it the user's current timezone when the assistant is active and\n * the zone differs (recorded), and ignores it otherwise, so it is safe to send\n * to any server (an older one simply drops an unknown message type).\n */\nexport interface TimezoneReportFrame {\n\ttype: 'client_timezone';\n\ttimezone: string;\n}\n\nconst browserTimeZone = (): string | undefined =>\n\tIntl.DateTimeFormat().resolvedOptions().timeZone;\n\n/** The frame to send, or null when the browser does not know its zone. */\nexport function timezoneReportFrame(\n\tresolve: () => string | undefined = browserTimeZone,\n): TimezoneReportFrame | null {\n\tlet timezone: string | undefined;\n\ttry {\n\t\ttimezone = resolve();\n\t} catch {\n\t\treturn null;\n\t}\n\tif (typeof timezone !== 'string' || !timezone) return null;\n\treturn {type: 'client_timezone', timezone};\n}\n","// Client-side half of saved drafts (messages kept instead of sent).\n//\n// The STORE is server-side (`server/src/drafts.ts`, `<config dir>/drafts.json`):\n// a draft saved on a phone has to be there on the laptop, so the machine holds\n// it, not a browser. The server is therefore the ONLY writer: it owns the id,\n// the dedupe, the cap and the ordering, and every mutation answers with the whole\n// new list, which this client adopts verbatim. Nothing here merges lists.\n//\n// What lives here is what the server cannot know: what the composer should do\n// when a draft is loaded into it. Plus a tolerant parse for the local MIRROR of\n// the server list, which exists only so the drafts panel still renders something\n// while disconnected (saving and deleting always need the server).\n//\n// This is deliberately a different thing from the composer's per-session\n// AUTO-draft (`wherever-draft:<sessionId>`), which is invisible crash protection\n// for the one text currently in the box, rewritten on every keystroke and\n// cleared by a send. Round-tripping that to the server per keystroke would be\n// absurd; a saved draft is an explicit, durable artifact and belongs on the\n// machine.\n\n/** localStorage mirror of the server list. Read-only cache: never uploaded. */\nexport const DRAFTS_CACHE_KEY = 'wherever-drafts-cache';\n\n/**\n * The key the FIRST (browser-only) version of this feature wrote its drafts to.\n * Kept solely as a one-shot migration source: anything found here is pushed up\n * to the server and the key is then removed, so a draft written against a\n * pre-server build is not silently orphaned. Never written to again.\n */\nexport const LEGACY_DRAFTS_KEY = 'wherever-drafts';\n\nexport interface Draft {\n\tid: string;\n\ttext: string;\n\tcreatedAt: number;\n\tupdatedAt: number;\n\t/** Session it was written in, if any. Display metadata only. */\n\tsessionId?: string;\n\t/** Working folder it was written in, if any. Display metadata only. */\n\tcwd?: string;\n}\n\n/** Newest-updated first, ties broken by id so the order is deterministic. */\nexport function sortDrafts(drafts: Draft[]): Draft[] {\n\treturn [...drafts].sort(\n\t\t(a, b) => b.updatedAt - a.updatedAt || a.id.localeCompare(b.id),\n\t);\n}\n\n/**\n * Tolerant parse of a stored/received list. A corrupt cache (or a response from\n * something that is not a wherever server) must never take the composer down, so\n * anything unparseable yields an empty list and a malformed member is dropped\n * rather than repaired.\n */\nexport function parseDrafts(raw: string | null | undefined): Draft[] {\n\tif (!raw) return [];\n\ttry {\n\t\treturn normalizeDrafts(JSON.parse(raw));\n\t} catch {\n\t\treturn [];\n\t}\n}\n\n/** Same tolerance, applied to an already-decoded value (an API response). */\nexport function normalizeDrafts(value: unknown): Draft[] {\n\tif (!Array.isArray(value)) return [];\n\tconst out: Draft[] = [];\n\tfor (const item of value) {\n\t\tif (!item || typeof item !== 'object') continue;\n\t\tconst d = item as Record<string, unknown>;\n\t\tif (typeof d.id !== 'string' || d.id.length === 0) continue;\n\t\tif (typeof d.text !== 'string') continue;\n\t\tconst text = d.text.trim();\n\t\tif (text.length === 0) continue;\n\t\tconst createdAt = typeof d.createdAt === 'number' ? d.createdAt : 0;\n\t\tconst updatedAt = typeof d.updatedAt === 'number' ? d.updatedAt : createdAt;\n\t\tout.push({\n\t\t\tid: d.id,\n\t\t\ttext,\n\t\t\tcreatedAt,\n\t\t\tupdatedAt,\n\t\t\t...(typeof d.sessionId === 'string' ? {sessionId: d.sessionId} : {}),\n\t\t\t...(typeof d.cwd === 'string' ? {cwd: d.cwd} : {}),\n\t\t});\n\t}\n\treturn sortDrafts(out);\n}\n\nexport function serializeDrafts(drafts: Draft[]): string {\n\treturn JSON.stringify(drafts);\n}\n\n/**\n * What loading a draft into the composer should do RIGHT NOW.\n *\n * `confirm` is the warning: the box already holds text the user has not sent,\n * and loading over it would silently destroy work. Whitespace is not work, so an\n * effectively empty box loads straight away.\n */\nexport function decideDraftLoad(currentText: string): 'load' | 'confirm' {\n\treturn currentText.trim().length > 0 ? 'confirm' : 'load';\n}\n\nexport type DraftLoadMode = 'replace' | 'append';\n\n/**\n * The composer text after loading `draftText` into `currentText`.\n *\n * `append` is the non-destructive way out of the warning: keep what was typed\n * AND take the draft, separated by a blank line.\n */\nexport function applyDraft(\n\tcurrentText: string,\n\tdraftText: string,\n\tmode: DraftLoadMode,\n): string {\n\tif (mode === 'replace') return draftText;\n\tconst current = currentText.replace(/\\s+$/, '');\n\tif (current.length === 0) return draftText;\n\treturn `${current}\\n\\n${draftText}`;\n}\n\n/**\n * Whether SENDING `sentText` consumes the draft that was loaded into the box.\n *\n * Mail-client semantics: loading a draft does NOT delete it (one mistap would\n * destroy the text with no undo), but actually SENDING it does -- an unsent\n * message that has now been sent is not a draft any more, and leaving it behind\n * turns the list into a pile of things the user already dealt with.\n *\n * The link is by CONTENT, not by a flag, and it matches EXACTLY the two shapes\n * applyDraft can produce: the draft alone (replace), or the draft as a SUFFIX\n * after typed text (append below). Deliberately not a substring test: a short\n * reusable prompt (\"run the tests\", \"continue\") would then be deleted whenever it\n * happened to appear inside an unrelated message sent later, which is the\n * data-losing direction. Anything else means the text was edited past the draft,\n * so the draft survives -- the safe side of a wrong guess.\n */\nexport function draftToConsumeOnSend(\n\tsource: {id: string; text: string} | null,\n\tsentText: string,\n): string | null {\n\tif (!source) return null;\n\tconst sent = sentText.trim();\n\tif (sent.length === 0) return null;\n\tconst draft = source.text.trim();\n\tif (draft.length === 0) return null;\n\treturn sent === draft || sent.endsWith(`\\n\\n${draft}`) ? source.id : null;\n}\n\n/**\n * One-line preview for the drafts list: whitespace/newlines collapsed so a\n * multi-line message stays one row, truncated with an ellipsis.\n */\nexport function draftPreview(text: string, max = 140): string {\n\tconst flat = text.replace(/\\s+/g, ' ').trim();\n\tif (flat.length <= max) return flat;\n\treturn `${flat.slice(0, max - 1).trimEnd()}…`;\n}\n\n/** Trailing folder name of a draft's origin cwd, for the list's context line. */\nexport function draftOriginLabel(draft: Draft): string | null {\n\tif (!draft.cwd) return null;\n\tconst parts = draft.cwd.split('/').filter(Boolean);\n\treturn parts.length > 0 ? parts[parts.length - 1] : draft.cwd;\n}\n","// On-device cache of recently viewed conversations (docs/adr/0013).\n//\n// Purpose: after the OS kills the PWA in the background, a reload has nothing to\n// show until the socket is up, the session is re-loaded and the history frame\n// has crossed a mobile link. This cache lets boot paint the last-seen\n// conversation immediately; the server's authoritative history then replaces it.\n// It is ONLY a cache: anything here may be missing, stale or evicted at any time,\n// and every caller must behave exactly as before when it is.\n//\n// Self-contained on purpose: the server identity arrives as a plain string (the\n// client's STAMPED `serverKey`, never re-derived here) and nothing at runtime\n// comes from `@wherever-dev/client` (the `ChatMessage` import is type-only).\n// Which events trigger a write, and which key to write under, are the caller's\n// decisions.\n//\n// Multi-tab: two tabs viewing the same session both write the same\n// `(serverKey, sessionId)` record and the LAST WRITE WINS. That is accepted\n// (spec story 12): a record is a hint for the first paint, overwritten by the\n// authoritative history either way, so a merge would buy nothing.\n\nimport type {ChatMessage} from '@wherever-dev/client';\n\n/** IndexedDB database name. One object store, `conversations`. */\nexport const CONVERSATION_CACHE_DB = 'wherever-conversation-cache';\nconst STORE = 'conversations';\nconst SAVED_AT_INDEX = 'savedAt';\nconst DB_VERSION = 1;\n\n/** Total sessions kept across ALL server keys (global LRU by `savedAt`). */\nexport const MAX_CACHED_SESSIONS = 5;\n/** Per-record budget in UTF-8 bytes of its JSON form. */\nexport const MAX_RECORD_BYTES = 2 * 1024 * 1024;\n/** Default coalescing interval for `createWriteThrottle`. */\nexport const WRITE_THROTTLE_MS = 5000;\n\nexport interface CachedConversation {\n\t/** Server identity the conversation was delivered by (the client's stamp). */\n\tserverKey: string;\n\tsessionId: string;\n\tsessionFile: string;\n\tcwd: string | null;\n\tmodel: string | null;\n\tmessages: ChatMessage[];\n\t/**\n\t * Paging state as last seen. Kept as-is even when the byte cap trims messages:\n\t * they only drive the \"Load older messages\" affordance, which the caller\n\t * gates on the authoritative history anyway.\n\t */\n\thistoryTotalCount: number;\n\thistoryOffset: number;\n\t/** ms epoch of the write; the LRU key. Stamped by `put`. */\n\tsavedAt: number;\n}\n\nexport type CachedConversationInput = Omit<CachedConversation, 'savedAt'>;\n\nexport interface ConversationCache {\n\tget(serverKey: string, sessionId: string): Promise<CachedConversation | null>;\n\t/** Normalize, trim to the byte cap, write, then enforce the session LRU. */\n\tput(record: CachedConversationInput): Promise<void>;\n\t/** Evict one record (e.g. a cached session the server refused to load). */\n\tremove(serverKey: string, sessionId: string): Promise<void>;\n\t/** Delete every record whose server key is not `serverKey`. */\n\tretainOnly(serverKey: string): Promise<void>;\n\t/** Delete everything (both Disconnect actions). */\n\tclear(): Promise<void>;\n}\n\n/**\n * What a cached message may contain. Applied at WRITE time so a record never\n * holds anything a hydrated view must not show:\n * - `delivery`-tagged user messages are dropped. Undelivered outbound messages\n * are recovered separately from localStorage (`loadPersistedPending`) and\n * re-tagged there; caching them too would double-surface them.\n * - `isStreaming` is forced to false: nothing is streaming in a page that just\n * booted, and a stale `true` would render a live spinner forever.\n * - tool images carrying base64 `data` are dropped: they dwarf the text, and the\n * authoritative history brings them back moments later. Images sent BY\n * REFERENCE (no `data`, just an address the browser fetches and caches) are\n * kept: they cost a few bytes and let the cached view show them offline-ish.\n * Returns new objects; the caller's (store-owned) messages are not mutated.\n */\nexport function normalizeMessages(\n\tmessages: readonly ChatMessage[],\n): ChatMessage[] {\n\tconst out: ChatMessage[] = [];\n\tfor (const m of messages) {\n\t\tif (m.delivery !== undefined) continue;\n\t\tconst {images, ...rest} = m;\n\t\tconst refs = images?.filter((i) => !i.data && i.toolCallId);\n\t\tout.push({\n\t\t\t...rest,\n\t\t\t...(refs && refs.length > 0 ? {images: refs} : {}),\n\t\t\tisStreaming: false,\n\t\t});\n\t}\n\treturn out;\n}\n\nfunction utf8Length(s: string): number {\n\tlet bytes = 0;\n\tfor (let i = 0; i < s.length; i++) {\n\t\tconst c = s.charCodeAt(i);\n\t\tif (c < 0x80) bytes += 1;\n\t\telse if (c < 0x800) bytes += 2;\n\t\telse if (c >= 0xd800 && c <= 0xdbff && i + 1 < s.length) {\n\t\t\t// A surrogate pair is one 4-byte code point.\n\t\t\tbytes += 4;\n\t\t\ti++;\n\t\t} else bytes += 3;\n\t}\n\treturn bytes;\n}\n\n/**\n * Drop the OLDEST messages until the record's JSON fits in `maxBytes` UTF-8\n * bytes. Each message is measured once, so a write while streaming costs one\n * serialization pass, not one per trimmed message. Offsets are not adjusted\n * (see `historyTotalCount`). May return zero messages; `put` treats that as\n * \"do not cache this session\".\n */\nexport function trimToByteCap<T extends {messages: ChatMessage[]}>(\n\trecord: T,\n\tmaxBytes: number,\n): T {\n\t// Size of the record with an empty array, then each message plus its comma.\n\tlet total = utf8Length(JSON.stringify({...record, messages: []}));\n\tconst sizes = record.messages.map((m) => utf8Length(JSON.stringify(m)));\n\tfor (let i = 0; i < sizes.length; i++) total += sizes[i] + (i > 0 ? 1 : 0);\n\tlet start = 0;\n\twhile (total > maxBytes && start < sizes.length) {\n\t\ttotal -= sizes[start] + (start < sizes.length - 1 ? 1 : 0);\n\t\tstart++;\n\t}\n\treturn start === 0\n\t\t? record\n\t\t: {...record, messages: record.messages.slice(start)};\n}\n\nfunction promisify<T>(req: IDBRequest<T>): Promise<T> {\n\treturn new Promise((resolve, reject) => {\n\t\treq.onsuccess = () => resolve(req.result);\n\t\treq.onerror = () => reject(req.error);\n\t});\n}\n\nfunction done(tx: IDBTransaction): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\ttx.oncomplete = () => resolve();\n\t\ttx.onerror = () => reject(tx.error);\n\t\ttx.onabort = () => reject(tx.error);\n\t});\n}\n\nexport interface ConversationCacheOptions {\n\t/**\n\t * The IndexedDB factory. Defaults to `globalThis.indexedDB`; `null` (or a\n\t * missing global) means \"no storage\", i.e. a disabled cache.\n\t */\n\tindexedDB?: IDBFactory | null;\n\tnow?: () => number;\n\tmaxSessions?: number;\n\tmaxRecordBytes?: number;\n}\n\n/**\n * Open the cache. The database is opened lazily on first use. If `open` throws\n * or fails (private mode, blocked storage, an old browser), the cache disables\n * itself for the rest of the page: every call resolves to a harmless no-op\n * (`get` -> null) and the open is not retried. A later per-operation failure\n * (quota, eviction mid-transaction) is swallowed the same way but does not\n * disable the cache. Nothing here ever throws or rejects to the caller.\n */\nexport function createConversationCache(\n\toptions: ConversationCacheOptions = {},\n): ConversationCache {\n\tconst factory =\n\t\toptions.indexedDB !== undefined\n\t\t\t? options.indexedDB\n\t\t\t: ((globalThis as {indexedDB?: IDBFactory}).indexedDB ?? null);\n\tconst now = options.now ?? Date.now;\n\tconst maxSessions = options.maxSessions ?? MAX_CACHED_SESSIONS;\n\tconst maxRecordBytes = options.maxRecordBytes ?? MAX_RECORD_BYTES;\n\n\tlet dbPromise: Promise<IDBDatabase | null> | null = null;\n\n\tfunction open(): Promise<IDBDatabase | null> {\n\t\tif (dbPromise) return dbPromise;\n\t\tdbPromise = new Promise<IDBDatabase | null>((resolve) => {\n\t\t\tif (!factory) return resolve(null);\n\t\t\tlet req: IDBOpenDBRequest;\n\t\t\ttry {\n\t\t\t\treq = factory.open(CONVERSATION_CACHE_DB, DB_VERSION);\n\t\t\t} catch {\n\t\t\t\treturn resolve(null);\n\t\t\t}\n\t\t\treq.onupgradeneeded = () => {\n\t\t\t\tconst store = req.result.createObjectStore(STORE, {\n\t\t\t\t\tkeyPath: ['serverKey', 'sessionId'],\n\t\t\t\t});\n\t\t\t\tstore.createIndex(SAVED_AT_INDEX, 'savedAt');\n\t\t\t};\n\t\t\treq.onsuccess = () => {\n\t\t\t\tconst db = req.result;\n\t\t\t\t// Another tab upgrading the schema: step aside rather than block it.\n\t\t\t\tdb.onversionchange = () => db.close();\n\t\t\t\tresolve(db);\n\t\t\t};\n\t\t\treq.onerror = () => resolve(null);\n\t\t\treq.onblocked = () => resolve(null);\n\t\t});\n\t\treturn dbPromise;\n\t}\n\n\t/** Run `fn` against the store; any failure (or a disabled cache) yields `fallback`. */\n\tasync function withStore<T>(\n\t\tmode: IDBTransactionMode,\n\t\tfallback: T,\n\t\tfn: (store: IDBObjectStore) => Promise<T>,\n\t): Promise<T> {\n\t\ttry {\n\t\t\tconst db = await open();\n\t\t\tif (!db) return fallback;\n\t\t\tconst tx = db.transaction(STORE, mode);\n\t\t\tconst completed = done(tx);\n\t\t\tconst result = await fn(tx.objectStore(STORE));\n\t\t\tawait completed;\n\t\t\treturn result;\n\t\t} catch {\n\t\t\treturn fallback;\n\t\t}\n\t}\n\n\t/** Delete every primary key `drop` selects, walking keys only (no values loaded). */\n\tfunction deleteKeysWhere(\n\t\tstore: IDBObjectStore,\n\t\tdrop: (key: IDBValidKey) => boolean,\n\t): Promise<void> {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst req = store.openKeyCursor();\n\t\t\treq.onerror = () => reject(req.error);\n\t\t\treq.onsuccess = () => {\n\t\t\t\tconst cursor = req.result;\n\t\t\t\tif (!cursor) return resolve();\n\t\t\t\tif (drop(cursor.primaryKey)) store.delete(cursor.primaryKey);\n\t\t\t\tcursor.continue();\n\t\t\t};\n\t\t});\n\t}\n\n\treturn {\n\t\tget(serverKey, sessionId) {\n\t\t\treturn withStore('readonly', null, async (store) => {\n\t\t\t\tconst value = (await promisify(store.get([serverKey, sessionId]))) as\n\t\t\t\t\t| CachedConversation\n\t\t\t\t\t| undefined;\n\t\t\t\treturn value ?? null;\n\t\t\t});\n\t\t},\n\n\t\tput(input) {\n\t\t\treturn withStore('readwrite', undefined, async (store) => {\n\t\t\t\tconst key = [input.serverKey, input.sessionId];\n\t\t\t\tconst record = trimToByteCap(\n\t\t\t\t\t{\n\t\t\t\t\t\t...input,\n\t\t\t\t\t\tmessages: normalizeMessages(input.messages),\n\t\t\t\t\t\tsavedAt: now(),\n\t\t\t\t\t},\n\t\t\t\t\tmaxRecordBytes,\n\t\t\t\t);\n\t\t\t\tif (record.messages.length === 0) {\n\t\t\t\t\t// Nothing fits (or nothing to show): an empty cached view would look\n\t\t\t\t\t// like an empty session, so cache nothing and drop any stale record.\n\t\t\t\t\tawait promisify(store.delete(key));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tawait promisify(store.put(record));\n\t\t\t\t// Global LRU: oldest `savedAt` first, keys only.\n\t\t\t\tconst keys = await promisify(store.index(SAVED_AT_INDEX).getAllKeys());\n\t\t\t\tfor (const old of keys.slice(\n\t\t\t\t\t0,\n\t\t\t\t\tMath.max(0, keys.length - maxSessions),\n\t\t\t\t)) {\n\t\t\t\t\tstore.delete(old);\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\n\t\tremove(serverKey, sessionId) {\n\t\t\treturn withStore('readwrite', undefined, async (store) => {\n\t\t\t\tawait promisify(store.delete([serverKey, sessionId]));\n\t\t\t});\n\t\t},\n\n\t\tretainOnly(serverKey) {\n\t\t\treturn withStore('readwrite', undefined, (store) =>\n\t\t\t\tdeleteKeysWhere(\n\t\t\t\t\tstore,\n\t\t\t\t\t(key) => (key as [string, string])[0] !== serverKey,\n\t\t\t\t),\n\t\t\t);\n\t\t},\n\n\t\tclear() {\n\t\t\treturn withStore('readwrite', undefined, async (store) => {\n\t\t\t\tawait promisify(store.clear());\n\t\t\t});\n\t\t},\n\t};\n}\n\nexport interface WriteThrottle {\n\t/** Note that a write is due; it happens at most once per interval. */\n\tschedule(): void;\n\t/** Write now and drop any pending throttled write. */\n\tflush(): void;\n\t/** Drop any pending throttled write without writing. */\n\tcancel(): void;\n}\n\n/**\n * Coalesce cache writes so a streaming reply costs at most one write per\n * `intervalMs`. `write` takes no arguments: it should snapshot the CURRENT state\n * when it runs, so the trailing write always carries the latest text. The first\n * `schedule()` arms a timer and later ones inside the window are absorbed\n * (trailing-edge only: the first write of a burst lands one interval in, which\n * is fine for a cache and keeps the write off the hot path of the first token).\n * `flush()` is for the caller's \"write now\" moments (history arrived, agent\n * ended, page hidden). A failing `write` is swallowed: a lost cache write must\n * never surface as an error.\n */\nexport function createWriteThrottle(\n\twrite: () => unknown,\n\toptions: {intervalMs?: number} = {},\n): WriteThrottle {\n\tconst intervalMs = options.intervalMs ?? WRITE_THROTTLE_MS;\n\tlet timer: ReturnType<typeof setTimeout> | null = null;\n\n\tfunction run() {\n\t\ttry {\n\t\t\tconst result = write();\n\t\t\tif (result && typeof (result as Promise<unknown>).catch === 'function') {\n\t\t\t\t(result as Promise<unknown>).catch(() => {});\n\t\t\t}\n\t\t} catch {\n\t\t\t// Swallowed: see above.\n\t\t}\n\t}\n\n\tfunction cancel() {\n\t\tif (timer !== null) clearTimeout(timer);\n\t\ttimer = null;\n\t}\n\n\treturn {\n\t\tschedule() {\n\t\t\tif (timer !== null) return;\n\t\t\ttimer = setTimeout(() => {\n\t\t\t\ttimer = null;\n\t\t\t\trun();\n\t\t\t}, intervalMs);\n\t\t},\n\t\tflush() {\n\t\t\tcancel();\n\t\t\trun();\n\t\t},\n\t\tcancel,\n\t};\n}\n","// Instant resume: the web-side decisions that wire the on-device conversation\n// cache (./conversation-cache.ts) to the client's hydration seam (docs/adr/0013).\n//\n// Pure on purpose, like `decideHashJoin` (./view-mode.ts): the web tests run in\n// a node environment with no DOM, so the cache, the client calls and the\n// window's location/history are all injected. `+page.svelte`,\n// `ConnectionSettings.svelte` and `wherever.ts` only call these.\n//\n// Decisions recorded here (see also CONTEXT.md \"Instant resume wiring\"):\n// - A snapshot is written ONLY under the client's stamped `serverKey` and ONLY\n// once the active session's history is authoritative. Before that the store\n// holds the cached copy itself (nothing new to save) or a rejoin in flight, so\n// skipping loses nothing and guarantees a record is never derived from a\n// view the server has not confirmed since the last write.\n// - The boot cache read is raced against a timeout and every failure is a\n// miss, so a slow or broken IndexedDB can delay boot by at most `timeoutMs`\n// and never stops it from connecting.\n// - While booting, a `pageshow` / `visibilitychange: visible` does NOT\n// connect: on a fresh load `pageshow` always fires, and its plain `connect()`\n// would reset the store under a hydration in progress. The flag clears as\n// soon as boot has ISSUED its own connect (not when the socket opens), so an\n// offline boot cannot hold the handlers off forever.\n\nimport type {ChatMessage} from '@wherever-dev/client';\nimport type {\n\tCachedConversation,\n\tCachedConversationInput,\n\tConversationCache,\n\tWriteThrottle,\n} from './conversation-cache';\n\n/** Default cap on how long boot waits for the cache read. */\nexport const BOOT_CACHE_TIMEOUT_MS = 300;\n\n/** The slice of the client's `WhereverState` the cache writes read. */\nexport interface ResumeStoreView {\n\tserverKey: string | null;\n\tsessionId: string | null;\n\tactiveSessionFile: string | null;\n\tactiveCwd: string | null;\n\tactiveModel: string | null;\n\tmessages: ChatMessage[];\n\thistoryTotalCount: number;\n\thistoryOffset: number;\n\thistoryAuthoritative: boolean;\n}\n\n/**\n * What to write to the cache for the current store, or null to write nothing.\n * The key is the STAMPED `serverKey`, never one derived from the current\n * settings (they can be edited without a reconnect, ADR 0013).\n */\nexport function cacheSnapshot(\n\ts: ResumeStoreView,\n): CachedConversationInput | null {\n\tif (!s.serverKey || !s.sessionId || !s.activeSessionFile) return null;\n\tif (!s.historyAuthoritative) return null;\n\tif (s.messages.length === 0) return null;\n\treturn {\n\t\tserverKey: s.serverKey,\n\t\tsessionId: s.sessionId,\n\t\tsessionFile: s.activeSessionFile,\n\t\tcwd: s.activeCwd,\n\t\tmodel: s.activeModel,\n\t\tmessages: s.messages,\n\t\thistoryTotalCount: s.historyTotalCount,\n\t\thistoryOffset: s.historyOffset,\n\t};\n}\n\n/**\n * \"Load older messages\" is offered only once the history is authoritative: a\n * hydrated (or rejoining) store's paging offset may be stale, and the client's\n * `loadMoreHistory()` is a no-op until then anyway.\n */\nexport function canLoadOlderHistory(s: {\n\thistoryOffset: number;\n\thistoryAuthoritative: boolean;\n}): boolean {\n\treturn s.historyAuthoritative && s.historyOffset > 0;\n}\n\n/**\n * What a return to the page (`visibilitychange: visible`, `pageshow`) should do\n * after its `noteVisible()` probe. `none` while booting (see the module note),\n * and when already connected.\n */\nexport function decideReturn(i: {\n\tbooting: boolean;\n\tconnected: boolean;\n\thasActiveSession: boolean;\n}): 'none' | 'resume' | 'connect' {\n\tif (i.booting || i.connected) return 'none';\n\treturn i.hasActiveSession ? 'resume' : 'connect';\n}\n\n/**\n * Read the cached record for the session the URL hash names, for boot. Resolves\n * null on no hash, a miss, a record that does not match, a failure, or after\n * `timeoutMs`. Never rejects.\n */\nexport function readBootCache(i: {\n\tcache: ConversationCache;\n\tserverKey: string;\n\thashId: string;\n\ttimeoutMs?: number;\n}): Promise<CachedConversation | null> {\n\tif (!i.hashId) return Promise.resolve(null);\n\tconst timeoutMs = i.timeoutMs ?? BOOT_CACHE_TIMEOUT_MS;\n\treturn new Promise((resolve) => {\n\t\tconst timer = setTimeout(() => resolve(null), timeoutMs);\n\t\tconst settle = (r: CachedConversation | null) => {\n\t\t\tclearTimeout(timer);\n\t\t\tresolve(r);\n\t\t};\n\t\tlet read: Promise<CachedConversation | null>;\n\t\ttry {\n\t\t\tread = i.cache.get(i.serverKey, i.hashId);\n\t\t} catch {\n\t\t\treturn settle(null);\n\t\t}\n\t\tread.then(\n\t\t\t(r) =>\n\t\t\t\tsettle(\n\t\t\t\t\tr && r.sessionId === i.hashId && r.serverKey === i.serverKey\n\t\t\t\t\t\t? r\n\t\t\t\t\t\t: null,\n\t\t\t\t),\n\t\t\t() => settle(null),\n\t\t);\n\t});\n}\n\n/**\n * Boot: on a cache hit hydrate the client and connect PRESERVING the store, so\n * the conversation is on screen before the socket opens and the rejoin\n * replaces it. On a miss (or if the client refused / failed to hydrate),\n * connect exactly as before. `connect` is called exactly once, always.\n * `hydrate` returns whether the record is now in the store.\n */\nexport async function runBoot(deps: {\n\tcached: Promise<CachedConversation | null>;\n\thydrate: (record: CachedConversation) => boolean;\n\tconnect: (opts: {preserveState: boolean}) => void;\n}): Promise<'hydrated' | 'plain'> {\n\tlet hydrated = false;\n\ttry {\n\t\tconst record = await deps.cached;\n\t\tif (record) hydrated = deps.hydrate(record);\n\t} catch {\n\t\thydrated = false;\n\t}\n\tdeps.connect({preserveState: hydrated});\n\treturn hydrated ? 'hydrated' : 'plain';\n}\n\n/**\n * Every connect keeps only the server it connects to. Reconnect and a\n * same-server Connect therefore keep everything; connecting to another server\n * drops the previous one's conversations (ADR 0013, story 7).\n */\nexport function retainCurrentServer(\n\tcache: ConversationCache,\n\tserverKey: string,\n): Promise<void> {\n\treturn cache.retainOnly(serverKey);\n}\n\n/**\n * Both Disconnect actions wipe the cache. ONLY those two handlers call this,\n * never the shared `disconnect()`: Connect and Reconnect call `disconnect()`\n * before `connect()`, and wiping there would lose the cache they must keep.\n * A pending throttled write is dropped first so it cannot re-create a record.\n */\nexport function clearCacheOnDisconnect(\n\tcache: ConversationCache,\n\tthrottle: WriteThrottle | null,\n): Promise<void> {\n\tthrottle?.cancel();\n\treturn cache.clear();\n}\n\nexport interface HashWindow {\n\tlocation: {hash: string; pathname: string; search: string};\n\thistory: {\n\t\tstate: unknown;\n\t\treplaceState(data: unknown, unused: string, url?: string | null): void;\n\t};\n}\n\n/**\n * The server refused the hydrated session's load (`hydration_rejected`). Clear\n * the hash FIRST and SYNCHRONOUSLY with `replaceState`: the page's hash effect\n * would otherwise clear it with `location.hash = ''` (a history entry, so Back\n * returns to the dead session), and a lingering hash would drive the auto-join\n * into re-joining it. Only a hash naming the rejected session is cleared. Then\n * evict the record under the key it was hydrated from.\n */\nexport function handleHydrationRejected(i: {\n\tsessionId: string;\n\tserverKey: string | null;\n\twin: HashWindow | null;\n\tcache: ConversationCache;\n}): void {\n\tconst w = i.win;\n\tif (w && w.location.hash) {\n\t\tlet hashId = '';\n\t\ttry {\n\t\t\thashId = decodeURIComponent(w.location.hash.slice(1));\n\t\t} catch {\n\t\t\thashId = w.location.hash.slice(1);\n\t\t}\n\t\tif (hashId === i.sessionId) {\n\t\t\tw.history.replaceState(\n\t\t\t\tw.history.state,\n\t\t\t\t'',\n\t\t\t\tw.location.pathname + w.location.search,\n\t\t\t);\n\t\t}\n\t}\n\tif (i.serverKey) void i.cache.remove(i.serverKey, i.sessionId);\n}\n","import {derived, get, writable} from 'svelte/store';\nimport {playInvitingBeep} from './core/beep';\nimport {\n\tWhereverClient,\n\tparseSkillInvocation,\n\tserverKey,\n\ttype ChatMessage,\n\ttype ToolImage,\n\ttype UploadByteSource,\n\ttype UploadProgress,\n\ttype WhereverState,\n} from '@wherever-dev/client';\nimport {\n\tresolveConversationMode,\n\tshouldSignalConversationMode,\n} from './core/conversation-mode';\nimport {buildAttachmentMessage} from './core/attachments';\nimport {shouldDropStaleHash} from './core/view-mode';\nimport {fileStillReadable, postUpload} from './core/post-upload';\nimport {adoptTokenFromUrlOnce} from './core/token-adoption';\nimport {timezoneReportFrame} from './core/timezone-report';\nimport {normalizeDrafts, type Draft} from './core/drafts';\nimport {\n\tcreateConversationCache,\n\tcreateWriteThrottle,\n\ttype CachedConversation,\n} from './core/conversation-cache';\nimport {\n\tcacheSnapshot,\n\tcanLoadOlderHistory,\n\tclearCacheOnDisconnect,\n\thandleHydrationRejected,\n\treadBootCache,\n\tretainCurrentServer,\n} from './core/instant-resume';\nimport {\n\tsetCurrentSession,\n\tgetBaseUrl,\n\tgetToken,\n\tuploadMethodStore,\n\tfetchSessions,\n\tsetSessionWorking,\n\tsearchFolderStore,\n\tsearchCreateRemoteStore,\n\tapplyAssistantPointer,\n} from './session-store';\n\nexport type {ChatMessage, WhereverState};\nexport {parseSkillInvocation};\n\nfunction getStoredConfig() {\n\ttry {\n\t\tconst stored = localStorage.getItem('wherever-config');\n\t\tif (stored) return JSON.parse(stored);\n\t} catch {}\n\treturn null;\n}\n\nfunction saveConfig(config: {\n\thost: string;\n\tport: number;\n\ttoken: string;\n\thideThinking?: boolean;\n\thideTools?: boolean;\n\tbeepDefault?: boolean;\n\tbeepSoundUrl?: string;\n\tconversationMode?: boolean;\n\tspeakReplies?: boolean;\n\tcollapseLongReplies?: boolean;\n\tmicReopensAfterReply?: boolean;\n}) {\n\tlocalStorage.setItem('wherever-config', JSON.stringify(config));\n}\n\n// The port to use when the user has NOT explicitly configured one. When the\n// dashboard is served from a real origin (e.g. behind a reverse proxy like\n// Caddy on 443, or any host:port), connect back to THAT origin's port instead\n// of assuming the dev default 31415. This makes reverse-proxy deployments\n// (https://host with no port in the URL) work without the user having to know\n// to type \"443\" into the port field. A direct LAN setup on http://ip:31415\n// still resolves to 31415 because that is the page's own port. Falls back to\n// 31415 only when there is no window (SSR) or no usable location port.\nfunction defaultPort(): number {\n\tif (typeof window !== 'undefined' && window.location) {\n\t\tconst loc = window.location;\n\t\tif (loc.port) return Number(loc.port);\n\t\t// No explicit port in the URL => standard port for the scheme.\n\t\tif (loc.protocol === 'https:') return 443;\n\t\tif (loc.protocol === 'http:') return 80;\n\t}\n\treturn 31415;\n}\n\nexport function getConfig() {\n\t// Before anything reads the stored config, let a token supplied in the page\n\t// URL (`#token=...`, or a legacy `?token=...`) be merged into it. This runs\n\t// HERE rather than in a layout hook because getConfig() is itself called at\n\t// module scope below, which is earlier than any component lifecycle. It is\n\t// idempotent, so calling it on every read costs nothing.\n\tadoptTokenFromUrlOnce();\n\n\tconst defaultHost =\n\t\ttypeof window !== 'undefined' && window.location && window.location.hostname\n\t\t\t? window.location.hostname\n\t\t\t: 'localhost';\n\n\tconst stored = getStoredConfig();\n\tif (stored) {\n\t\t// A config written by token adoption alone (fresh browser, link with a\n\t\t// token) carries no port, and the legacy healing below only assigns one\n\t\t// when the page port differs from 31415. Fill it in first so the returned\n\t\t// config always has a usable port.\n\t\tif (stored.port === undefined) {\n\t\t\tstored.port = defaultPort();\n\t\t}\n\t\t// Legacy port healing: a config stored before reverse-proxy support has\n\t\t// port 31415 baked in. If the dashboard is actually served from a\n\t\t// different origin port (e.g. 443 behind Caddy), that stale 31415 makes\n\t\t// the client dial a closed port and hang on \"Connecting...\". When the\n\t\t// stored port is the legacy default AND the page's own port differs,\n\t\t// adopt the page's port so proxied deployments just work.\n\t\tif (\n\t\t\t(stored.port === 31415 || stored.port === undefined) &&\n\t\t\tdefaultPort() !== 31415\n\t\t) {\n\t\t\tstored.port = defaultPort();\n\t\t}\n\t\tif (\n\t\t\t!stored.host ||\n\t\t\tstored.host === 'localhost' ||\n\t\t\tstored.host === '127.0.0.1'\n\t\t) {\n\t\t\tif (\n\t\t\t\tdefaultHost &&\n\t\t\t\tdefaultHost !== 'localhost' &&\n\t\t\t\tdefaultHost !== '127.0.0.1'\n\t\t\t) {\n\t\t\t\treturn {\n\t\t\t\t\thideThinking: false,\n\t\t\t\t\thideTools: false,\n\t\t\t\t\t...stored,\n\t\t\t\t\thost: defaultHost,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t\tif (!stored.host) {\n\t\t\tstored.host = defaultHost;\n\t\t}\n\t\treturn {\n\t\t\thideThinking: false,\n\t\t\thideTools: false,\n\t\t\tbeepDefault: false,\n\t\t\tbeepSoundUrl: '',\n\t\t\tconversationMode: false,\n\t\t\tspeakReplies: false,\n\t\t\tcollapseLongReplies: false,\n\t\t\tmicReopensAfterReply: false,\n\t\t\t...stored,\n\t\t};\n\t}\n\treturn {\n\t\thost: defaultHost,\n\t\tport: defaultPort(),\n\t\ttoken: '',\n\t\thideThinking: false,\n\t\thideTools: false,\n\t\tbeepDefault: false,\n\t\tbeepSoundUrl: '',\n\t\tconversationMode: false,\n\t\tspeakReplies: false,\n\t\tcollapseLongReplies: false,\n\t\tmicReopensAfterReply: false,\n\t};\n}\n\n// --- Waiting-for-human beep ------------------------------------------------\n// The beep is DISABLED by default. A persisted config flag (beepDefault) sets\n// the default for EVERY session. Each session can additionally hold its OWN\n// explicit choice (a per-session override) that wins over the default.\n//\n// Key semantics (\"unset\" is a real, distinct state):\n// - A session with NO override \"follows the default\": change the default and\n// this session's effective beep state changes with it, live.\n// - Once the user explicitly sets the per-session control (on/off), that\n// choice STICKS to that session and is unaffected by later default changes,\n// until the user clears it back to \"follow default\".\n//\n// Overrides are therefore stored PER SESSION (keyed by the session id/file) and\n// persisted, so a choice made in session A survives visiting session B and\n// coming back, and survives a reload. Absence of a key = \"follow default\".\nconst beepDefaultStore = writable<boolean>(!!getConfig().beepDefault);\n\n// Map<sessionKey, boolean> of explicit per-session choices, persisted to\n// localStorage. A missing key means the session follows the default.\nconst BEEP_OVERRIDES_KEY = 'wherever-beep-overrides';\n\nfunction loadBeepOverrides(): Record<string, boolean> {\n\ttry {\n\t\tconst raw = localStorage.getItem(BEEP_OVERRIDES_KEY);\n\t\tif (raw) {\n\t\t\tconst parsed = JSON.parse(raw);\n\t\t\tif (parsed && typeof parsed === 'object') return parsed;\n\t\t}\n\t} catch {}\n\treturn {};\n}\n\nfunction saveBeepOverrides(map: Record<string, boolean>) {\n\ttry {\n\t\tlocalStorage.setItem(BEEP_OVERRIDES_KEY, JSON.stringify(map));\n\t} catch {}\n}\n\nconst beepOverridesStore = writable<Record<string, boolean>>(\n\ttypeof localStorage !== 'undefined' ? loadBeepOverrides() : {},\n);\n// The active session's key ('' when no session). Drives which override applies.\nconst beepSessionKeyStore = writable<string>('');\n\nexport function getBeepDefault(): boolean {\n\treturn get(beepDefaultStore);\n}\n\n// Optional custom sound file/URL to play instead of the synthesized chime.\n// Empty string means \"use the built-in chime\".\nexport function getBeepSoundUrl(): string {\n\tconst url = getConfig().beepSoundUrl;\n\treturn typeof url === 'string' ? url : '';\n}\n\n// Persist the custom beep sound URL (empty string clears it, reverting to the\n// built-in chime).\nexport function setBeepSoundUrl(value: string) {\n\tconst config = getConfig();\n\tsaveConfig({...config, beepSoundUrl: value});\n}\n\n// The current session's explicit choice, or undefined when it follows the\n// default. Tri-state: true | false | undefined. Lets the UI signal \"not set\".\nexport const beepSessionOverride = derived(\n\t[beepSessionKeyStore, beepOverridesStore],\n\t([$key, $overrides]) =>\n\t\t$key && $key in $overrides ? $overrides[$key] : undefined,\n);\n\n// True when the beep should sound for the current session: the per-session\n// override if the session set one, otherwise the persisted default. Recomputes\n// when the session, its override, or the default changes.\nexport const beepEnabled = derived(\n\t[beepSessionOverride, beepDefaultStore],\n\t([$override, $default]) => ($override === undefined ? $default : $override),\n);\n\n// Set (or clear) the beep default that applies to all sessions. Persists to\n// config AND updates the reactive default store so beepEnabled recomputes.\nexport function setBeepDefault(value: boolean) {\n\tconst config = getConfig();\n\tsaveConfig({...config, beepDefault: value});\n\tbeepDefaultStore.set(value);\n}\n\n// Set this session's explicit choice (true/false), or pass undefined to CLEAR\n// it back to \"follow the default\". Persisted per session.\nexport function setBeepSessionOverride(value: boolean | undefined) {\n\tconst key = get(beepSessionKeyStore);\n\tif (!key) return; // no active session to attach the choice to\n\tbeepOverridesStore.update((map) => {\n\t\tconst next = {...map};\n\t\tif (value === undefined) {\n\t\t\tdelete next[key];\n\t\t} else {\n\t\t\tnext[key] = value;\n\t\t}\n\t\tsaveBeepOverrides(next);\n\t\treturn next;\n\t});\n}\n\n// Point the beep state at a session (its id/file). Called when the active\n// session changes. Does NOT clear any stored per-session choice: an unset\n// session follows the default; a session with a stored choice keeps it.\nexport function setBeepSessionKey(key: string | null) {\n\tbeepSessionKeyStore.set(key ?? '');\n}\n\n// --- Conversation mode knobs ------------------------------------------------\n// Conversation mode is a saved PRESET over a set of independent boolean knobs\n// (see core/conversation-mode.ts for the registry + gating logic). This block\n// is the persistence + reactive-store wiring, mirroring the beepDefault pattern:\n// each knob has exactly ONE canonical localStorage home.\n//\n// - autoSendOnSpeechEnd IS the pre-existing directSend flag, so it reuses the\n// `wherever-speech-direct-send` key (NOT a forked second flag) and stays the\n// SAME underlying value SpeechButton reads/writes. It is therefore NOT gated\n// by the master toggle (story 14): a standalone-set directSend still\n// auto-sends with conversation mode off.\n// - conversationMode (the master) + the purely-conversation knobs\n// (speakReplies, collapseLongReplies, micReopensAfterReply) live as boolean\n// fields in the single `wherever-config` entry via getConfig()/saveConfig().\nconst DIRECT_SEND_KEY = 'wherever-speech-direct-send';\n\nfunction readDirectSend(): boolean {\n\ttry {\n\t\treturn localStorage.getItem(DIRECT_SEND_KEY) === 'true';\n\t} catch {}\n\treturn false;\n}\n\n// autoSendOnSpeechEnd === directSend. Reflected here so a change made in either\n// this store or SpeechButton is observable from the same single key.\nexport const autoSendOnSpeechEnd = writable<boolean>(\n\ttypeof localStorage !== 'undefined' ? readDirectSend() : false,\n);\n\nexport function getAutoSendOnSpeechEnd(): boolean {\n\treturn readDirectSend();\n}\n\nexport function setAutoSendOnSpeechEnd(value: boolean) {\n\ttry {\n\t\tlocalStorage.setItem(DIRECT_SEND_KEY, String(value));\n\t} catch {}\n\tautoSendOnSpeechEnd.set(value);\n}\n\n// --- The master toggle: PER CONVERSATION, over a global default -------------\n// A spoken exchange is a property of the CONVERSATION you are having, not of the\n// app: turning conversation mode on in the bar while talking to one session must\n// not start speaking replies in every other session (nor stamp the per-turn\n// conversation-mode signal on messages sent from them). So this mirrors the\n// waiting-for-human beep exactly: a persisted config flag is the DEFAULT for\n// every conversation, and each session may hold its OWN explicit choice that\n// wins over it. Absence of a per-session key = \"follow the default\", live.\n//\n// Only WHETHER a conversation is spoken is per conversation. The gated knobs\n// (speakReplies, collapseLongReplies, micReopensAfterReply) describe HOW a spoken\n// conversation behaves and stay GLOBAL settings.\nconst conversationModeDefaultStore = writable<boolean>(\n\t!!getConfig().conversationMode,\n);\n\nconst CONVERSATION_MODE_OVERRIDES_KEY = 'wherever-conversation-mode-overrides';\n\nfunction loadConversationModeOverrides(): Record<string, boolean> {\n\ttry {\n\t\tconst raw = localStorage.getItem(CONVERSATION_MODE_OVERRIDES_KEY);\n\t\tif (raw) {\n\t\t\tconst parsed = JSON.parse(raw);\n\t\t\tif (parsed && typeof parsed === 'object') return parsed;\n\t\t}\n\t} catch {}\n\treturn {};\n}\n\nfunction saveConversationModeOverrides(map: Record<string, boolean>) {\n\ttry {\n\t\tlocalStorage.setItem(CONVERSATION_MODE_OVERRIDES_KEY, JSON.stringify(map));\n\t} catch {}\n}\n\nconst conversationModeOverridesStore = writable<Record<string, boolean>>(\n\ttypeof localStorage !== 'undefined' ? loadConversationModeOverrides() : {},\n);\n// The active session's key ('' when no session). Drives which override applies.\nconst conversationModeSessionKeyStore = writable<string>('');\n\n// This session's explicit choice, or undefined when it follows the default.\n// Tri-state: true | false | undefined, so the UI can signal \"not set\".\nexport const conversationModeSessionOverride = derived(\n\t[conversationModeSessionKeyStore, conversationModeOverridesStore],\n\t([$key, $overrides]) =>\n\t\t$key && $key in $overrides ? $overrides[$key] : undefined,\n);\n\nexport const conversationModeDefault = {\n\tsubscribe: conversationModeDefaultStore.subscribe,\n};\n\nconst speakRepliesStore = writable<boolean>(!!getConfig().speakReplies);\nconst collapseLongRepliesStore = writable<boolean>(\n\t!!getConfig().collapseLongReplies,\n);\nconst micReopensAfterReplyStore = writable<boolean>(\n\t!!getConfig().micReopensAfterReply,\n);\n\n// The EFFECTIVE master for the conversation being viewed: this session's own\n// choice if it made one, otherwise the default. Recomputes when the session, its\n// override, or the default changes.\nexport const conversationMode = derived(\n\t[conversationModeSessionOverride, conversationModeDefaultStore],\n\t([$override, $default]) => resolveConversationMode($override, $default),\n);\nexport const speakReplies = {subscribe: speakRepliesStore.subscribe};\nexport const collapseLongReplies = {\n\tsubscribe: collapseLongRepliesStore.subscribe,\n};\nexport const micReopensAfterReply = {\n\tsubscribe: micReopensAfterReplyStore.subscribe,\n};\n\n// The effective master for the CURRENT conversation (override, else default).\nexport function getConversationMode(): boolean {\n\treturn get(conversationMode);\n}\n\nexport function getConversationModeDefault(): boolean {\n\treturn get(conversationModeDefaultStore);\n}\n\n// Set the DEFAULT master for conversations that have not been toggled. Persists\n// to config AND updates the reactive store, so every session still following the\n// default flips with it, live.\n//\n// This does NOT force the purely-conversation knobs on/off: they keep their\n// configured values and become active only while the master is on (the gating\n// lives in isKnobActive; see core/conversation-mode.ts). It also does NOT touch\n// autoSendOnSpeechEnd (= directSend), whose standalone effect must survive the\n// master being off.\nexport function setConversationModeDefault(value: boolean) {\n\tconst config = getConfig();\n\tsaveConfig({...config, conversationMode: value});\n\tconversationModeDefaultStore.set(value);\n}\n\n// Set THIS conversation's explicit choice (true/false), or pass undefined to\n// CLEAR it back to \"follow the default\". Persisted per session, so a choice made\n// in conversation A survives visiting B and coming back, and survives a reload.\nexport function setConversationModeSessionOverride(value: boolean | undefined) {\n\tconst key = get(conversationModeSessionKeyStore);\n\tif (!key) return; // no active session to attach the choice to\n\tconversationModeOverridesStore.update((map) => {\n\t\tconst next = {...map};\n\t\tif (value === undefined) {\n\t\t\tdelete next[key];\n\t\t} else {\n\t\t\tnext[key] = value;\n\t\t}\n\t\tsaveConversationModeOverrides(next);\n\t\treturn next;\n\t});\n}\n\n// Point the conversation-mode state at a session (its id/file). Called when the\n// active session changes. Does NOT clear any stored per-session choice: an unset\n// session follows the default; a session with a stored choice keeps it.\nexport function setConversationModeSessionKey(key: string | null) {\n\tconversationModeSessionKeyStore.set(key ?? '');\n}\n\nexport function setSpeakReplies(value: boolean) {\n\tconst config = getConfig();\n\tsaveConfig({...config, speakReplies: value});\n\tspeakRepliesStore.set(value);\n}\n\nexport function setCollapseLongReplies(value: boolean) {\n\tconst config = getConfig();\n\tsaveConfig({...config, collapseLongReplies: value});\n\tcollapseLongRepliesStore.set(value);\n}\n\nexport function setMicReopensAfterReply(value: boolean) {\n\tconst config = getConfig();\n\tsaveConfig({...config, micReopensAfterReply: value});\n\tmicReopensAfterReplyStore.set(value);\n}\n\n// The whole knob bundle as a plain object, for isKnobActive()/bundleOn() from\n// core/conversation-mode.ts.\nexport function getConversationKnobs(): {\n\tconversationMode: boolean;\n\tautoSendOnSpeechEnd: boolean;\n\tspeakReplies: boolean;\n\tcollapseLongReplies: boolean;\n\tmicReopensAfterReply: boolean;\n} {\n\treturn {\n\t\tconversationMode: getConversationMode(),\n\t\tautoSendOnSpeechEnd: getAutoSendOnSpeechEnd(),\n\t\tspeakReplies: get(speakRepliesStore),\n\t\tcollapseLongReplies: get(collapseLongRepliesStore),\n\t\tmicReopensAfterReply: get(micReopensAfterReplyStore),\n\t};\n}\n\n// Flip the master ON (bundling in the configured knobs) or OFF FOR THE\n// CONVERSATION BEING VIEWED. Mirrors bundleOn() from core/conversation-mode.ts:\n// turning it off dormant-izes the gated knobs but does NOT force\n// autoSendOnSpeechEnd off. This is what the top-bar toggle calls, so it writes\n// this session's own choice and never moves the global default (which lives in\n// Connection Settings as \"default for new conversations\").\nexport function setConversationModeBundle(on: boolean) {\n\tif (get(conversationModeSessionKeyStore)) {\n\t\tsetConversationModeSessionOverride(on);\n\t\treturn;\n\t}\n\t// No conversation is open, so there is nothing to scope the choice TO: the\n\t// only thing the user can mean is the default. This also keeps the toggle from\n\t// silently doing nothing on the empty state.\n\tsetConversationModeDefault(on);\n}\n\n// Per-send options for every outbound user message: stamp the PER-TURN\n// conversation-mode signal from the knobs as they are right now (the mode can be\n// flipped mid-session, and the master is per CONVERSATION, so this reads the\n// session being viewed). This is the only place the web decides it, so send and\n// resend can never disagree. With the mode (or speakReplies) off the flag is\n// false and the client omits the field entirely, leaving today's behaviour intact.\nfunction sendOptions(): {conversationMode: boolean} {\n\treturn {\n\t\tconversationMode: shouldSignalConversationMode(getConversationKnobs()),\n\t};\n}\n\n// Stable identity for THIS TAB, carried across reconnects and across reloads of\n// the same tab. sessionStorage (not localStorage) is deliberate: every tab is a\n// genuinely distinct viewer and must keep its own key, otherwise opening a\n// second tab would kick the first one off. The server uses this key to retire\n// this tab's own superseded connection instead of counting a phantom (silently\n// dropped) socket as a second viewer, which used to turn an explicit \"New\n// Session Here\" into a read-only folder conflict.\nconst CLIENT_KEY_STORAGE = 'wherever-client-key';\n\nfunction getClientKey(): string | undefined {\n\tif (typeof sessionStorage === 'undefined') return undefined;\n\ttry {\n\t\tconst existing = sessionStorage.getItem(CLIENT_KEY_STORAGE);\n\t\tif (existing) return existing;\n\t\tconst key = `tab-${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`;\n\t\tsessionStorage.setItem(CLIENT_KEY_STORAGE, key);\n\t\treturn key;\n\t} catch {\n\t\t// Private-mode / blocked storage: fall back to the client's per-instance\n\t\t// key, which still covers in-page reconnects.\n\t\treturn undefined;\n\t}\n}\n\n// \"Duplicate tab\" CLONES sessionStorage, so two live tabs can start out sharing\n// one key. The server then treats the second as the first's reconnect and\n// retires it, which would ping-pong forever. It tells the retired (but alive)\n// connection so the client can take a fresh key: persist it here so the\n// collision is resolved once, not re-created on the next reconnect.\nfunction persistClientKey(key: string): void {\n\ttry {\n\t\tsessionStorage.setItem(CLIENT_KEY_STORAGE, key);\n\t} catch {\n\t\t// Storage unavailable: the in-memory key still resolves the collision for\n\t\t// this page's lifetime.\n\t}\n}\n\n// Instantiate the isomorphic WhereverClient\nconst initialConfig = getConfig();\nexport const client = new WhereverClient({\n\thost: initialConfig.host,\n\tport: initialConfig.port,\n\ttoken: initialConfig.token,\n\tclientKey: getClientKey(),\n\tonClientKeyChange: persistClientKey,\n\tsecure:\n\t\ttypeof window !== 'undefined' &&\n\t\twindow.location &&\n\t\twindow.location.protocol === 'https:',\n\thideThinking: !!initialConfig.hideThinking,\n\thideTools: !!initialConfig.hideTools,\n\t// Large history images come by reference; `toolImageSrc` loads them.\n\timageRefs: true,\n});\n\nexport const state = client.stateStore;\n\n// --- On-device conversation cache (docs/adr/0013) ---------------------------\n// Lets a reload after the OS killed the PWA paint the last-seen conversation\n// before the socket is up. Every decision lives in core/instant-resume.ts; this\n// block only wires it to the client. The cache disables itself (every call a\n// no-op) where IndexedDB is unusable, so nothing here can fail loudly.\nconst conversationCache = createConversationCache();\n\n// Writes snapshot the CURRENT store when they run, under its STAMPED key and\n// only once the history is authoritative (cacheSnapshot decides). Streaming is\n// coalesced to one write per ~5 s; the other triggers flush at once.\nconst cacheWrites = createWriteThrottle(() => {\n\tconst snap = cacheSnapshot(get(state));\n\treturn snap ? conversationCache.put(snap) : undefined;\n});\n\n// The key the current hydration came from, so a `hydration_rejected` can evict\n// that record (the client has already cleared the stamp when it fires).\nlet hydratedServerKey: string | null = null;\n\nfunction currentServerKey(): string {\n\tconst config = getConfig();\n\treturn serverKey({host: config.host, port: config.port, token: config.token});\n}\n\n// Throttled writes while a reply streams: one per changed message list.\nlet prevCachedMessages: unknown = null;\nstate.subscribe((s) => {\n\tif (s.messages === prevCachedMessages) return;\n\tprevCachedMessages = s.messages;\n\tif (s.isStreaming) cacheWrites.schedule();\n});\n\n/** Write the active conversation now (page hidden, pagehide). */\nexport function flushConversationCache() {\n\tcacheWrites.flush();\n}\n\n/**\n * Both Disconnect actions (and ONLY those): wipe the cache. Never called from\n * the shared disconnect(), which Connect and Reconnect also use.\n */\nexport function clearConversationCache() {\n\tvoid clearCacheOnDisconnect(conversationCache, cacheWrites);\n}\n\n/** Boot: the cached record for the hash session under the current key, or null. */\nexport function readBootConversation(\n\thashId: string,\n): Promise<CachedConversation | null> {\n\treturn readBootCache({\n\t\tcache: conversationCache,\n\t\tserverKey: currentServerKey(),\n\t\thashId,\n\t});\n}\n\n/**\n * Paint a cached record into the client store. Returns whether it took (the\n * client ignores it when a session is already active, loading or connected).\n */\nexport function hydrateFromCache(record: CachedConversation): boolean {\n\tclient.hydrateCachedSession(record);\n\tconst took = get(state).activeSessionFile === record.sessionFile;\n\tif (took) hydratedServerKey = record.serverKey;\n\treturn took;\n}\n\n// --- Waiting-for-human beep trigger ----------------------------------------\n// Watch the streaming flag and sound the inviting chime on the true -> false\n// edge, i.e. the moment the agent stops working and is waiting for a human\n// message. Gated by beepEnabled (per-session override or the persisted\n// default). Also point the beep state at the active session when it changes, so\n// beepEnabled reflects THAT session's stored choice (or the default if unset).\nlet prevIsStreaming = false;\nlet prevSessionKey: string | null = null;\nstate.subscribe((s) => {\n\tconst sessionKey = s.sessionId ?? s.activeSessionFile ?? null;\n\tif (sessionKey !== prevSessionKey) {\n\t\tprevSessionKey = sessionKey;\n\t\t// New/changed session: retarget the per-session state (the beep AND the\n\t\t// conversation-mode master, both of which resolve to that session's stored\n\t\t// choice if it made one, else the default) and do not treat the session's\n\t\t// initial streaming state as a finished-turn edge.\n\t\tsetBeepSessionKey(sessionKey);\n\t\tsetConversationModeSessionKey(sessionKey);\n\t\tprevIsStreaming = s.isStreaming;\n\t\treturn;\n\t}\n\tif (prevIsStreaming && !s.isStreaming) {\n\t\t// Only chime for a real session with a transcript, not for a bare\n\t\t// disconnect/leave that also drops isStreaming to false.\n\t\tif (sessionKey && get(beepEnabled)) {\n\t\t\tplayInvitingBeep(getBeepSoundUrl());\n\t\t}\n\t}\n\tprevIsStreaming = s.isStreaming;\n});\n\n// When runSearch() creates a session, hold the query (and any files attached to\n// it) here until the matching session_created arrives, then send it as the first\n// message of that session.\n// Files cannot be uploaded before that point: an upload is attributed to a\n// session (it decides the upload dir), and in search mode the session does not\n// exist yet. So the browser keeps the File objects and the upload happens in\n// deliverPendingSearch(), between session creation and the first message.\ntype PendingSearch = {query: string; files: File[]};\nlet pendingSearch: PendingSearch | null = null;\n\n/**\n * Send a held search query as the first message of the freshly created session,\n * uploading its attachments first so their server paths can be referenced.\n *\n * Upload failures never swallow the search: the query still goes out with\n * whatever uploaded, and the failures are surfaced as a session error.\n */\nasync function deliverPendingSearch(pending: PendingSearch): Promise<void> {\n\tconst {query, files} = pending;\n\tif (files.length === 0) {\n\t\tclient.sendMessage(query, sendOptions());\n\t\treturn;\n\t}\n\tconst sessionId = get(state).sessionId;\n\tconst paths: string[] = [];\n\tconst failed: string[] = [];\n\tfor (const file of files) {\n\t\tif (!sessionId) {\n\t\t\tfailed.push(file.name);\n\t\t\tcontinue;\n\t\t}\n\t\ttry {\n\t\t\tconst res = await uploadFile(sessionId, file);\n\t\t\tpaths.push(res.savedPath);\n\t\t} catch (err) {\n\t\t\tfailed.push(\n\t\t\t\t`${file.name} (${(err as Error).message || 'upload failed'})`,\n\t\t\t);\n\t\t}\n\t}\n\tif (failed.length > 0) {\n\t\tstate.update((s) => ({\n\t\t\t...s,\n\t\t\tsessionError: `Could not attach ${failed.join(', ')}`,\n\t\t}));\n\t}\n\tclient.sendMessage(buildAttachmentMessage(query, paths), sendOptions());\n}\n\n// Composer prefill: text to drop into the message box (to edit and send), used\n// by the fork-at-user-message flow to mirror pi's `/fork` position:'before'\n// (which hands you the forked-at message to edit and resend). The composer\n// watches this store, applies the text to its textarea, and clears it. A bump\n// counter guarantees the composer re-applies even when the same text is set\n// twice in a row.\nexport const composerPrefill = writable<{text: string; bump: number}>({\n\ttext: '',\n\tbump: 0,\n});\n\nexport function prefillComposer(text: string) {\n\tcomposerPrefill.update((p) => ({text, bump: p.bump + 1}));\n}\n\n// After a `session_fork` succeeds, the server returns the new session file plus\n// the forked-at message text. Hold that text here until the new session is\n// created/loaded, then push it into the composer so it lands in the RIGHT\n// (forked) session, not the source one.\nlet pendingForkPrefill: string | null = null;\n\n// Sync WebSocket messages with Svelte session-store state side-effects\nclient.onMessage((msg) => {\n\tswitch (msg.type) {\n\t\tcase 'session_forked': {\n\t\t\t// The server created the branched session file. Load it (switching away\n\t\t\t// from the source), and stash the forked-at message text so it is dropped\n\t\t\t// into the composer once the new session is active.\n\t\t\tconst forkedMsg = msg as {\n\t\t\t\tsessionFile: string;\n\t\t\t\tcwd: string;\n\t\t\t\tprefillText: string;\n\t\t\t};\n\t\t\tpendingForkPrefill = forkedMsg.prefillText ?? '';\n\t\t\tswitchSession(forkedMsg.sessionFile, forkedMsg.cwd);\n\t\t\tbreak;\n\t\t}\n\n\t\tcase 'assistant_current':\n\t\t\t// The answer to openAssistant()/resetAssistant(): open that session\n\t\t\t// through the normal load, like any session picked from the sidebar.\n\t\t\tswitchSession(msg.sessionFile, msg.cwd);\n\t\t\tbreak;\n\n\t\tcase 'assistant_status':\n\t\t\tapplyAssistantPointer({\n\t\t\t\tcurrentSessionId: msg.currentSessionId ?? null,\n\t\t\t\tcurrentSessionFile: msg.currentSessionFile ?? null,\n\t\t\t\t...(msg.timezone !== undefined ? {timezone: msg.timezone} : {}),\n\t\t\t});\n\t\t\tbreak;\n\n\t\tcase 'connected': {\n\t\t\t// Every new socket reports this browser's timezone: while the assistant\n\t\t\t// is active the server makes it the user's current one when it differs\n\t\t\t// (core/timezone-report.ts); otherwise the server ignores it.\n\t\t\tconst report = timezoneReportFrame();\n\t\t\tif (report) client.send(report);\n\t\t\tbreak;\n\t\t}\n\n\t\tcase 'session_created':\n\t\t\tsetCurrentSession(msg.sessionFile);\n\t\t\tif (pendingForkPrefill !== null) {\n\t\t\t\tconst text = pendingForkPrefill;\n\t\t\t\tpendingForkPrefill = null;\n\t\t\t\t// Defer so the composer has hydrated the (empty) new-session draft\n\t\t\t\t// before we overwrite it with the forked-at text.\n\t\t\t\tqueueMicrotask(() => prefillComposer(text));\n\t\t\t}\n\t\t\tif (pendingSearch !== null) {\n\t\t\t\tconst pending = pendingSearch;\n\t\t\t\tpendingSearch = null;\n\t\t\t\t// App onMessage listeners run BEFORE the client's internal switch\n\t\t\t\t// sets sessionId on its state store, and sendMessage() drops the\n\t\t\t\t// message when sessionId is still null (uploads need it too). Defer to\n\t\t\t\t// the next microtask so the store is populated before we send.\n\t\t\t\tqueueMicrotask(() => void deliverPendingSearch(pending));\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase 'message_history':\n\t\tcase 'agent_end':\n\t\t\t// Listeners run BEFORE the client's reducer applies the frame (and\n\t\t\t// agent_end's isStreaming reset is itself deferred; normalization forces\n\t\t\t// it off anyway), so write on the next microtask, from the updated store.\n\t\t\tqueueMicrotask(() => cacheWrites.flush());\n\t\t\tbreak;\n\n\t\tcase 'hydration_rejected': {\n\t\t\t// Synthesized by the client: the server refused the hydrated session's\n\t\t\t// load. Clears the hash synchronously (before any await, ahead of the\n\t\t\t// page's hash effect) and evicts the dead record.\n\t\t\tconst key = hydratedServerKey;\n\t\t\thydratedServerKey = null;\n\t\t\thandleHydrationRejected({\n\t\t\t\tsessionId: (msg as {sessionId: string}).sessionId,\n\t\t\t\tserverKey: key,\n\t\t\t\twin: typeof window !== 'undefined' ? window : null,\n\t\t\t\tcache: conversationCache,\n\t\t\t});\n\t\t\tbreak;\n\t\t}\n\n\t\tcase 'session_error':\n\t\t\t// A search that failed to create a session must not leave a stale\n\t\t\t// pending query that would fire on the next unrelated session.\n\t\t\tpendingSearch = null;\n\t\t\t// Likewise, a failed fork must not leak its prefill into a later session.\n\t\t\tpendingForkPrefill = null;\n\t\t\tbreak;\n\n\t\tcase 'session_destroyed':\n\t\t\tconst s = get(state);\n\t\t\tif (s.sessionId === msg.sessionId) {\n\t\t\t\tsetCurrentSession(null);\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase 'sessions_updated':\n\t\t\tfetchSessions();\n\t\t\tbreak;\n\n\t\tcase 'session_working': {\n\t\t\tconst m = msg as {sessionFile: string; working: boolean};\n\t\t\tsetSessionWorking(m.sessionFile, !!m.working);\n\t\t\tbreak;\n\t\t}\n\n\t\tcase 'session_interrupted':\n\t\t\tsetCurrentSession(null);\n\t\t\tbreak;\n\t}\n});\n\n// `preserveState` keeps the store across the connect (boot over a hydrated\n// cache). Every connect keeps only this server's cached conversations, so a\n// Reconnect or a same-server Connect wipes nothing and another server wipes the\n// previous one's.\nexport function connect(options: {preserveState?: boolean} = {}) {\n\tconst config = getConfig();\n\tsaveConfig(config);\n\tvoid retainCurrentServer(\n\t\tconversationCache,\n\t\tserverKey({host: config.host, port: config.port, token: config.token}),\n\t);\n\n\tconst isSecure =\n\t\ttypeof window !== 'undefined' &&\n\t\twindow.location &&\n\t\twindow.location.protocol === 'https:';\n\n\tclient.connect(\n\t\t{\n\t\t\thost: config.host,\n\t\t\tport: config.port,\n\t\t\ttoken: config.token,\n\t\t\tsecure: isSecure,\n\t\t\thideThinking: !!config.hideThinking,\n\t\t\thideTools: !!config.hideTools,\n\t\t},\n\t\t!!options.preserveState,\n\t);\n}\n\nexport function disconnect() {\n\tclient.disconnect(true);\n\tsetCurrentSession(null);\n}\n\n// Suspend the connection on tab-background without dropping the cached session.\n// Keeps messages/sessionId in the store so returning resyncs in place instead of\n// reloading. Deliberately does NOT clear the current session.\nexport function suspend() {\n\tclient.suspend();\n}\n\n// Resume after suspend(): reconnect preserving the cache and rejoin the active\n// session. The store's resyncing flag drives the UI's reconnecting affordance.\nexport function resume() {\n\tclient.resume();\n}\n\n// The page became visible again (visibilitychange: visible, pageshow). Probes a\n// still-open socket at once instead of trusting the silence clock across the\n// freeze (docs/adr/0011), with a short grace and no reconnect backoff since the\n// user is waiting. Also resets the backoff and restarts a stalled handshake.\n// Never opens a socket where there is none, so it is safe to call on every\n// return, before deciding whether to resume/connect. Call it only while the\n// page is visible: it assumes a user is looking.\nexport function noteVisible() {\n\tclient.noteVisible();\n}\n\n// True when a session was recorded for resume (i.e. the tab was suspended with an\n// active session). Lets callers choose the resume path only when there is\n// actually something to rejoin, and otherwise do a plain connect.\nexport function hasSuspendedSession(): boolean {\n\treturn client.hasSuspendedSession();\n}\n\n// True when the client still holds an active session to rejoin in place (from an\n// explicit suspend OR an unsolicited drop). Lets the page prefer the\n// preserve-cache resume() path over a session-wiping fresh connect() on return.\nexport function hasActiveSession(): boolean {\n\treturn client.hasActiveSession();\n}\n\n// --- Native file-picker guard ---------------------------------------------\n// Opening the OS file picker / camera backgrounds the page, which fires\n// `visibilitychange: hidden`. If the user lingers (taking a photo, browsing\n// files), the background suspend timer would otherwise fire and tear down the\n// session, so the subsequent upload fails with \"No active session\". Components\n// flag the picker as active so the visibility handler skips suspending while a\n// picker is open. A timestamp guards against the flag getting stuck if the\n// change event never arrives (e.g. the user cancels the picker on some\n// platforms).\nlet filePickerActiveUntil = 0;\nconst FILE_PICKER_GRACE_MS = 5 * 60 * 1000;\n\nexport function beginFilePicker() {\n\tfilePickerActiveUntil = Date.now() + FILE_PICKER_GRACE_MS;\n}\n\nexport function endFilePicker() {\n\tfilePickerActiveUntil = 0;\n}\n\nexport function isFilePickerActive(): boolean {\n\treturn Date.now() < filePickerActiveUntil;\n}\n\nexport function sendMessage(text: string): boolean {\n\treturn client.sendMessage(text, sendOptions());\n}\n\n// Retry a user message whose delivery could not be confirmed (delivery:\n// 'failed'). Returns false if it could not be handed to a live socket.\n// A resend starts a fresh turn, so the conversation-mode signal is re-read from\n// the knobs as they are NOW rather than reused from the original send.\nexport function resendMessage(messageId: string): boolean {\n\treturn client.resendMessage(messageId, sendOptions());\n}\n\n// Drop an undelivered user message the user chooses not to resend.\nexport function discardMessage(messageId: string): void {\n\tclient.discardMessage(messageId);\n}\n\nexport function abort() {\n\tclient.abort();\n}\n\n// Cancel the queued mid-stream steer messages for the active session, retracting\n// a steer the user regrets WITHOUT aborting the in-flight turn. Only meaningful\n// for server-type sessions (the ones that report a steer queue).\nexport function cancelSteer() {\n\tclient.cancelSteer();\n}\n\n// The composer's `/reload`: rebuild the active session's agent on the server so\n// it re-reads extensions, skills, prompts and context files (see\n// SessionPool.reloadSession). The server drives the UI state from here. Not to\n// be confused with reloadSession() below, which re-LOADS the session file.\nexport function reloadResources() {\n\tclient.reloadResources();\n}\n\nexport function joinSession(sessionFile: string, cwd?: string, model?: string) {\n\tclient.joinSession(sessionFile, cwd, model);\n}\n\n// Atomically leave the current session (if any) and load another one. Preferred\n// over a manual leaveSession()+joinSession() dance: it has no in-between gap that\n// could strand the \"Loading session...\" spinner. Always rearms the load watchdog\n// for the new target, so the latest tap wins.\nexport function switchSession(\n\tsessionFile: string,\n\tcwd?: string,\n\tmodel?: string,\n) {\n\tclient.switchSession(sessionFile, cwd, model);\n\tdropStaleHash(sessionFile);\n}\n\n// Fork the given session at a specific user-message entry (pi's `/fork`,\n// position 'before'). The server creates the branched session file and replies\n// with `session_forked`, which the onMessage handler above turns into a switch\n// to the new session + a composer prefill of the forked-at message text.\nexport function forkSession(sessionId: string, entryId: string) {\n\tclient.forkSession(sessionId, entryId);\n}\n\nexport function createSession(\n\tcwd: string,\n\tmodel?: string,\n\tgitInit?: boolean,\n\tcreateRemote?: boolean,\n\trepoVisibility?: 'private' | 'public',\n\tcloneRemote?: boolean,\n) {\n\tclient.createSession(\n\t\tcwd,\n\t\tmodel,\n\t\tgitInit,\n\t\tcreateRemote,\n\t\trepoVisibility,\n\t\tcloneRemote,\n\t);\n}\n\n/**\n * Run a web search: create a fresh session in the configured search folder and,\n * once it is created, send the query as the first message. Each search is a new\n * session, grouped in the sidebar under the search folder. When `model` is\n * omitted the server default (folder-local config) is used. Returns false\n * (no-op) if no search folder is configured.\n *\n * `files` are attachments picked in the search composer. They are uploaded only\n * AFTER the session exists (see deliverPendingSearch) and referenced from the\n * first message, so a search can open with an image or a document. A search with\n * files but no prose is allowed; an empty search with neither is not.\n */\nexport function runSearch(\n\tquery: string,\n\tmodel?: string,\n\tfiles: File[] = [],\n): boolean {\n\tconst trimmed = query.trim();\n\tif (!trimmed && files.length === 0) return false;\n\tconst folder = get(searchFolderStore);\n\tif (!folder) return false;\n\tconst createRemote = get(searchCreateRemoteStore);\n\tpendingSearch = {query: trimmed, files};\n\t// model omitted -> server default. gitInit follows remote intent.\n\t// repoVisibility forced to 'private' when a remote is created.\n\tclient.createSession(\n\t\tfolder,\n\t\tmodel || undefined,\n\t\tcreateRemote,\n\t\tcreateRemote,\n\t\tcreateRemote ? 'private' : undefined,\n\t);\n\treturn true;\n}\n\n/**\n * The Assistant entry point: open the CURRENT assistant session (the server\n * creates one when there is none). The server answers `assistant_current`, which\n * the onMessage handler above turns into a normal session switch.\n */\nexport function openAssistant() {\n\tclient.send({type: 'assistant_open'});\n}\n\n/**\n * Reset the assistant: the server retires the current session (aborting a\n * running turn, clearing its queue) and makes a fresh one current, then answers\n * `assistant_current` like openAssistant. The folder is the memory, so this is\n * cheap. A composer `/new` or `/reset` inside the assistant session does the same\n * through the ordinary `session_new`.\n */\nexport function resetAssistant() {\n\tclient.send({type: 'assistant_reset'});\n}\n\nexport function leaveSession() {\n\tclient.leaveSession();\n\tsetCurrentSession(null);\n\tdropStaleHash();\n}\n\n// See shouldDropStaleHash. Without a history entry or a hashchange.\nfunction dropStaleHash(target?: string) {\n\tif (typeof window === 'undefined') return;\n\tconst hashId = window.location.hash\n\t\t? decodeURIComponent(window.location.hash.slice(1))\n\t\t: '';\n\tif (!shouldDropStaleHash({connected: get(state).connected, hashId, target})) {\n\t\treturn;\n\t}\n\thistory.replaceState(\n\t\thistory.state,\n\t\t'',\n\t\twindow.location.pathname + window.location.search,\n\t);\n}\n\nexport function loadMoreHistory() {\n\tclient.loadMoreHistory();\n}\n\n// \"Continue anyway\" on the folder-conflict warning banner: enable the composer\n// for this session even though another session in the same folder is active. It\n// does NOT abort the other session.\nexport function continueFolderConflict() {\n\tclient.continueFolderConflict();\n}\n\nexport function ping() {\n\tclient.ping();\n}\n\nexport function clearMessages() {\n\tclient.clearMessages();\n}\n\nexport function setConfig(config: {\n\thost: string;\n\tport: number;\n\ttoken: string;\n\thideThinking?: boolean;\n\thideTools?: boolean;\n\tbeepDefault?: boolean;\n\tbeepSoundUrl?: string;\n\tconversationMode?: boolean;\n\tspeakReplies?: boolean;\n\tcollapseLongReplies?: boolean;\n\tmicReopensAfterReply?: boolean;\n}) {\n\tsaveConfig(config);\n\t// beepDefault/beepSoundUrl and the conversation-mode knobs are frontend-only\n\t// preferences; the client config has no such fields, so forward only the\n\t// fields it understands.\n\tconst {host, port, token, hideThinking, hideTools} = config;\n\tclient.setConfig({host, port, token, hideThinking, hideTools});\n\t// Keep the reactive stores in sync so derived state recomputes when the\n\t// settings UI changes a value (this is the path the settings UI uses, not the\n\t// dedicated setters). Only when the field is actually present in this update.\n\tif (config.beepDefault !== undefined) {\n\t\tbeepDefaultStore.set(!!config.beepDefault);\n\t}\n\tif (config.conversationMode !== undefined) {\n\t\t// The config field is the DEFAULT for conversations that have not been\n\t\t// toggled; a session's own choice still wins over it.\n\t\tconversationModeDefaultStore.set(!!config.conversationMode);\n\t}\n\tif (config.speakReplies !== undefined) {\n\t\tspeakRepliesStore.set(!!config.speakReplies);\n\t}\n\tif (config.collapseLongReplies !== undefined) {\n\t\tcollapseLongRepliesStore.set(!!config.collapseLongReplies);\n\t}\n\tif (config.micReopensAfterReply !== undefined) {\n\t\tmicReopensAfterReplyStore.set(!!config.micReopensAfterReply);\n\t}\n}\n\nexport function updateConfig(updates: {\n\thideThinking?: boolean;\n\thideTools?: boolean;\n}) {\n\tconst config = getConfig();\n\tconst newConfig = {...config, ...updates};\n\tsaveConfig(newConfig);\n\tclient.setConfig(newConfig);\n}\n\nexport function dismissSessionError() {\n\tclient.dismissSessionError();\n}\n\nexport function dismissNotice() {\n\tclient.dismissNotice();\n}\n\n// Submit the password for a pending `!sudo ...` command. The password is sent\n// straight to the server and never kept in client state.\nexport function sendSudoPassword(password: string) {\n\tclient.sendSudoPassword(password);\n}\n\n// Dismiss the pending sudo prompt without running the command.\nexport function cancelSudoPrompt() {\n\tclient.cancelSudoPrompt();\n}\n\nexport function changeModel(model: string) {\n\tclient.changeModel(model);\n}\n\n// --- Restoring a missing working folder ------------------------------------\n//\n// RESTORE = make the missing FOLDER exist again (clone it back, or create it).\n// Not to be confused with the unrelated restoring of queued steers/drafts after\n// a reload; see CONTEXT.md, where the wording is pinned.\n\n// Clone `url` into the active session's missing folder (or create the folder).\n// The job is server-owned and keyed by that path, so this may JOIN a clone\n// another device already started -- the panel is told which, and with which url.\nexport function startRestore(\n\taction: 'clone' | 'create',\n\turl?: string,\n\tgitInit?: boolean,\n): boolean {\n\treturn client.startRestore(action, url, gitInit);\n}\n\n// Cancel the running restore for the active session's folder. A directory the\n// job created is removed with it; one that already existed is left alone.\nexport function cancelRestore(): boolean {\n\treturn client.cancelRestore();\n}\n\n// Re-load the active session. This is how a completed restore goes LIVE: whether\n// a session has a live agent is a load-time decision, and the load that found\n// the folder missing deliberately built none.\nexport function reloadSession(): boolean {\n\treturn client.reloadSession();\n}\n\nexport const piState = derived(state, ($s) => $s);\nexport const isConnected = derived(piState, ($s) => $s.connected);\nexport const isStreaming = derived(piState, ($s) => $s.isStreaming);\nexport const messages = derived(piState, ($s) => $s.messages);\nexport const connectionError = derived(piState, ($s) => $s.error);\nexport const currentSession = derived(piState, ($s) => $s.session);\n// Folder-conflict warning-banner state (null when there is no conflict).\nexport const folderConflict = derived(piState, ($s) => $s.folderConflict);\n// The active session's working folder does not exist on this machine (null when\n// it does). Non-null means the session is READ-ONLY with no live agent and no\n// dismiss: the composer is replaced by a notice naming `cwd`, and only restoring\n// that folder and reloading brings the session back.\nexport const folderMissing = derived(piState, ($s) => $s.folderMissing);\n// The restore of that folder: the server's path-keyed job (running, finished, or\n// not yet started) plus this client's own last request. Drives the restore panel\n// that replaces the composer. null when no folder-missing session is open.\nexport const restoreState = derived(piState, ($s) => $s.restore);\nexport const isInterrupted = derived(piState, ($s) => $s.isInterrupted);\n// The mid-stream steer messages still queued on the server (not yet injected).\n// A user bubble whose content appears here is a pending steer the user can\n// cancel. Empty when nothing is queued.\nexport const pendingSteering = derived(piState, ($s) => $s.pendingSteering);\nexport const sessionError = derived(piState, ($s) => $s.sessionError);\n// A dismissible, non-fatal session notice (e.g. a CLI took over this session\n// while it was mid-turn here, discarding the in-flight tool call or streaming\n// reply). Rendered as a banner.\nexport const sessionNotice = derived(piState, ($s) => $s.notice);\n// A pending `!sudo ...` password prompt for the active session (or null). Drives\n// the masked SudoPasswordDialog.\nexport const sudoPrompt = derived(piState, ($s) => $s.sudoPrompt);\nexport const isReadOnly = derived(piState, ($s) => $s.readOnly);\nexport const activeSessionInfo = derived(piState, ($s) => ({\n\tsessionFile: $s.activeSessionFile,\n\tcwd: $s.activeCwd,\n\tmodel: $s.activeModel,\n\tsessionId: $s.sessionId,\n}));\nexport const contextUsage = derived(piState, ($s) => $s.contextUsage);\nexport const isCreatingSession = derived(piState, ($s) => $s.creatingSession);\nexport const isLoadingSession = derived(piState, ($s) => $s.loadingSession);\nexport const isResyncing = derived(piState, ($s) => $s.resyncing);\n// True after a fast-first (cold) session load: the conversation is readable but\n// the live agent is still building, so sending must stay blocked until ready.\nexport const isAgentPending = derived(piState, ($s) => $s.agentPending);\n// \"Load older messages\" stays hidden until the history is authoritative: a\n// hydrated or rejoining store's offset may be stale (ADR 0013).\nexport const hasMoreHistory = derived(piState, ($s) => canLoadOlderHistory($s));\nexport const isLoadingMoreHistory = derived(\n\tpiState,\n\t($s) => $s.loadingMoreHistory,\n);\n\n// `uploads.method: 'post'`: one XMLHttpRequest POST with byte progress, the\n// same `onProgress` contract as the WebSocket paths, and no resume\n// (`./core/post-upload.ts`, whose module comment records the decisions).\nfunction uploadFileViaPost(\n\tsessionId: string,\n\tfile: File,\n\tsignal: AbortSignal | undefined,\n\tonProgress: ((progress: UploadProgress) => void) | undefined,\n): Promise<{savedPath: string; filename: string}> {\n\tconst baseUrl = getBaseUrl();\n\tconst token = getToken();\n\tconst url = `${baseUrl}/session/upload?sessionId=${encodeURIComponent(sessionId)}&filename=${encodeURIComponent(file.name)}${token ? `&token=${encodeURIComponent(token)}` : ''}`;\n\treturn postUpload({\n\t\turl,\n\t\tbody: file,\n\t\tsize: file.size,\n\t\tsignal,\n\t\tonProgress,\n\t\tprobeReadable: () => fileStillReadable(file),\n\t});\n}\n\n/**\n * A picked File as the client's platform-neutral byte source. `File.slice()`\n * reads only the requested range, so a chunked upload never holds the whole\n * file in memory; a `NotReadableError` (the OS invalidated the pick) passes\n * through for the client to turn into \"pick it again\".\n */\nexport function fileByteSource(file: File): UploadByteSource {\n\treturn {\n\t\tsize: file.size,\n\t\tread: async (offset, length) =>\n\t\t\tnew Uint8Array(await file.slice(offset, offset + length).arrayBuffer()),\n\t};\n}\n\n/**\n * Build an authenticated URL for GET /session/download. The server streams the\n * file with Content-Disposition: attachment, validating `path` against the\n * session's allowed download roots. `path` is the server-provided (already\n * validated) path echoed back verbatim. Returns null when there is no active\n * session to attribute the download to.\n */\nexport function downloadFileUrl(path: string): string | null {\n\tconst state = get(piState);\n\tconst sessionId = state.sessionId;\n\tif (!sessionId) return null;\n\tconst baseUrl = getBaseUrl();\n\tconst token = getToken();\n\treturn (\n\t\t`${baseUrl}/session/download` +\n\t\t`?sessionId=${encodeURIComponent(sessionId)}` +\n\t\t`&path=${encodeURIComponent(path)}` +\n\t\t(token ? `&token=${encodeURIComponent(token)}` : '')\n\t);\n}\n\n/**\n * The `src` for a tool image: a data URI when the bytes came inline, else the\n * authenticated `GET /session/tool-image` URL for an image the server sent BY\n * REFERENCE (history over a slow-link-aware socket, see ToolImage). Null when\n * neither is possible (no data, no address, or no active session).\n */\nexport function toolImageSrc(img: ToolImage): string | null {\n\tif (img.data) return `data:${img.mimeType};base64,${img.data}`;\n\tif (!img.toolCallId || typeof img.index !== 'number') return null;\n\tconst sessionId = get(piState).sessionId;\n\tif (!sessionId) return null;\n\tconst token = getToken();\n\treturn (\n\t\t`${getBaseUrl()}/session/tool-image` +\n\t\t`?sessionId=${encodeURIComponent(sessionId)}` +\n\t\t`&toolCallId=${encodeURIComponent(img.toolCallId)}` +\n\t\t(img.entryId ? `&entryId=${encodeURIComponent(img.entryId)}` : '') +\n\t\t`&index=${img.index}` +\n\t\t(token ? `&token=${encodeURIComponent(token)}` : '')\n\t);\n}\n\n/**\n * Upload a composer attachment. `onProgress` receives every state change,\n * `{acked, size, state, error?}` (the same shape as the client's\n * `uploadsStore` entries), on EVERY path, so it can be the chip's single source\n * of truth. Over the WebSocket the client picks the protocol (chunked with real\n * acked progress on servers with `upload.v1`, else the legacy one-frame upload:\n * `queued` -> `sending` (acked 0) -> `paused` while its socket is lost ->\n * `done` / `failed`). POST reports `sending` (acked = bytes the browser has\n * sent, from `xhr.upload.onprogress`) -> `done` / `failed`, with no resume. A\n * cancel through `signal` reports `aborted`.\n */\nexport async function uploadFile(\n\tsessionId: string,\n\tfile: File,\n\toptions?: {\n\t\tsignal?: AbortSignal;\n\t\tonProgress?: (progress: UploadProgress) => void;\n\t},\n): Promise<{savedPath: string; filename: string}> {\n\tconst method = get(uploadMethodStore);\n\tconst onProgress = options?.onProgress;\n\tif (method === 'post') {\n\t\treturn uploadFileViaPost(sessionId, file, options?.signal, onProgress);\n\t}\n\treturn client.uploadFileViaWebSocket(\n\t\tsessionId,\n\t\tfile.name,\n\t\tfileByteSource(file),\n\t\t{\n\t\t\tsignal: options?.signal,\n\t\t\tmime: file.type || undefined,\n\t\t\tonProgress,\n\t\t},\n\t);\n}\n\n// --- Saved drafts -------------------------------------------------------\n// Thin transport over the server's /drafts routes. The SERVER owns the list\n// (ids, dedupe, cap, order) and answers every mutation with the whole new list,\n// so these just hand it back to the caller: the client never merges lists of its\n// own, which is what would make the two copies drift.\n\nasync function draftsRequest(\n\tpathname: string,\n\tinit?: {method?: string; body?: unknown},\n): Promise<Draft[]> {\n\tconst baseUrl = getBaseUrl();\n\tconst token = getToken();\n\tconst url = `${baseUrl}${pathname}${token ? `?token=${encodeURIComponent(token)}` : ''}`;\n\tconst res = await fetch(url, {\n\t\tmethod: init?.method ?? 'GET',\n\t\t...(init?.body !== undefined\n\t\t\t? {\n\t\t\t\t\theaders: {'Content-Type': 'application/json'},\n\t\t\t\t\tbody: JSON.stringify(init.body),\n\t\t\t\t}\n\t\t\t: {}),\n\t});\n\tif (!res.ok) {\n\t\tconst errData = await res.json().catch(() => ({}));\n\t\tthrow new Error(\n\t\t\terrData.error || `Drafts request failed with status ${res.status}`,\n\t\t);\n\t}\n\tconst data = await res.json().catch(() => ({}));\n\treturn normalizeDrafts(data.drafts);\n}\n\nexport async function fetchDrafts(): Promise<Draft[]> {\n\treturn draftsRequest('/drafts');\n}\n\nexport async function saveDraftRemote(input: {\n\ttext: string;\n\tsessionId?: string;\n\tcwd?: string;\n}): Promise<Draft[]> {\n\treturn draftsRequest('/drafts', {method: 'POST', body: input});\n}\n\nexport async function deleteDraftRemote(id: string): Promise<Draft[]> {\n\treturn draftsRequest('/drafts/delete', {method: 'POST', body: {id}});\n}\n\nexport async function deleteSession(sessionFile: string): Promise<void> {\n\ttry {\n\t\tconst baseUrl = getBaseUrl();\n\t\tconst token = getToken();\n\t\tconst url = `${baseUrl}/session/delete${token ? `?token=${encodeURIComponent(token)}` : ''}`;\n\n\t\tconst res = await fetch(url, {\n\t\t\tmethod: 'POST',\n\t\t\theaders: {\n\t\t\t\t'Content-Type': 'application/json',\n\t\t\t},\n\t\t\tbody: JSON.stringify({sessionFile}),\n\t\t});\n\n\t\tif (!res.ok) {\n\t\t\tconst errData = await res.json().catch(() => ({}));\n\t\t\tthrow new Error(\n\t\t\t\terrData.error || `Delete failed with status ${res.status}`,\n\t\t\t);\n\t\t}\n\t} catch (err) {\n\t\tconsole.error('Failed to delete session:', err);\n\t\tthrow err;\n\t}\n}\n","// Browser text-to-speech for the `say` tool's spoken-form reply, mirroring the\n// core/beep.ts pattern: a small, framework-agnostic helper that FEATURE-DETECTS\n// its browser API and degrades to a silent no-op (never a throw) when it is\n// unavailable, so it is safe to call from anywhere and unit-testable without a\n// real browser.\n//\n// The `say` affordance is driven entirely by the tool CALL over the already\n// streamed tool_start/tool_end (no new WS message type, no new chat role). The\n// short spoken text comes ONLY from the agent's explicit `say({ text })` call —\n// it is NEVER a client-side summary of the full written reply. The full written\n// reply always stays in the transcript; the spoken layer is additive.\n\n/**\n * Pull the spoken text out of a `say` tool call's parsed args object.\n *\n * Returns the trimmed `text`, or null when there is nothing to speak/show\n * (missing, blank, or non-string). Both the first-class \"spoken:\" card render\n * and the TTS utterance key off this SAME extracted text, so divergence between\n * what is shown and what is spoken is impossible.\n */\nexport function extractSayText(\n\targsObj: Record<string, unknown> | null | undefined,\n): string | null {\n\tif (!argsObj) return null;\n\tconst raw = argsObj.text;\n\tif (typeof raw !== 'string') return null;\n\tconst text = raw.trim();\n\treturn text ? text : null;\n}\n\n// The browser TTS surface this module needs, injectable so tests can supply a\n// fake without a real SpeechSynthesis (which the node test env lacks). In the\n// browser these default to window.speechSynthesis + SpeechSynthesisUtterance.\nexport interface SpeechDeps {\n\tsynth: SpeechSynthesis | null;\n\tUtterance: typeof SpeechSynthesisUtterance | null;\n}\n\n// --- TTS-settle signal ------------------------------------------------------\n// The hands-free mic-reopen loop (see core/hands-free.ts) must NOT re-open the\n// mic while a `say` reply is still being spoken, or the spoken reply would be\n// captured as microphone input. `speakUtterance` is otherwise fire-and-forget,\n// so this module owns a minimal settle signal: it tracks how many utterances\n// are currently outstanding (incremented on speak, decremented on the\n// utterance's onend/onerror) and lets a caller ask \"is TTS speaking right now?\"\n// or await \"resolve once TTS is idle\". When no utterance was ever fired\n// (speakReplies off) the count is 0, so it reports idle IMMEDIATELY and never\n// blocks the re-open. Deliberately additive: speakUtterance's existing callers\n// see no behaviour change.\nlet outstandingUtterances = 0;\nlet idleWaiters: Array<() => void> = [];\n\nfunction settleOneUtterance(): void {\n\tif (outstandingUtterances > 0) outstandingUtterances--;\n\tif (outstandingUtterances === 0 && idleWaiters.length > 0) {\n\t\tconst waiters = idleWaiters;\n\t\tidleWaiters = [];\n\t\tfor (const resolve of waiters) resolve();\n\t}\n}\n\n/**\n * Whether the browser is currently speaking a `say` reply (one or more\n * utterances are outstanding). Reports false when nothing was ever spoken\n * (speakReplies off) so the hands-free loop is not blocked.\n */\nexport function isTtsSpeaking(): boolean {\n\treturn outstandingUtterances > 0;\n}\n\n/**\n * Resolve once no TTS utterance is outstanding. Resolves IMMEDIATELY when TTS is\n * already idle (including when no utterance was ever fired), otherwise resolves\n * when the last outstanding utterance finishes (onend) or fails (onerror). The\n * hands-free loop awaits this before re-opening the mic so the spoken reply is\n * never captured as input.\n */\nexport function whenTtsIdle(): Promise<void> {\n\tif (outstandingUtterances === 0) return Promise.resolve();\n\treturn new Promise((resolve) => {\n\t\tidleWaiters.push(resolve);\n\t});\n}\n\n/**\n * Force the TTS-settle signal back to idle, resolving any pending whenTtsIdle()\n * waiters. Use when outstanding utterances can no longer be trusted to fire\n * their onend (e.g. the page called speechSynthesis.cancel() on session\n * teardown, which drops queued utterances without an onend for each), and in\n * test teardown so the module-global count does not leak between tests.\n */\nexport function resetTtsSettleSignal(): void {\n\toutstandingUtterances = 0;\n\tconst waiters = idleWaiters;\n\tidleWaiters = [];\n\tfor (const resolve of waiters) resolve();\n}\n\n// --- Gesture unlock --------------------------------------------------------\n// Mobile Chrome, iOS Safari and installed PWA webviews gate the FIRST\n// speechSynthesis.speak() of a page behind USER ACTIVATION: a speak() issued\n// outside a real tap/click handler is silently DROPPED (no error thrown, and\n// onend may never fire). A `say` reply is spoken from a WebSocket-driven $effect\n// in the chat list, so there is no gesture in its call stack -- which is exactly\n// why the spoken reply worked on desktop but never fired on mobile.\n//\n// The remedy is the standard one-time gesture unlock (the same shape as\n// core/beep.ts resuming a suspended AudioContext on user interaction): the first\n// time the user makes a gesture that means \"I want spoken replies\" -- turning\n// Conversation Mode ON, or tapping the mic -- we prime speechSynthesis from\n// INSIDE that handler, and the browser then permits the later gesture-less\n// utterances for the rest of the session.\nlet ttsUnlocked = false;\n// Whether the document-wide \"prime on the first gesture, whatever it is\" net is\n// currently armed (see armTtsGestureUnlock).\nlet gestureUnlockArmed = false;\nlet disarmGestureUnlock: (() => void) | null = null;\n\n// Best-effort \"un-pause the queue\" kick. Mobile Chrome can leave the\n// speechSynthesis queue in a paused state, which swallows subsequent utterances\n// even after the session is unlocked. resume() on an unpaused queue is a no-op,\n// so this is safe to issue before every speak; guarded for implementations that\n// lack it (and swallow-all, like the rest of the module).\nfunction resumeQueue(synth: SpeechSynthesis): void {\n\ttry {\n\t\tif (typeof synth.resume === 'function') synth.resume();\n\t} catch {\n\t\t// A spoken reply is a nicety: never surface a browser-side failure.\n\t}\n}\n\n// Inaudible (volume 0) but NOT blank: mobile Chrome drops whitespace-only\n// utterances outright, so a blank prime can fail to consume the user activation\n// it was issued under. See unlockTts.\nconst PRIMING_TEXT = '.';\n\n/**\n * Ask the engine for its voices, tolerating implementations that lack/throw on\n * getVoices(). Returns [] when the list is not (yet) known, which callers must\n * treat as \"no information\", never as \"no voices exist\".\n */\nfunction loadVoices(synth: SpeechSynthesis): SpeechSynthesisVoice[] {\n\ttry {\n\t\tif (typeof synth.getVoices !== 'function') return [];\n\t\treturn synth.getVoices() ?? [];\n\t} catch {\n\t\treturn [];\n\t}\n}\n\n/**\n * The `lang` to set on an utterance, or '' to leave the browser default alone.\n *\n * Setting a lang the engine has NO voice for is a known way to get silence on\n * mobile: the engine finds no match and simply says nothing. So the configured\n * speech locale is applied only when the voice list actually offers that language\n * (matched on the primary subtag, so `en-GB` is served by an `en-US` voice). When\n * the list is empty -- unknown, e.g. voices not loaded yet, or an engine without\n * getVoices() -- we have no information, so the locale is applied as before.\n *\n * Exported for unit testing; production callers go through speakUtterance.\n */\nexport function resolveUtteranceLang(\n\tlang: string | undefined,\n\tvoices: readonly {lang?: string}[],\n): string {\n\tconst wanted = (lang ?? '').trim();\n\tif (!wanted) return '';\n\tif (voices.length === 0) return wanted;\n\tconst primary = wanted.toLowerCase().split(/[-_]/)[0];\n\tconst supported = voices.some(\n\t\t(voice) => (voice.lang ?? '').toLowerCase().split(/[-_]/)[0] === primary,\n\t);\n\treturn supported ? wanted : '';\n}\n\n/**\n * Prime the browser's speech synthesis from INSIDE a user gesture so later\n * gesture-less `say` replies are actually spoken on mobile Chrome / iOS Safari /\n * installed PWAs. Idempotent: returns true only for the call that actually\n * primed, false when already unlocked or when it could not prime.\n *\n * MUST be called synchronously from a real tap/click handler (calling it from a\n * timer or a WebSocket effect does nothing useful -- there is no user activation\n * to consume). Its two production call sites are both real gestures that mean \"I\n * want a spoken exchange\":\n * - the Conversation Mode toggle handler in ChatMessageList.svelte (the user\n * opting into spoken replies), and\n * - the mic-button pointerdown in speech/SpeechButton.svelte, which additionally\n * covers a RETURNING user whose conversation mode was already persisted ON and\n * who therefore never taps the toggle.\n * The gesture-less hands-free re-open path (startRecordingProgrammatically) does\n * NOT unlock, since there is no user activation there.\n *\n * The priming utterance is SILENT (volume 0) so the user hears nothing, but its\n * text is deliberately NOT blank: mobile Chrome DISCARDS a whitespace-only\n * utterance without ever running the speech pipeline, so an empty prime can be\n * dropped without consuming the user activation it was issued under -- priming\n * that never primes, which is the mobile silence this is meant to fix. A single\n * period at volume 0 is inaudible and still exercises the pipeline.\n *\n * It is deliberately NOT tracked by the TTS-settle signal: some browsers never\n * fire onend for a priming utterance, which would wedge isTtsSpeaking() at true\n * forever and stop the hands-free loop from ever re-opening the mic. Keeping it\n * off the tracked path means isTtsSpeaking() / whenTtsIdle() keep reporting ONLY\n * real `say` replies.\n *\n * We do NOT call speechSynthesis.cancel() around the priming: cancel drops\n * queued utterances without firing their onend, which would leak the settle\n * count for a real reply that happens to be speaking when the user re-toggles.\n *\n * Feature-detected + swallow-all: a no-op (never a throw) when speechSynthesis is\n * absent, and in that case the session stays lockable so a later gesture in a\n * capable browser can still prime.\n *\n * `deps` is injectable for testing; production callers omit it.\n */\nexport function unlockTts(deps: SpeechDeps = browserSpeechDeps()): boolean {\n\tif (ttsUnlocked) return false;\n\n\tconst {synth, Utterance} = deps;\n\tif (!synth || !Utterance) return false;\n\n\ttry {\n\t\tresumeQueue(synth);\n\t\t// Nudge the voice list into loading while we are here: some engines only\n\t\t// populate getVoices() lazily, and a first utterance issued before any voice\n\t\t// exists can be dropped.\n\t\tloadVoices(synth);\n\t\tconst priming = new Utterance(PRIMING_TEXT);\n\t\tpriming.volume = 0;\n\t\t// No onend/onerror wiring and no outstandingUtterances++ on purpose: this\n\t\t// utterance must stay invisible to the settle signal.\n\t\tsynth.speak(priming);\n\t\tttsUnlocked = true;\n\t\tdisarmGestureUnlock?.();\n\t\treturn true;\n\t} catch {\n\t\t// Could not prime (e.g. the browser refused outside an activation window):\n\t\t// stay locked so the next gesture gets another go.\n\t\treturn false;\n\t}\n}\n\n/**\n * Whether TTS has been primed from a user gesture in this session. Diagnostic /\n * test-facing; callers do not need to check it before speaking (an un-primed\n * speak simply degrades to silence, as it does today).\n */\nexport function isTtsUnlocked(): boolean {\n\treturn ttsUnlocked;\n}\n\n/**\n * Forget that TTS was unlocked. For test isolation (the flag is module-global,\n * one per browser page); production code never needs this.\n */\nexport function resetTtsUnlock(): void {\n\tttsUnlocked = false;\n\tdisarmGestureUnlock?.();\n}\n\n/** The minimal event-target surface armTtsGestureUnlock needs (injectable for tests). */\nexport interface GestureTarget {\n\taddEventListener(\n\t\ttype: string,\n\t\tlistener: () => void,\n\t\toptions?: {capture?: boolean; passive?: boolean},\n\t): void;\n\tremoveEventListener(\n\t\ttype: string,\n\t\tlistener: () => void,\n\t\toptions?: {capture?: boolean},\n\t): void;\n}\n\n// Any of these means \"a human is driving this page right now\", which is all the\n// browser asks for before it will let the page speak.\nconst GESTURE_EVENTS = ['pointerdown', 'touchend', 'mousedown', 'keydown'];\n\n/**\n * Arm a one-shot, document-wide net that primes TTS from the user's NEXT gesture,\n * whatever that gesture is.\n *\n * WHY, on top of the explicit unlock call sites: those are the Conversation Mode\n * toggle, the mic button and settings-save -- all of which assume the user TOUCHES\n * one of them in this page load. A returning user whose conversation mode is\n * already persisted ON does not: they open the (installed) PWA, type or dictate,\n * and the first `say` reply arrives with no gesture ever having primed, so mobile\n * drops it silently while desktop speaks. That is exactly the reported \"no voice on\n * the phone, voice on the desktop\" gap, and it is why priming must not depend on\n * the user happening to tap one specific control.\n *\n * Listeners are capture-phase and passive (they never preventDefault, never\n * stopPropagation, and do not care which element was hit), and they remove\n * themselves as soon as priming succeeds, so this costs one gesture at most.\n * Idempotent: arming twice, or arming when already unlocked, does nothing.\n *\n * Returns true only if it actually armed the net.\n */\nexport function armTtsGestureUnlock(\n\ttarget: GestureTarget | null = typeof document === 'undefined'\n\t\t? null\n\t\t: document,\n\tdeps: SpeechDeps = browserSpeechDeps(),\n): boolean {\n\tif (ttsUnlocked || gestureUnlockArmed || !target) return false;\n\n\tconst onGesture = () => {\n\t\t// unlockTts() disarms us on success; if it could not prime (no speech\n\t\t// synthesis, or the browser refused), stay armed for the next gesture.\n\t\tunlockTts(deps);\n\t};\n\n\tdisarmGestureUnlock = () => {\n\t\tif (!gestureUnlockArmed) return;\n\t\tgestureUnlockArmed = false;\n\t\tdisarmGestureUnlock = null;\n\t\tfor (const type of GESTURE_EVENTS) {\n\t\t\ttry {\n\t\t\t\ttarget.removeEventListener(type, onGesture, {capture: true});\n\t\t\t} catch {\n\t\t\t\t// Never let listener bookkeeping surface as an app error.\n\t\t\t}\n\t\t}\n\t};\n\n\tgestureUnlockArmed = true;\n\ttry {\n\t\tfor (const type of GESTURE_EVENTS) {\n\t\t\ttarget.addEventListener(type, onGesture, {capture: true, passive: true});\n\t\t}\n\t} catch {\n\t\tdisarmGestureUnlock?.();\n\t\treturn false;\n\t}\n\treturn true;\n}\n\n/** Whether the first-gesture priming net is currently armed (test/diagnostic use). */\nexport function isTtsGestureUnlockArmed(): boolean {\n\treturn gestureUnlockArmed;\n}\n\nfunction browserSpeechDeps(): SpeechDeps {\n\tif (typeof window === 'undefined') return {synth: null, Utterance: null};\n\tconst w = window as Window & {\n\t\tspeechSynthesis?: SpeechSynthesis;\n\t\tSpeechSynthesisUtterance?: typeof SpeechSynthesisUtterance;\n\t};\n\treturn {\n\t\tsynth: w.speechSynthesis ?? null,\n\t\tUtterance: w.SpeechSynthesisUtterance ?? null,\n\t};\n}\n\n/**\n * Speak `text` aloud via the browser SpeechSynthesis API, firing EXACTLY ONE\n * utterance. Returns true when an utterance was spoken, false when it did\n * nothing (blank text, or the API is unavailable).\n *\n * - Feature-detected: when `speechSynthesis` / `SpeechSynthesisUtterance` are\n * not present (unsupported browser, SSR), this is a silent no-op — never a\n * throw — so callers need no guard of their own.\n * - `lang`: when a non-empty speech locale is provided it is set on the\n * utterance so the voice matches the configured speech language; when omitted\n * the browser default voice/lang is used. A locale the engine has NO voice for\n * is DROPPED rather than set, because setting it is a known way to get silence\n * on mobile (see resolveUtteranceLang).\n * - A defensive `resume()` kick is issued first: mobile Chrome can leave the\n * utterance queue paused, which drops the utterance even once the session has\n * been gesture-unlocked (see unlockTts). On desktop / an unpaused queue this is\n * a no-op, so behaviour there is unchanged.\n *\n * `deps` is injectable for testing; production callers omit it and get the real\n * browser APIs.\n */\nexport function speakUtterance(\n\ttext: string,\n\tlang?: string,\n\tdeps: SpeechDeps = browserSpeechDeps(),\n): boolean {\n\tconst spoken = (text ?? '').trim();\n\tif (!spoken) return false;\n\n\tconst {synth, Utterance} = deps;\n\tif (!synth || !Utterance) return false;\n\n\t// Track this utterance for the TTS-settle signal: it is outstanding until the\n\t// browser fires onend (finished) or onerror (failed). Both settle it (via\n\t// settleOnce, guarded so double-firing cannot double-decrement), so a failed\n\t// or duplicate-event utterance never wedges the hands-free loop \"speaking\"\n\t// forever. If anything below throws (or speak was never issued) we settle it\n\t// immediately so the count cannot leak.\n\toutstandingUtterances++;\n\tlet settled = false;\n\tconst settleOnce = () => {\n\t\tif (settled) return;\n\t\tsettled = true;\n\t\tsettleOneUtterance();\n\t};\n\n\ttry {\n\t\tresumeQueue(synth);\n\t\tconst utterance = new Utterance(spoken);\n\t\tconst resolvedLang = resolveUtteranceLang(lang, loadVoices(synth));\n\t\tif (resolvedLang) {\n\t\t\tutterance.lang = resolvedLang;\n\t\t}\n\t\tutterance.onend = settleOnce;\n\t\tutterance.onerror = settleOnce;\n\t\tsynth.speak(utterance);\n\t\treturn true;\n\t} catch {\n\t\t// A spoken reply is a nicety, never a hard requirement: swallow any\n\t\t// browser-side failure rather than surface it in the chat. Settle the\n\t\t// utterance we optimistically counted so the signal does not leak.\n\t\tsettleOnce();\n\t\treturn false;\n\t}\n}\n","<script lang=\"ts\">\n\timport {\n\t\tconnect,\n\t\tdisconnect,\n\t\tclearConversationCache,\n\t\tgetConfig,\n\t\tsetConfig,\n\t\tisConnected,\n\t} from '$lib/wherever';\n\timport {playInvitingBeep} from '$lib/core/beep';\n\timport {unlockTts} from '$lib/core/speak';\n\timport {onMount} from 'svelte';\n\n\tlet {\n\t\thost,\n\t\tport,\n\t\ttoken,\n\t\tonConnected,\n\t}: {\n\t\thost: string;\n\t\tport: number;\n\t\ttoken: string;\n\t\tonConnected: () => void;\n\t} = $props();\n\n\tlet localHost = $state('');\n\tlet localPort = $state(0);\n\tlet localToken = $state('');\n\tlet localHideThinking = $state(false);\n\tlet localBeepDefault = $state(false);\n\tlet localBeepSoundUrl = $state('');\n\tlet localConversationMode = $state(false);\n\tlet localSpeakReplies = $state(false);\n\tlet localCollapseLongReplies = $state(false);\n\tlet localMicReopensAfterReply = $state(false);\n\tlet saving = $state(false);\n\tlet connected = $derived($isConnected);\n\n\tonMount(() => {\n\t\tconst config = getConfig();\n\t\tlocalHost = config.host;\n\t\tlocalPort = config.port;\n\t\tlocalToken = config.token || '';\n\t\tlocalHideThinking = !!config.hideThinking;\n\t\tlocalBeepDefault = !!config.beepDefault;\n\t\tlocalBeepSoundUrl = config.beepSoundUrl || '';\n\t\tlocalConversationMode = !!config.conversationMode;\n\t\tlocalSpeakReplies = !!config.speakReplies;\n\t\tlocalCollapseLongReplies = !!config.collapseLongReplies;\n\t\tlocalMicReopensAfterReply = !!config.micReopensAfterReply;\n\t});\n\n\tfunction handleTestBeep() {\n\t\tplayInvitingBeep(localBeepSoundUrl.trim() || undefined);\n\t}\n\n\tfunction handleConfigChange() {\n\t\tsetConfig({\n\t\t\thost: localHost,\n\t\t\tport: localPort,\n\t\t\ttoken: localToken,\n\t\t\thideThinking: localHideThinking,\n\t\t\t// Tool calls are always shown (the toggle was removed); force it off so a\n\t\t\t// previously-stored `true` is cleared.\n\t\t\thideTools: false,\n\t\t\tbeepDefault: localBeepDefault,\n\t\t\tbeepSoundUrl: localBeepSoundUrl.trim(),\n\t\t\tconversationMode: localConversationMode,\n\t\t\tspeakReplies: localSpeakReplies,\n\t\t\tcollapseLongReplies: localCollapseLongReplies,\n\t\t\tmicReopensAfterReply: localMicReopensAfterReply,\n\t\t});\n\t\t// Enabling spoken replies HERE is a real user gesture (a checkbox onchange),\n\t\t// so it is a valid moment to prime browser TTS. Without this, a mobile user\n\t\t// who turns conversation mode + speak-replies on from settings and then only\n\t\t// types (never tapping the master toggle or the mic) would have their FIRST\n\t\t// `say` reply silently dropped by mobile Chrome / iOS / PWA user-activation\n\t\t// gating. unlockTts() is idempotent (a no-op once primed) and only primes\n\t\t// when spoken replies are actually intended.\n\t\tif (localConversationMode && localSpeakReplies) {\n\t\t\tunlockTts();\n\t\t}\n\t}\n\n\tfunction handleConnect() {\n\t\tsetConfig({\n\t\t\thost: localHost,\n\t\t\tport: localPort,\n\t\t\ttoken: localToken,\n\t\t\thideThinking: localHideThinking,\n\t\t\thideTools: false,\n\t\t\tbeepDefault: localBeepDefault,\n\t\t\tbeepSoundUrl: localBeepSoundUrl.trim(),\n\t\t\tconversationMode: localConversationMode,\n\t\t\tspeakReplies: localSpeakReplies,\n\t\t\tcollapseLongReplies: localCollapseLongReplies,\n\t\t\tmicReopensAfterReply: localMicReopensAfterReply,\n\t\t});\n\t\t// No wipe here: connect() keeps only the (possibly edited) server's cached\n\t\t// conversations, so a same-server Connect wipes nothing (ADR 0013).\n\t\tdisconnect();\n\t\tsetTimeout(() => connect(), 100);\n\t}\n\n\t// \"Disconnect\" wipes the on-device conversation cache (ADR 0013). Only here and\n\t// in the page's \"Disconnect Server\", never in the shared disconnect().\n\tfunction handleDisconnect() {\n\t\tdisconnect();\n\t\tclearConversationCache();\n\t}\n\n\tfunction handleReload() {\n\t\twindow.location.reload();\n\t}\n</script>\n\n<div class=\"border-b border-brand-border p-4\">\n\t<div class=\"space-y-3\">\n\t\t<div>\n\t\t\t<label for=\"pi-host\" class=\"mb-1 block text-xs text-brand-text-muted\"\n\t\t\t\t>Host</label\n\t\t\t>\n\t\t\t<input\n\t\t\t\tid=\"pi-host\"\n\t\t\t\ttype=\"text\"\n\t\t\t\tbind:value={localHost}\n\t\t\t\tplaceholder=\"localhost\"\n\t\t\t\tclass=\"w-full rounded border border-brand-border bg-brand-surface-2 px-3 py-2 text-sm text-brand-text placeholder-brand-text-muted focus:border-brand-blue focus:outline-none\"\n\t\t\t/>\n\t\t</div>\n\n\t\t<div>\n\t\t\t<label for=\"pi-port\" class=\"mb-1 block text-xs text-brand-text-muted\"\n\t\t\t\t>Port</label\n\t\t\t>\n\t\t\t<input\n\t\t\t\tid=\"pi-port\"\n\t\t\t\ttype=\"number\"\n\t\t\t\tbind:value={localPort}\n\t\t\t\tclass=\"w-full rounded border border-brand-border bg-brand-surface-2 px-3 py-2 text-sm text-brand-text placeholder-brand-text-muted focus:border-brand-blue focus:outline-none\"\n\t\t\t/>\n\t\t</div>\n\n\t\t<div>\n\t\t\t<label for=\"pi-token\" class=\"mb-1 block text-xs text-brand-text-muted\"\n\t\t\t\t>Token (optional)</label\n\t\t\t>\n\t\t\t<input\n\t\t\t\tid=\"pi-token\"\n\t\t\t\ttype=\"password\"\n\t\t\t\tbind:value={localToken}\n\t\t\t\tplaceholder=\"Authentication token\"\n\t\t\t\tclass=\"w-full rounded border border-brand-border bg-brand-surface-2 px-3 py-2 text-sm text-brand-text placeholder-brand-text-muted focus:border-brand-blue focus:outline-none\"\n\t\t\t/>\n\t\t</div>\n\n\t\t<div class=\"flex items-center gap-2 py-1\">\n\t\t\t<input\n\t\t\t\tid=\"pi-hide-thinking\"\n\t\t\t\ttype=\"checkbox\"\n\t\t\t\tbind:checked={localHideThinking}\n\t\t\t\tonchange={handleConfigChange}\n\t\t\t\tclass=\"h-4 w-4 rounded border-brand-border bg-brand-surface-2 text-brand-blue focus:ring-brand-blue focus:ring-offset-0\"\n\t\t\t/>\n\t\t\t<label\n\t\t\t\tfor=\"pi-hide-thinking\"\n\t\t\t\tclass=\"cursor-pointer text-xs text-brand-text select-none\"\n\t\t\t>\n\t\t\t\tHide thinking steps\n\t\t\t</label>\n\t\t</div>\n\n\t\t<div class=\"flex items-center gap-2 py-1\">\n\t\t\t<input\n\t\t\t\tid=\"pi-beep-default\"\n\t\t\t\ttype=\"checkbox\"\n\t\t\t\tbind:checked={localBeepDefault}\n\t\t\t\tonchange={handleConfigChange}\n\t\t\t\tclass=\"h-4 w-4 rounded border-brand-border bg-brand-surface-2 text-brand-blue focus:ring-brand-blue focus:ring-offset-0\"\n\t\t\t/>\n\t\t\t<label\n\t\t\t\tfor=\"pi-beep-default\"\n\t\t\t\tclass=\"cursor-pointer text-xs text-brand-text select-none\"\n\t\t\t>\n\t\t\t\tBeep when the agent is waiting (default for new sessions)\n\t\t\t</label>\n\t\t</div>\n\n\t\t<div>\n\t\t\t<label\n\t\t\t\tfor=\"pi-beep-sound\"\n\t\t\t\tclass=\"mb-1 block text-xs text-brand-text-muted\"\n\t\t\t\t>Beep sound URL (optional, blank = built-in chime)</label\n\t\t\t>\n\t\t\t<div class=\"flex gap-2\">\n\t\t\t\t<input\n\t\t\t\t\tid=\"pi-beep-sound\"\n\t\t\t\t\ttype=\"text\"\n\t\t\t\t\tbind:value={localBeepSoundUrl}\n\t\t\t\t\tonchange={handleConfigChange}\n\t\t\t\t\tplaceholder=\"/sounds/complete.mp3 or https://...\"\n\t\t\t\t\tclass=\"w-full rounded border border-brand-border bg-brand-surface-2 px-3 py-2 text-sm text-brand-text placeholder-brand-text-muted focus:border-brand-blue focus:outline-none\"\n\t\t\t\t/>\n\t\t\t\t<button\n\t\t\t\t\ttype=\"button\"\n\t\t\t\t\tonclick={handleTestBeep}\n\t\t\t\t\ttitle=\"Play the beep to test it\"\n\t\t\t\t\tclass=\"flex-shrink-0 rounded border border-brand-border bg-brand-surface-2 px-3 py-2 text-sm text-brand-text transition-colors hover:bg-brand-surface-3\"\n\t\t\t\t>\n\t\t\t\t\tTest\n\t\t\t\t</button>\n\t\t\t</div>\n\t\t</div>\n\n\t\t<div class=\"space-y-2 border-t border-brand-border pt-3\">\n\t\t\t<div class=\"flex items-center gap-2 py-1\">\n\t\t\t\t<input\n\t\t\t\t\tid=\"pi-conversation-mode\"\n\t\t\t\t\ttype=\"checkbox\"\n\t\t\t\t\tbind:checked={localConversationMode}\n\t\t\t\t\tonchange={handleConfigChange}\n\t\t\t\t\tclass=\"h-4 w-4 rounded border-brand-border bg-brand-surface-2 text-brand-blue focus:ring-brand-blue focus:ring-offset-0\"\n\t\t\t\t/>\n\t\t\t\t<label\n\t\t\t\t\tfor=\"pi-conversation-mode\"\n\t\t\t\t\tclass=\"cursor-pointer text-xs font-medium text-brand-text select-none\"\n\t\t\t\t>\n\t\t\t\t\tConversation Mode by default (spoken back-and-forth)\n\t\t\t\t</label>\n\t\t\t</div>\n\t\t\t<p class=\"pl-6 text-[10px] leading-relaxed text-brand-text-muted\">\n\t\t\t\tThe DEFAULT for conversations you have not toggled: Conversation Mode is\n\t\t\t\tper conversation, and the 💬/🗣️ toggle above the composer sets it for\n\t\t\t\tthe conversation you are in, leaving the others alone. Changing this\n\t\t\t\tdefault moves every conversation still following it. It flips the knobs\n\t\t\t\tbelow on at once; when off, they are dormant and the default\n\t\t\t\ttyping-first experience is unchanged. Auto-send on speech end (Direct\n\t\t\t\tSend, in Speech Settings) keeps its own effect regardless.\n\t\t\t</p>\n\n\t\t\t<div class=\"flex items-center gap-2 py-1 pl-6\">\n\t\t\t\t<input\n\t\t\t\t\tid=\"pi-speak-replies\"\n\t\t\t\t\ttype=\"checkbox\"\n\t\t\t\t\tbind:checked={localSpeakReplies}\n\t\t\t\t\tonchange={handleConfigChange}\n\t\t\t\t\tclass=\"h-4 w-4 rounded border-brand-border bg-brand-surface-2 text-brand-blue focus:ring-brand-blue focus:ring-offset-0\"\n\t\t\t\t/>\n\t\t\t\t<label\n\t\t\t\t\tfor=\"pi-speak-replies\"\n\t\t\t\t\tclass=\"cursor-pointer text-xs text-brand-text select-none\"\n\t\t\t\t>\n\t\t\t\t\tSpeak replies aloud (browser TTS)\n\t\t\t\t</label>\n\t\t\t</div>\n\n\t\t\t<div class=\"flex items-center gap-2 py-1 pl-6\">\n\t\t\t\t<input\n\t\t\t\t\tid=\"pi-collapse-long-replies\"\n\t\t\t\t\ttype=\"checkbox\"\n\t\t\t\t\tbind:checked={localCollapseLongReplies}\n\t\t\t\t\tonchange={handleConfigChange}\n\t\t\t\t\tclass=\"h-4 w-4 rounded border-brand-border bg-brand-surface-2 text-brand-blue focus:ring-brand-blue focus:ring-offset-0\"\n\t\t\t\t/>\n\t\t\t\t<label\n\t\t\t\t\tfor=\"pi-collapse-long-replies\"\n\t\t\t\t\tclass=\"cursor-pointer text-xs text-brand-text select-none\"\n\t\t\t\t>\n\t\t\t\t\tCollapse long written replies\n\t\t\t\t</label>\n\t\t\t</div>\n\n\t\t\t<div class=\"flex items-center gap-2 py-1 pl-6\">\n\t\t\t\t<input\n\t\t\t\t\tid=\"pi-mic-reopen\"\n\t\t\t\t\ttype=\"checkbox\"\n\t\t\t\t\tbind:checked={localMicReopensAfterReply}\n\t\t\t\t\tonchange={handleConfigChange}\n\t\t\t\t\tclass=\"h-4 w-4 rounded border-brand-border bg-brand-surface-2 text-brand-blue focus:ring-brand-blue focus:ring-offset-0\"\n\t\t\t\t/>\n\t\t\t\t<label\n\t\t\t\t\tfor=\"pi-mic-reopen\"\n\t\t\t\t\tclass=\"cursor-pointer text-xs text-brand-text select-none\"\n\t\t\t\t>\n\t\t\t\t\tRe-open mic after the agent speaks (hands-free)\n\t\t\t\t</label>\n\t\t\t</div>\n\t\t\t<p class=\"pl-6 text-[10px] leading-relaxed text-brand-text-muted\">\n\t\t\t\tApplies to both speech engines. On the Cloud AI engine, which records\n\t\t\t\tuntil told to stop, an auto-opened mic stops itself on silence (and\n\t\t\t\talways within a minute), so a re-opened mic can never run away.\n\t\t\t</p>\n\t\t</div>\n\n\t\t<div class=\"flex gap-2\">\n\t\t\t{#if connected}\n\t\t\t\t<button\n\t\t\t\t\tonclick={handleDisconnect}\n\t\t\t\t\tclass=\"flex-1 rounded bg-rose-500 px-4 py-2 text-sm text-white transition-colors hover:bg-rose-600\"\n\t\t\t\t>\n\t\t\t\t\tDisconnect\n\t\t\t\t</button>\n\t\t\t{:else}\n\t\t\t\t<button\n\t\t\t\t\tonclick={handleConnect}\n\t\t\t\t\tdisabled={saving}\n\t\t\t\t\tclass=\"flex-1 rounded bg-gradient-to-r from-brand-cyan to-brand-blue px-4 py-2 text-sm text-white transition-all hover:opacity-90 disabled:cursor-not-allowed disabled:from-brand-surface-3 disabled:to-brand-surface-3\"\n\t\t\t\t>\n\t\t\t\t\t{saving ? 'Connecting...' : 'Connect'}\n\t\t\t\t</button>\n\t\t\t{/if}\n\t\t</div>\n\n\t\t<button\n\t\t\tonclick={handleReload}\n\t\t\ttitle=\"Reload the page\"\n\t\t\tclass=\"flex w-full items-center justify-center gap-2 rounded border border-brand-border bg-brand-surface-2 px-4 py-2 text-sm text-brand-text transition-colors hover:bg-brand-surface-3\"\n\t\t>\n\t\t\t<svg\n\t\t\t\txmlns=\"http://www.w3.org/2000/svg\"\n\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\tfill=\"none\"\n\t\t\t\tstroke=\"currentColor\"\n\t\t\t\tstroke-width=\"2\"\n\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\tclass=\"h-4 w-4\"\n\t\t\t\taria-hidden=\"true\"\n\t\t\t>\n\t\t\t\t<path d=\"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8\" />\n\t\t\t\t<path d=\"M21 3v5h-5\" />\n\t\t\t\t<path d=\"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16\" />\n\t\t\t\t<path d=\"M8 16H3v5\" />\n\t\t\t</svg>\n\t\t\tReload\n\t\t</button>\n\t</div>\n</div>\n","/**\n * THIS device's Web Push subscription to the wherever assistant (server\n * `web-push.ts`, ADR 0017): the settings toggle subscribes or unsubscribes it\n * with `PushManager.subscribe` and the server's VAPID public key, and registers\n * it on the server's token-gated `/push/subscription`.\n *\n * Framework-free with every browser object injected, so it is unit-tested with\n * fakes. Replaces the template's `push-notifications` module, which was built for\n * `push-notification-server`'s signer-based `/register` and was never used.\n */\n\n/** The slice of `PushSubscription` used here. */\nexport interface DevicePushSubscription {\n\tendpoint: string;\n\toptions?: {applicationServerKey?: ArrayBuffer | null};\n\ttoJSON(): unknown;\n\tunsubscribe(): Promise<boolean>;\n}\n\n/** The slice of `PushManager` used here. */\nexport interface DevicePushManager {\n\tgetSubscription(): Promise<DevicePushSubscription | null>;\n\tsubscribe(options: {\n\t\tuserVisibleOnly: boolean;\n\t\tapplicationServerKey: Uint8Array;\n\t}): Promise<DevicePushSubscription>;\n}\n\nexport interface PushServerDeps {\n\tbaseUrl: string;\n\ttoken: string;\n\tfetch: (url: string, init?: RequestInit) => Promise<Response>;\n}\n\n/** True when this browser can receive Web Push at all (service worker + PushManager + Notification). */\nexport function pushSupported(g: any = globalThis): boolean {\n\treturn (\n\t\t!!g.navigator &&\n\t\t'serviceWorker' in g.navigator &&\n\t\t'PushManager' in g &&\n\t\t'Notification' in g\n\t);\n}\n\nexport function urlB64ToUint8Array(base64String: string): Uint8Array {\n\tconst padding = '='.repeat((4 - (base64String.length % 4)) % 4);\n\tconst base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/');\n\tconst raw = atob(base64);\n\tconst out = new Uint8Array(raw.length);\n\tfor (let i = 0; i < raw.length; ++i) out[i] = raw.charCodeAt(i);\n\treturn out;\n}\n\nfunction pushUrl(deps: PushServerDeps, path: string, query = ''): string {\n\tconst params = new URLSearchParams(query);\n\tif (deps.token) params.set('token', deps.token);\n\tconst qs = params.toString();\n\treturn `${deps.baseUrl}${path}${qs ? `?${qs}` : ''}`;\n}\n\nasync function ok(res: Response): Promise<any> {\n\tconst data = await res.json().catch(() => ({}));\n\tif (!res.ok) throw new Error(data?.error || `HTTP ${res.status}`);\n\treturn data;\n}\n\nfunction sameKey(a: ArrayBuffer | null | undefined, b: Uint8Array): boolean {\n\tif (!a) return false;\n\tconst x = new Uint8Array(a);\n\treturn x.length === b.length && x.every((v, i) => v === b[i]);\n}\n\n/** Whether THIS device is subscribed: it holds a subscription AND the server has it. */\nexport async function isThisDeviceSubscribed(\n\tpm: DevicePushManager,\n\tdeps: PushServerDeps,\n): Promise<boolean> {\n\tconst sub = await pm.getSubscription();\n\tif (!sub) return false;\n\tconst data = await ok(\n\t\tawait deps.fetch(\n\t\t\tpushUrl(\n\t\t\t\tdeps,\n\t\t\t\t'/push/subscription',\n\t\t\t\t`endpoint=${encodeURIComponent(sub.endpoint)}`,\n\t\t\t),\n\t\t),\n\t);\n\treturn !!data.subscribed;\n}\n\n/**\n * Subscribe THIS device: fetch the server's VAPID key (the server generates it\n * on first use), subscribe (replacing a subscription made for another key), and\n * register it on the server.\n */\nexport async function subscribeThisDevice(\n\tpm: DevicePushManager,\n\tdeps: PushServerDeps,\n): Promise<void> {\n\tconst {publicKey} = await ok(\n\t\tawait deps.fetch(pushUrl(deps, '/push/vapid-public-key')),\n\t);\n\tif (typeof publicKey !== 'string' || !publicKey)\n\t\tthrow new Error('the server sent no VAPID public key');\n\tconst key = urlB64ToUint8Array(publicKey);\n\tlet sub = await pm.getSubscription();\n\tif (sub && !sameKey(sub.options?.applicationServerKey, key)) {\n\t\tawait sub.unsubscribe();\n\t\tsub = null;\n\t}\n\tif (!sub) {\n\t\tsub = await pm.subscribe({\n\t\t\tuserVisibleOnly: true,\n\t\t\tapplicationServerKey: key,\n\t\t});\n\t}\n\tawait ok(\n\t\tawait deps.fetch(pushUrl(deps, '/push/subscription'), {\n\t\t\tmethod: 'POST',\n\t\t\theaders: {'Content-Type': 'application/json'},\n\t\t\tbody: JSON.stringify(sub.toJSON()),\n\t\t}),\n\t);\n}\n\n/** Unsubscribe THIS device: remove it from the server, then drop the browser subscription. */\nexport async function unsubscribeThisDevice(\n\tpm: DevicePushManager,\n\tdeps: PushServerDeps,\n): Promise<void> {\n\tconst sub = await pm.getSubscription();\n\tif (!sub) return;\n\tawait ok(\n\t\tawait deps.fetch(pushUrl(deps, '/push/subscription'), {\n\t\t\tmethod: 'DELETE',\n\t\t\theaders: {'Content-Type': 'application/json'},\n\t\t\tbody: JSON.stringify({endpoint: sub.endpoint}),\n\t\t}),\n\t);\n\tawait sub.unsubscribe();\n}\n\n/**\n * A push error for the settings UI: its NAME and message (a DOMException's\n * name is the useful part: Firefox's \"Error retrieving push subscription.\" is\n * an AbortError), plus a short actionable hint for the two errors a user can\n * fix: AbortError (the browser's push service is disabled or unreachable) and\n * NotAllowedError or a denied permission (re-allow notifications).\n */\nexport function describePushError(err: unknown, permission?: string): string {\n\tlet text: string;\n\tlet name = '';\n\tif (err && typeof err === 'object' && 'message' in err) {\n\t\tconst e = err as {name?: unknown; message?: unknown};\n\t\tname = typeof e.name === 'string' ? e.name : '';\n\t\tconst message = String(e.message ?? '');\n\t\ttext = name && name !== 'Error' ? `${name}: ${message}` : message;\n\t} else {\n\t\ttext = String(err);\n\t}\n\tif (name === 'NotAllowedError' || permission === 'denied') {\n\t\treturn `${text} Notifications are blocked for this site: re-allow them in the browser's site settings (the icon left of the address), then try again.`;\n\t}\n\tif (name === 'AbortError') {\n\t\treturn `${text} The browser's push service is disabled or unreachable. On Firefox and LibreWolf, open about:config and check that dom.push.enabled and dom.push.connection.enabled are true (and that the browser can reach its push server).`;\n\t}\n\treturn text;\n}\n\n/**\n * The settings toggle: subscribe (`want` true) or unsubscribe THIS device,\n * then RE-READ the real state, so the checkbox never shows a state the device\n * is not in (a failed subscribe used to leave it checked). When even the\n * re-read fails, the state is assumed unchanged (`!want`).\n */\nexport async function applyPushToggle(\n\tpm: DevicePushManager,\n\tdeps: PushServerDeps,\n\twant: boolean,\n\tpermission?: () => string | undefined,\n): Promise<{subscribed: boolean; error: string}> {\n\tlet error = '';\n\ttry {\n\t\tif (want) await subscribeThisDevice(pm, deps);\n\t\telse await unsubscribeThisDevice(pm, deps);\n\t} catch (err) {\n\t\terror = describePushError(err, permission?.());\n\t}\n\tlet subscribed = !want;\n\ttry {\n\t\tsubscribed = await isThisDeviceSubscribed(pm, deps);\n\t} catch (err) {\n\t\tif (!error) error = describePushError(err, permission?.());\n\t}\n\treturn {subscribed, error};\n}\n\n/** One channel's result in `POST /push/test` (the dispatcher's delivery). */\nexport interface TestDelivery {\n\tchannel: string;\n\tresult: {ok: true; detail?: string} | {ok: false; error: string};\n}\n\n/**\n * \"Send test notification\": `POST /push/test` (token-gated), which goes through\n * the same notify path as `assistant_notify` (every channel), opening\n * `sessionId` (the session this device has open) or the main screen. Resolves\n * a one-line summary per channel; rejects with the server's error when the\n * notification reached nothing.\n */\nexport async function sendTestNotification(\n\tdeps: PushServerDeps,\n\tsessionId: string | null,\n): Promise<string> {\n\tconst data = await ok(\n\t\tawait deps.fetch(pushUrl(deps, '/push/test'), {\n\t\t\tmethod: 'POST',\n\t\t\theaders: {'Content-Type': 'application/json'},\n\t\t\tbody: JSON.stringify(sessionId ? {sessionId} : {}),\n\t\t}),\n\t);\n\tconst deliveries: TestDelivery[] = Array.isArray(data?.deliveries)\n\t\t? data.deliveries\n\t\t: [];\n\tconst sent = deliveries\n\t\t.filter((d) => d.result.ok)\n\t\t.map((d) =>\n\t\t\td.result.ok && d.result.detail\n\t\t\t\t? `${d.channel} (${d.result.detail})`\n\t\t\t\t: d.channel,\n\t\t);\n\tconst failed = deliveries\n\t\t.filter((d) => !d.result.ok)\n\t\t.map((d) => `${d.channel}: ${d.result.ok ? '' : d.result.error}`);\n\tlet text = sent.length > 0 ? `Sent: ${sent.join(', ')}.` : 'Sent.';\n\tif (failed.length > 0) text += ` Not delivered: ${failed.join('; ')}.`;\n\treturn text;\n}\n","<script lang=\"ts\">\n\t// The settings toggle for the assistant's Web Push (server/src/web-push.ts,\n\t// ADR 0017): subscribes or unsubscribes THIS device. Rendered by the page only\n\t// while the assistant is active and its Web Push channel runs, so with the\n\t// assistant off nothing of it shows.\n\timport {onMount} from 'svelte';\n\timport {\n\t\tapplyPushToggle,\n\t\tdescribePushError,\n\t\tisThisDeviceSubscribed,\n\t\tpushSupported,\n\t\tsendTestNotification,\n\t\ttype DevicePushManager,\n\t\ttype PushServerDeps,\n\t} from '$lib/core/push-subscription';\n\timport {fetchConfig, getBaseUrl, getToken} from '$lib/session-store';\n\n\t// The session this device has open: a test notification opens it (none: the\n\t// main screen).\n\tlet {currentSessionId = null}: {currentSessionId?: string | null} = $props();\n\n\tlet supported = $state(false);\n\tlet subscribed = $state(false);\n\tlet busy = $state(true);\n\tlet error = $state('');\n\tlet testing = $state(false);\n\tlet testResult = $state('');\n\tlet testError = $state('');\n\tlet checkbox: HTMLInputElement | undefined = $state();\n\n\tconst permission = () =>\n\t\ttypeof Notification !== 'undefined' ? Notification.permission : undefined;\n\n\tconst deps = (): PushServerDeps => ({\n\t\tbaseUrl: getBaseUrl(),\n\t\ttoken: getToken(),\n\t\tfetch: (url, init) => fetch(url, init),\n\t});\n\n\tasync function manager(): Promise<DevicePushManager> {\n\t\tconst registration = await navigator.serviceWorker.ready;\n\t\treturn registration.pushManager as unknown as DevicePushManager;\n\t}\n\n\tonMount(() => {\n\t\tsupported = pushSupported();\n\t\tif (!supported) {\n\t\t\tbusy = false;\n\t\t\treturn;\n\t\t}\n\t\tvoid (async () => {\n\t\t\ttry {\n\t\t\t\tsubscribed = await isThisDeviceSubscribed(await manager(), deps());\n\t\t\t} catch (err) {\n\t\t\t\terror = describePushError(err, permission());\n\t\t\t} finally {\n\t\t\t\tbusy = false;\n\t\t\t}\n\t\t})();\n\t});\n\n\tasync function toggle() {\n\t\tbusy = true;\n\t\terror = '';\n\t\ttestResult = '';\n\t\ttestError = '';\n\t\tconst want = !subscribed;\n\t\ttry {\n\t\t\tconst r = await applyPushToggle(\n\t\t\t\tawait manager(),\n\t\t\t\tdeps(),\n\t\t\t\twant,\n\t\t\t\tpermission,\n\t\t\t);\n\t\t\tsubscribed = r.subscribed;\n\t\t\terror = r.error;\n\t\t\tvoid fetchConfig();\n\t\t} catch (err) {\n\t\t\t// The service worker itself is unavailable: nothing changed.\n\t\t\terror = describePushError(err, permission());\n\t\t} finally {\n\t\t\t// `checked={subscribed}` is one-way: the click already flipped the box,\n\t\t\t// and an unchanged `subscribed` would not flip it back. Always show\n\t\t\t// the real state.\n\t\t\tif (checkbox) checkbox.checked = subscribed;\n\t\t\tbusy = false;\n\t\t}\n\t}\n\n\tasync function sendTest() {\n\t\ttesting = true;\n\t\ttestResult = '';\n\t\ttestError = '';\n\t\ttry {\n\t\t\ttestResult = await sendTestNotification(deps(), currentSessionId);\n\t\t} catch (err) {\n\t\t\ttestError = (err as Error).message;\n\t\t} finally {\n\t\t\ttesting = false;\n\t\t}\n\t}\n</script>\n\n<div class=\"border-t border-brand-border p-4\">\n\t<h3\n\t\tclass=\"mb-3 text-xs font-bold tracking-wider text-brand-text-muted uppercase\"\n\t>\n\t\tAssistant notifications\n\t</h3>\n\t{#if !supported}\n\t\t<p class=\"text-xs text-brand-text-muted\">\n\t\t\tThis browser cannot receive push notifications (on iOS, add wherever to\n\t\t\tthe home screen first).\n\t\t</p>\n\t{:else}\n\t\t<div class=\"flex items-center gap-2 py-1\">\n\t\t\t<input\n\t\t\t\tid=\"assistant-push\"\n\t\t\t\ttype=\"checkbox\"\n\t\t\t\tbind:this={checkbox}\n\t\t\t\tchecked={subscribed}\n\t\t\t\tdisabled={busy}\n\t\t\t\tonchange={toggle}\n\t\t\t\tclass=\"h-4 w-4 rounded border-brand-border bg-brand-surface-2 text-brand-blue focus:ring-brand-blue focus:ring-offset-0\"\n\t\t\t/>\n\t\t\t<label\n\t\t\t\tfor=\"assistant-push\"\n\t\t\t\tclass=\"cursor-pointer text-xs text-brand-text select-none\"\n\t\t\t>\n\t\t\t\tPush notifications on this device\n\t\t\t</label>\n\t\t</div>\n\t\t<p class=\"pl-6 text-[10px] leading-relaxed text-brand-text-muted\">\n\t\t\tOnly when an agent deliberately notifies you (assistant_notify); tapping\n\t\t\tone opens the session it is about.\n\t\t</p>\n\t\t{#if error}\n\t\t\t<p\n\t\t\t\tclass=\"selectable pl-6 text-[10px] leading-relaxed break-words text-rose-400\"\n\t\t\t>\n\t\t\t\t{error}\n\t\t\t</p>\n\t\t{/if}\n\t\t{#if subscribed}\n\t\t\t<div class=\"mt-2 pl-6\">\n\t\t\t\t<button\n\t\t\t\t\ttype=\"button\"\n\t\t\t\t\tonclick={sendTest}\n\t\t\t\t\tdisabled={testing || busy}\n\t\t\t\t\tclass=\"rounded border border-brand-border bg-brand-surface-2 px-2 py-1 text-xs text-brand-text transition-colors hover:bg-brand-surface-3 disabled:opacity-50\"\n\t\t\t\t\ttitle=\"Send a notification through the server, as an agent's assistant_notify does\"\n\t\t\t\t>\n\t\t\t\t\t{testing ? 'Sending…' : 'Send test notification'}\n\t\t\t\t</button>\n\t\t\t\t{#if testResult}\n\t\t\t\t\t<p\n\t\t\t\t\t\tclass=\"selectable mt-1 text-[10px] leading-relaxed text-emerald-400\"\n\t\t\t\t\t>\n\t\t\t\t\t\t{testResult}\n\t\t\t\t\t</p>\n\t\t\t\t{/if}\n\t\t\t\t{#if testError}\n\t\t\t\t\t<p\n\t\t\t\t\t\tclass=\"selectable mt-1 text-[10px] leading-relaxed break-words text-rose-400\"\n\t\t\t\t\t>\n\t\t\t\t\t\t{testError}\n\t\t\t\t\t</p>\n\t\t\t\t{/if}\n\t\t\t</div>\n\t\t{/if}\n\t{/if}\n</div>\n","/**\n * The Telegram settings section's logic (server `telegram-channel.ts`): whether\n * it shows, what it says, and the re-pair action (`POST /telegram/repair`,\n * token-gated). Framework-free with `fetch` injected, so it is unit-tested with\n * fakes.\n */\n\n/** `GET /config` `assistant.telegram` (only while the assistant is active). */\nexport type TelegramStatus =\n\t| {enabled: false; state: 'disabled'}\n\t| {enabled: true; state: 'disabled'; error: string}\n\t| {enabled: true; state: 'starting'; bot: string | null; error?: string}\n\t| {\n\t\t\tenabled: true;\n\t\t\tstate: 'unpaired';\n\t\t\tcode: string | null;\n\t\t\tbot: string | null;\n\t\t\terror?: string;\n\t }\n\t| {\n\t\t\tenabled: true;\n\t\t\tstate: 'paired';\n\t\t\tuser: {id: string; name?: string; source: 'config' | 'pairing'};\n\t\t\tbot: string | null;\n\t\t\terror?: string;\n\t }\n\t| {enabled: true; state: 'error'; error: string; bot: string | null};\n\n/**\n * The section shows only while the assistant is active and Telegram is enabled\n * in the config (an enabled Telegram that could not start still shows, with its\n * error).\n */\nexport function telegramSectionVisible(status: {\n\tactive: boolean;\n\ttelegram?: TelegramStatus;\n}): boolean {\n\treturn status.active && !!status.telegram?.enabled;\n}\n\n/** The pairing instruction while unpaired. */\nexport function pairingInstruction(status: TelegramStatus): string | null {\n\tif (status.state !== 'unpaired' || !status.code) return null;\n\treturn `Send /pair ${status.code} to ${status.bot ?? 'the bot'} on Telegram.`;\n}\n\n/** Whether the re-pair action is offered (a pairing made by code; never a configured id). */\nexport function canRepair(status: TelegramStatus): boolean {\n\treturn status.state === 'paired' && status.user.source === 'pairing';\n}\n\nexport interface TelegramServerDeps {\n\tbaseUrl: string;\n\ttoken: string;\n\tfetch: (url: string, init?: RequestInit) => Promise<Response>;\n}\n\n/** Re-pair: the server forgets the pairing and issues a new code; resolves the new status. */\nexport async function requestTelegramRepair(\n\tdeps: TelegramServerDeps,\n): Promise<TelegramStatus> {\n\tconst qs = deps.token ? `?token=${encodeURIComponent(deps.token)}` : '';\n\tconst res = await deps.fetch(`${deps.baseUrl}/telegram/repair${qs}`, {\n\t\tmethod: 'POST',\n\t});\n\tconst data = await res.json().catch(() => ({}));\n\tif (!res.ok) throw new Error(data?.error || `HTTP ${res.status}`);\n\treturn data.telegram as TelegramStatus;\n}\n","/**\n * Copy text for the settings' Copy buttons: the async Clipboard API when the\n * browser offers it (a secure context), else the legacy `execCommand('copy')`\n * on a temporary off-screen textarea (plain-HTTP LAN access has no\n * `navigator.clipboard`). Resolves false when neither works, so the caller can\n * say to copy by hand (the value itself is selectable, `.selectable`).\n *\n * Framework-free with the browser objects injected, so it is unit-tested.\n */\nexport interface ClipboardDeps {\n\tclipboard?: {writeText(text: string): Promise<void>} | undefined;\n\tdocument?: Document | undefined;\n}\n\nfunction browserDeps(): ClipboardDeps {\n\treturn {\n\t\tclipboard:\n\t\t\ttypeof navigator !== 'undefined' ? navigator.clipboard : undefined,\n\t\tdocument: typeof document !== 'undefined' ? document : undefined,\n\t};\n}\n\nexport async function copyText(\n\ttext: string,\n\tdeps: ClipboardDeps = browserDeps(),\n): Promise<boolean> {\n\tif (deps.clipboard?.writeText) {\n\t\ttry {\n\t\t\tawait deps.clipboard.writeText(text);\n\t\t\treturn true;\n\t\t} catch {\n\t\t\t// Refused (no permission, not focused): try the legacy path.\n\t\t}\n\t}\n\tconst doc = deps.document;\n\tif (!doc?.body || typeof doc.execCommand !== 'function') return false;\n\tconst area = doc.createElement('textarea');\n\tarea.value = text;\n\tarea.setAttribute('readonly', '');\n\tarea.style.position = 'fixed';\n\tarea.style.top = '-1000px';\n\tarea.style.opacity = '0';\n\tdoc.body.appendChild(area);\n\ttry {\n\t\tarea.select();\n\t\treturn doc.execCommand('copy');\n\t} catch {\n\t\treturn false;\n\t} finally {\n\t\tdoc.body.removeChild(area);\n\t}\n}\n","<script lang=\"ts\">\n\t// A small \"Copy\" button for a value shown in the settings (a pairing code, an\n\t// id, an error): copies `value` (clipboard.ts: the Clipboard API, else the\n\t// legacy execCommand fallback) and confirms with \"Copied\" for a moment. When\n\t// nothing can copy, it says to copy by hand (the value is `.selectable`).\n\timport {onDestroy} from 'svelte';\n\timport {copyText} from '$lib/core/clipboard';\n\n\tlet {value, label = 'Copy'}: {value: string; label?: string} = $props();\n\n\tlet copyState = $state<'idle' | 'copied' | 'failed'>('idle');\n\tlet timer: ReturnType<typeof setTimeout> | null = null;\n\n\tasync function copy() {\n\t\tcopyState = (await copyText(value)) ? 'copied' : 'failed';\n\t\tif (timer) clearTimeout(timer);\n\t\ttimer = setTimeout(\n\t\t\t() => (copyState = 'idle'),\n\t\t\tcopyState === 'copied' ? 1500 : 4000,\n\t\t);\n\t}\n\tonDestroy(() => {\n\t\tif (timer) clearTimeout(timer);\n\t});\n</script>\n\n<button\n\ttype=\"button\"\n\tonclick={copy}\n\ttitle={copyState === 'failed'\n\t\t? 'Copying is not available here: select the text and copy it by hand'\n\t\t: `Copy ${value}`}\n\tclass=\"flex-shrink-0 rounded border border-brand-border bg-brand-surface-2 px-2 py-0.5 text-[10px] text-brand-text transition-colors hover:bg-brand-surface-3\"\n>\n\t{copyState === 'copied'\n\t\t? 'Copied'\n\t\t: copyState === 'failed'\n\t\t\t? 'Select to copy'\n\t\t\t: label}\n</button>\n","<script lang=\"ts\">\n\t// The assistant's Telegram settings (server/src/telegram-channel.ts): the\n\t// channel state, the one-time pairing code while unpaired, the paired user,\n\t// and the re-pair action. Rendered by the page only while the assistant is\n\t// active and `assistantTelegram.enabled` is set (telegramSectionVisible), so\n\t// with the assistant or Telegram off nothing of it shows.\n\timport {onDestroy} from 'svelte';\n\timport {\n\t\tcanRepair,\n\t\tpairingInstruction,\n\t\trequestTelegramRepair,\n\t\ttype TelegramStatus,\n\t} from '$lib/core/telegram-settings';\n\timport {fetchConfig, getBaseUrl, getToken} from '$lib/session-store';\n\timport CopyButton from './CopyButton.svelte';\n\n\tlet {status}: {status: TelegramStatus} = $props();\n\n\tlet busy = $state(false);\n\tlet error = $state('');\n\n\t// While waiting for the user to pair (or for the channel to start), refresh\n\t// the status so the section flips to \"paired\" once `/pair` arrives.\n\tlet timer: ReturnType<typeof setInterval> | null = null;\n\t$effect(() => {\n\t\tconst waiting = status.state === 'unpaired' || status.state === 'starting';\n\t\tif (waiting && !timer) {\n\t\t\ttimer = setInterval(() => void fetchConfig(), 3000);\n\t\t} else if (!waiting && timer) {\n\t\t\tclearInterval(timer);\n\t\t\ttimer = null;\n\t\t}\n\t});\n\tonDestroy(() => {\n\t\tif (timer) clearInterval(timer);\n\t});\n\n\tasync function repair() {\n\t\tif (\n\t\t\t!confirm(\n\t\t\t\t'Unpair the current Telegram account? A new pairing code will be issued.',\n\t\t\t)\n\t\t)\n\t\t\treturn;\n\t\tbusy = true;\n\t\terror = '';\n\t\ttry {\n\t\t\tawait requestTelegramRepair({\n\t\t\t\tbaseUrl: getBaseUrl(),\n\t\t\t\ttoken: getToken(),\n\t\t\t\tfetch: (url, init) => fetch(url, init),\n\t\t\t});\n\t\t\tawait fetchConfig();\n\t\t} catch (err) {\n\t\t\terror = (err as Error).message;\n\t\t} finally {\n\t\t\tbusy = false;\n\t\t}\n\t}\n</script>\n\n<div class=\"border-t border-brand-border p-4\">\n\t<h3\n\t\tclass=\"mb-3 text-xs font-bold tracking-wider text-brand-text-muted uppercase\"\n\t>\n\t\tAssistant on Telegram\n\t</h3>\n\t{#if status.state === 'disabled' || status.state === 'error'}\n\t\t<p class=\"selectable text-xs text-rose-400\">\n\t\t\tTelegram is disabled{'error' in status && status.error\n\t\t\t\t? `: ${status.error}`\n\t\t\t\t: ''}.\n\t\t</p>\n\t{:else if status.state === 'starting'}\n\t\t<p class=\"text-xs text-brand-text-muted\">Connecting to Telegram…</p>\n\t{:else if status.state === 'unpaired'}\n\t\t<p class=\"text-xs text-brand-text\">Not paired yet.</p>\n\t\t{#if status.code}\n\t\t\t<p class=\"selectable mt-2 text-xs text-brand-text-muted\">\n\t\t\t\t{pairingInstruction(status)}\n\t\t\t</p>\n\t\t\t<div class=\"mt-1 flex items-center gap-2\">\n\t\t\t\t<!-- `.selectable-all`, not Tailwind's `select-all`: the chrome's\n\t\t\t\t unlayered user-select: none beats any layered utility. -->\n\t\t\t\t<span\n\t\t\t\t\tclass=\"selectable-all font-mono text-base tracking-widest text-brand-text\"\n\t\t\t\t\t>{status.code}</span\n\t\t\t\t>\n\t\t\t\t<CopyButton value={status.code} />\n\t\t\t\t<CopyButton value={`/pair ${status.code}`} label=\"Copy /pair\" />\n\t\t\t</div>\n\t\t\t<p class=\"mt-1 text-[10px] leading-relaxed text-brand-text-muted\">\n\t\t\t\tThe code works once; anyone else writing to the bot is ignored.\n\t\t\t</p>\n\t\t{/if}\n\t{:else if status.state === 'paired'}\n\t\t<p class=\"selectable text-xs text-brand-text\">\n\t\t\tPaired with {status.user.name ?? `user ${status.user.id}`}{status.bot\n\t\t\t\t? ` via ${status.bot}`\n\t\t\t\t: ''}.\n\t\t</p>\n\t\t{#if status.user.source === 'config'}\n\t\t\t<p class=\"mt-1 text-[10px] leading-relaxed text-brand-text-muted\">\n\t\t\t\tSet in the config (assistantTelegram.userId).\n\t\t\t</p>\n\t\t{/if}\n\t\t{#if canRepair(status)}\n\t\t\t<button\n\t\t\t\tonclick={repair}\n\t\t\t\tdisabled={busy}\n\t\t\t\tclass=\"mt-2 rounded border border-brand-border bg-brand-surface-2 px-2 py-1 text-xs text-brand-text transition-colors hover:bg-brand-surface-3 disabled:opacity-50\"\n\t\t\t>\n\t\t\t\tRe-pair\n\t\t\t</button>\n\t\t{/if}\n\t{/if}\n\t{#if status.state !== 'disabled' && status.state !== 'error' && status.error}\n\t\t<p class=\"selectable mt-1 text-[10px] text-amber-400\">{status.error}</p>\n\t{/if}\n\t{#if error}\n\t\t<p class=\"selectable mt-1 text-[10px] text-rose-400\">{error}</p>\n\t{/if}\n</div>\n","// Media classification + the download/preview affordance predicate, extracted as\n// pure, framework-agnostic logic so both ChatMessageList.svelte and the unit\n// tests share one source of truth.\n//\n// Two concerns live here because they are the two halves of the same decision:\n// 1. extractDownloadablePath() - WHICH tool calls get a download/preview\n// affordance at all, and WHAT single path it operates on.\n// 2. mediaKind() - given such a path, WHAT kind of inline preview (if any) it\n// can drive, keyed purely by file extension (the path is already\n// server-validated, so no client-side MIME sniffing).\n\n/**\n * The kind of inline media a downloadable path can render as, or null when it is\n * not a previewable media file (fall back to the download chip only).\n *\n * All three kinds are defined now even though the first slice only USES `image`,\n * so the later audio/video slices are pure additions to the render layer.\n */\nexport type MediaKind = 'image' | 'audio' | 'video';\n\n// Extension → kind. Detection is by file EXTENSION only, case-insensitive; the\n// server has already validated the path, so we never sniff bytes on the client.\nconst IMAGE_EXTS = ['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'svg', 'avif'];\nconst AUDIO_EXTS = ['mp3', 'wav', 'oga', 'ogg', 'm4a', 'aac', 'flac', 'opus'];\nconst VIDEO_EXTS = ['mp4', 'webm', 'mov', 'm4v', 'ogv'];\n\nfunction extensionOf(path: string): string | null {\n\tif (!path || typeof path !== 'string') return null;\n\t// Consider only the final path segment so a dot in a directory name never\n\t// counts, and require a real extension after the last dot.\n\tconst base = path.split(/[/\\\\]/).pop() || '';\n\tconst dot = base.lastIndexOf('.');\n\tif (dot <= 0 || dot === base.length - 1) return null;\n\treturn base.slice(dot + 1).toLowerCase();\n}\n\n/**\n * Classify a file path into an inline media kind by its extension\n * (case-insensitive), or null for anything else (including directory/search\n * paths, which have no media extension).\n */\nexport function mediaKind(path: string): MediaKind | null {\n\tconst ext = extensionOf(path);\n\tif (!ext) return null;\n\tif (IMAGE_EXTS.includes(ext)) return 'image';\n\tif (AUDIO_EXTS.includes(ext)) return 'audio';\n\tif (VIDEO_EXTS.includes(ext)) return 'video';\n\treturn null;\n}\n\n/**\n * Return the single file path a tool call operated on when it qualifies for the\n * download/preview affordance, else null. Narrowed to `read` + `attach_file`\n * ONLY: those are the two tools where a download/preview is meaningful — an\n * intentional attachment, or a file the agent read. `write`/`edit` are write-side\n * operations (offering a download of a file the agent just wrote is noise) and\n * are deliberately excluded, as are `ls`/`grep`/`find` (their path arg is a\n * directory or search scope, not a downloadable file). Suppressed on errors.\n */\nexport function extractDownloadablePath(\n\ttoolName: string,\n\targsObj: Record<string, any> | null,\n\tisError: boolean,\n): string | null {\n\tif (isError || !argsObj) return null;\n\tconst name = (toolName || '').toLowerCase();\n\tif (!['attach_file', 'read'].includes(name)) return null;\n\tconst pathVal = argsObj.path || argsObj.filepath || argsObj.file;\n\tif (!pathVal || typeof pathVal !== 'string') return null;\n\treturn pathVal.trim() || null;\n}\n","// The SPOKEN-REPLY FALLBACK: what conversation mode speaks when the agent did\n// not call `say` for a turn.\n//\n// WHY THIS EXISTS. Conversation mode's spoken reply was designed to come ONLY\n// from the agent's explicit `say` call, and the agent is told a spoken\n// conversation is active (the per-turn conversation-mode signal, ADR 0004). That\n// is the right primary path: the agent authors a short spoken line, distinct from\n// its full written answer. But it is a REQUEST, and compliance is a model\n// property, not something the client controls. Measured against the local model a\n// reported session actually ran on (a 35B), a turn with the injected hint called\n// `say` roughly half the time, and almost never at the post-tool-result synthesis\n// call. So a mode whose whole point is \"I can listen to the reply\" went silent for\n// entire turns, and the user had to nag (\"why don't you speak?\") to get audio.\n//\n// The fallback closes that gap WITHOUT touching the agent contract: when a turn\n// settles with spoken replies active and no `say` was spoken, the client speaks a\n// short, plain-text lead-in derived from the written reply it already has. It is\n// strictly a SAFETY NET:\n// - `say` always wins (a turn that spoke is never re-spoken by the fallback),\n// - the full written reply is never modified, hidden or truncated on screen, and\n// - what is spoken is deliberately SHORT, because a whole written answer read\n// aloud (code blocks, URLs, bullet lists) is worse than useless.\n//\n// Pure and framework-free so it is unit-testable without jsdom, mirroring\n// core/collapse-reply.ts and core/hands-free.ts.\n\n/** Roughly how much of a written reply is worth reading aloud. */\nexport const FALLBACK_MAX_CHARS = 320;\n\n/**\n * Turn a written markdown reply into something worth SPEAKING, or '' when there\n * is nothing speakable in it.\n *\n * Drops what is noise out loud rather than trying to read everything:\n * - fenced code blocks (and any reply that is only code speaks as ''),\n * - inline code/emphasis/heading/quote/list markers (the words are kept),\n * - link URLs (the link TEXT is kept: \"see [the docs](http://...)\" -> \"see the docs\"),\n * - bare URLs, which are unlistenable character by character.\n *\n * Then keeps the LEAD-IN only: whole sentences up to FALLBACK_MAX_CHARS (at least\n * one sentence, hard-capped mid-sentence with an ellipsis if that first sentence\n * is itself enormous). The written answer keeps every detail; this is the \"what\n * happened\" a listener needs to know whether to go and read it.\n */\nexport function spokenFallbackText(\n\treply: string,\n\tmaxChars = FALLBACK_MAX_CHARS,\n): string {\n\tconst withoutCode = (reply ?? '')\n\t\t// Fenced code blocks, including an unterminated trailing fence.\n\t\t.replace(/```[\\s\\S]*?(?:```|$)/g, ' ')\n\t\t// Indented code blocks are indistinguishable from wrapped prose often\n\t\t// enough that we leave them alone; inline code just loses its backticks.\n\t\t.replace(/`([^`]*)`/g, '$1');\n\n\tconst plain = withoutCode\n\t\t// Images first (their alt text is rarely worth speaking), then links.\n\t\t.replace(/!\\[[^\\]]*\\]\\([^)]*\\)/g, ' ')\n\t\t.replace(/\\[([^\\]]*)\\]\\([^)]*\\)/g, '$1')\n\t\t// Bare URLs read as gibberish out loud.\n\t\t.replace(/\\bhttps?:\\/\\/\\S+/gi, ' ')\n\t\t// Structural markers at the start of a line: heading, quote, list bullet.\n\t\t.replace(/^[ \\t]*(?:#{1,6}|>|[-*+]|\\d+[.)])[ \\t]+/gm, '')\n\t\t// Horizontal rules.\n\t\t.replace(/^[ \\t]*(?:[-*_][ \\t]*){3,}$/gm, ' ')\n\t\t// Emphasis markers around words we still want to speak.\n\t\t.replace(/(\\*\\*|__|\\*|_|~~)/g, '')\n\t\t.replace(/\\s+/g, ' ')\n\t\t.trim();\n\n\tif (!plain) return '';\n\tif (plain.length <= maxChars) return plain;\n\n\t// Prefer whole sentences: take as many as fit, but never return nothing just\n\t// because the first sentence is long.\n\tconst sentences = plain.match(/[^.!?]+[.!?]+(?:\\s|$)|[^.!?]+$/g) ?? [plain];\n\tlet out = '';\n\tfor (const sentence of sentences) {\n\t\tconst next = (out + sentence).trimEnd();\n\t\tif (out && next.length > maxChars) break;\n\t\tout = next;\n\t\tif (out.length >= maxChars) break;\n\t}\n\tout = out.trim();\n\tif (!out) out = plain;\n\tif (out.length > maxChars) out = `${out.slice(0, maxChars).trimEnd()}...`;\n\treturn out;\n}\n\n/**\n * Whether the settling turn should be spoken by the fallback.\n *\n * - `active`: the `speakReplies` knob is ACTIVE (which already folds in the\n * conversation-mode master gate; see isKnobActive). With spoken replies off,\n * nothing is ever spoken, fallback included.\n * - `spokeThisTurn`: a `say` reply was already spoken for this turn. The agent's\n * own spoken line always wins; the fallback exists only for its absence.\n * - `reply`: the final assistant text of the settled turn (may be empty, e.g. a\n * turn that only ran tools).\n */\nexport function shouldSpeakFallback(opts: {\n\tactive: boolean;\n\tspokeThisTurn: boolean;\n\treply: string;\n}): boolean {\n\tif (!opts.active) return false;\n\tif (opts.spokeThisTurn) return false;\n\treturn spokenFallbackText(opts.reply).length > 0;\n}\n","// Conversation mode's `collapseLongReplies` knob de-emphasises LONG written\n// assistant replies so the short spoken summary (the `say` card) is the focus\n// and the transcript stays glanceable during a hands-busy spoken exchange.\n//\n// This is a DISPLAY concern ONLY: the full written reply is NEVER deleted,\n// hidden, or destructively truncated. A collapsed reply is merely clamped/\n// de-emphasised and ALWAYS remains expandable and fully readable (the reader's\n// escape hatch). When the knob is inactive (conversation mode off, or the knob\n// off), replies render exactly as today. The underlying transcript/message\n// content is untouched either way.\n//\n// This module is the pure decision seam ChatMessageList.svelte consumes (mirror\n// of core/speak.ts for the `say` card): \"should THIS reply render collapsed\n// right now?\" The gating of the knob itself (conversation mode on AND\n// collapseLongReplies on) lives upstream in core/conversation-mode.ts's\n// isKnobActive; the `active` argument here already folds that in.\n\n/**\n * How many characters make a written reply \"long\" enough to collapse. Below\n * this a reply is short enough to leave alone (collapsing it would be pure\n * noise). Tuned to spare typical short answers while catching the long,\n * code-heavy replies conversation mode is meant to de-emphasise.\n *\n * DECISION (recorded here, the natural choice site): the threshold is a fixed\n * char count, NOT a new user-configurable knob. Rationale: the task scope is a\n * boolean knob (`collapseLongReplies`) plus the collapse behaviour; adding a\n * \"how long is long\" setting would be a new user-visible config surface the\n * conversation-mode knobs registry does not define, so it is deliberately kept\n * an internal display heuristic. Alternative considered: derive from a line/\n * viewport-height measure. Rejected for v1 as it needs DOM measurement (harder\n * to unit-test at this pure seam) for no clear user benefit over a char count.\n * Touches nothing outside this module; a future task can promote it to a knob\n * without changing shouldCollapseReply's shape.\n */\nexport const LONG_REPLY_CHAR_THRESHOLD = 600;\n\n/**\n * Whether an assistant reply's written content is long enough to be a collapse\n * candidate. Missing/blank content is never long.\n */\nexport function isLongReply(content: string | undefined | null): boolean {\n\tif (!content) return false;\n\treturn content.length > LONG_REPLY_CHAR_THRESHOLD;\n}\n\n/**\n * Whether a given assistant reply should render COLLAPSED right now.\n *\n * True only when all of:\n * - `active`: the `collapseLongReplies` knob is active (which, being a gated\n * conversation knob, already requires conversation mode on -- see\n * isKnobActive). When false, this is always false: replies render exactly as\n * today, no collapse.\n * - `content` is long (past LONG_REPLY_CHAR_THRESHOLD). Short replies are never\n * collapsed.\n * - `expanded` is false: the user has not opened this reply. Expanding is the\n * escape hatch -- an opened reply renders in FULL and is never re-collapsed\n * behind the reader's back. The full text is therefore always reachable.\n *\n * Collapse is a display state; it never removes or truncates the stored reply.\n */\nexport function shouldCollapseReply(opts: {\n\tactive: boolean;\n\texpanded: boolean;\n\tcontent: string | undefined | null;\n}): boolean {\n\tif (!opts.active) return false;\n\tif (opts.expanded) return false;\n\treturn isLongReply(opts.content);\n}\n","/**\n * marked v15.0.12 - a markdown parser\n * Copyright (c) 2011-2025, Christopher Jeffrey. (MIT Licensed)\n * https://github.com/markedjs/marked\n */\n\n/**\n * DO NOT EDIT THIS FILE\n * The code in this file is generated from files in ./src/\n */\n\n\n// src/defaults.ts\nfunction _getDefaults() {\n return {\n async: false,\n breaks: false,\n extensions: null,\n gfm: true,\n hooks: null,\n pedantic: false,\n renderer: null,\n silent: false,\n tokenizer: null,\n walkTokens: null\n };\n}\nvar _defaults = _getDefaults();\nfunction changeDefaults(newDefaults) {\n _defaults = newDefaults;\n}\n\n// src/rules.ts\nvar noopTest = { exec: () => null };\nfunction edit(regex, opt = \"\") {\n let source = typeof regex === \"string\" ? regex : regex.source;\n const obj = {\n replace: (name, val) => {\n let valSource = typeof val === \"string\" ? val : val.source;\n valSource = valSource.replace(other.caret, \"$1\");\n source = source.replace(name, valSource);\n return obj;\n },\n getRegex: () => {\n return new RegExp(source, opt);\n }\n };\n return obj;\n}\nvar other = {\n codeRemoveIndent: /^(?: {1,4}| {0,3}\\t)/gm,\n outputLinkReplace: /\\\\([\\[\\]])/g,\n indentCodeCompensation: /^(\\s+)(?:```)/,\n beginningSpace: /^\\s+/,\n endingHash: /#$/,\n startingSpaceChar: /^ /,\n endingSpaceChar: / $/,\n nonSpaceChar: /[^ ]/,\n newLineCharGlobal: /\\n/g,\n tabCharGlobal: /\\t/g,\n multipleSpaceGlobal: /\\s+/g,\n blankLine: /^[ \\t]*$/,\n doubleBlankLine: /\\n[ \\t]*\\n[ \\t]*$/,\n blockquoteStart: /^ {0,3}>/,\n blockquoteSetextReplace: /\\n {0,3}((?:=+|-+) *)(?=\\n|$)/g,\n blockquoteSetextReplace2: /^ {0,3}>[ \\t]?/gm,\n listReplaceTabs: /^\\t+/,\n listReplaceNesting: /^ {1,4}(?=( {4})*[^ ])/g,\n listIsTask: /^\\[[ xX]\\] /,\n listReplaceTask: /^\\[[ xX]\\] +/,\n anyLine: /\\n.*\\n/,\n hrefBrackets: /^<(.*)>$/,\n tableDelimiter: /[:|]/,\n tableAlignChars: /^\\||\\| *$/g,\n tableRowBlankLine: /\\n[ \\t]*$/,\n tableAlignRight: /^ *-+: *$/,\n tableAlignCenter: /^ *:-+: *$/,\n tableAlignLeft: /^ *:-+ *$/,\n startATag: /^<a /i,\n endATag: /^<\\/a>/i,\n startPreScriptTag: /^<(pre|code|kbd|script)(\\s|>)/i,\n endPreScriptTag: /^<\\/(pre|code|kbd|script)(\\s|>)/i,\n startAngleBracket: /^</,\n endAngleBracket: />$/,\n pedanticHrefTitle: /^([^'\"]*[^\\s])\\s+(['\"])(.*)\\2/,\n unicodeAlphaNumeric: /[\\p{L}\\p{N}]/u,\n escapeTest: /[&<>\"']/,\n escapeReplace: /[&<>\"']/g,\n escapeTestNoEncode: /[<>\"']|&(?!(#\\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\\w+);)/,\n escapeReplaceNoEncode: /[<>\"']|&(?!(#\\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\\w+);)/g,\n unescapeTest: /&(#(?:\\d+)|(?:#x[0-9A-Fa-f]+)|(?:\\w+));?/ig,\n caret: /(^|[^\\[])\\^/g,\n percentDecode: /%25/g,\n findPipe: /\\|/g,\n splitPipe: / \\|/,\n slashPipe: /\\\\\\|/g,\n carriageReturn: /\\r\\n|\\r/g,\n spaceLine: /^ +$/gm,\n notSpaceStart: /^\\S*/,\n endingNewline: /\\n$/,\n listItemRegex: (bull) => new RegExp(`^( {0,3}${bull})((?:[\t ][^\\\\n]*)?(?:\\\\n|$))`),\n nextBulletRegex: (indent) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:[*+-]|\\\\d{1,9}[.)])((?:[ \t][^\\\\n]*)?(?:\\\\n|$))`),\n hrRegex: (indent) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\\\* *){3,})(?:\\\\n+|$)`),\n fencesBeginRegex: (indent) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:\\`\\`\\`|~~~)`),\n headingBeginRegex: (indent) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}#`),\n htmlBeginRegex: (indent) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}<(?:[a-z].*>|!--)`, \"i\")\n};\nvar newline = /^(?:[ \\t]*(?:\\n|$))+/;\nvar blockCode = /^((?: {4}| {0,3}\\t)[^\\n]+(?:\\n(?:[ \\t]*(?:\\n|$))*)?)+/;\nvar fences = /^ {0,3}(`{3,}(?=[^`\\n]*(?:\\n|$))|~{3,})([^\\n]*)(?:\\n|$)(?:|([\\s\\S]*?)(?:\\n|$))(?: {0,3}\\1[~`]* *(?=\\n|$)|$)/;\nvar hr = /^ {0,3}((?:-[\\t ]*){3,}|(?:_[ \\t]*){3,}|(?:\\*[ \\t]*){3,})(?:\\n+|$)/;\nvar heading = /^ {0,3}(#{1,6})(?=\\s|$)(.*)(?:\\n+|$)/;\nvar bullet = /(?:[*+-]|\\d{1,9}[.)])/;\nvar lheadingCore = /^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\\n(?!\\s*?\\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\\n {0,3}(=+|-+) *(?:\\n+|$)/;\nvar lheading = edit(lheadingCore).replace(/bull/g, bullet).replace(/blockCode/g, /(?: {4}| {0,3}\\t)/).replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g, / {0,3}>/).replace(/heading/g, / {0,3}#{1,6}/).replace(/html/g, / {0,3}<[^\\n>]+>\\n/).replace(/\\|table/g, \"\").getRegex();\nvar lheadingGfm = edit(lheadingCore).replace(/bull/g, bullet).replace(/blockCode/g, /(?: {4}| {0,3}\\t)/).replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g, / {0,3}>/).replace(/heading/g, / {0,3}#{1,6}/).replace(/html/g, / {0,3}<[^\\n>]+>\\n/).replace(/table/g, / {0,3}\\|?(?:[:\\- ]*\\|)+[\\:\\- ]*\\n/).getRegex();\nvar _paragraph = /^([^\\n]+(?:\\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\\n)[^\\n]+)*)/;\nvar blockText = /^[^\\n]+/;\nvar _blockLabel = /(?!\\s*\\])(?:\\\\.|[^\\[\\]\\\\])+/;\nvar def = edit(/^ {0,3}\\[(label)\\]: *(?:\\n[ \\t]*)?([^<\\s][^\\s]*|<.*?>)(?:(?: +(?:\\n[ \\t]*)?| *\\n[ \\t]*)(title))? *(?:\\n+|$)/).replace(\"label\", _blockLabel).replace(\"title\", /(?:\"(?:\\\\\"?|[^\"\\\\])*\"|'[^'\\n]*(?:\\n[^'\\n]+)*\\n?'|\\([^()]*\\))/).getRegex();\nvar list = edit(/^( {0,3}bull)([ \\t][^\\n]+?)?(?:\\n|$)/).replace(/bull/g, bullet).getRegex();\nvar _tag = \"address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul\";\nvar _comment = /<!--(?:-?>|[\\s\\S]*?(?:-->|$))/;\nvar html = edit(\n \"^ {0,3}(?:<(script|pre|style|textarea)[\\\\s>][\\\\s\\\\S]*?(?:</\\\\1>[^\\\\n]*\\\\n+|$)|comment[^\\\\n]*(\\\\n+|$)|<\\\\?[\\\\s\\\\S]*?(?:\\\\?>\\\\n*|$)|<![A-Z][\\\\s\\\\S]*?(?:>\\\\n*|$)|<!\\\\[CDATA\\\\[[\\\\s\\\\S]*?(?:\\\\]\\\\]>\\\\n*|$)|</?(tag)(?: +|\\\\n|/?>)[\\\\s\\\\S]*?(?:(?:\\\\n[ \t]*)+\\\\n|$)|<(?!script|pre|style|textarea)([a-z][\\\\w-]*)(?:attribute)*? */?>(?=[ \\\\t]*(?:\\\\n|$))[\\\\s\\\\S]*?(?:(?:\\\\n[ \t]*)+\\\\n|$)|</(?!script|pre|style|textarea)[a-z][\\\\w-]*\\\\s*>(?=[ \\\\t]*(?:\\\\n|$))[\\\\s\\\\S]*?(?:(?:\\\\n[ \t]*)+\\\\n|$))\",\n \"i\"\n).replace(\"comment\", _comment).replace(\"tag\", _tag).replace(\"attribute\", / +[a-zA-Z:_][\\w.:-]*(?: *= *\"[^\"\\n]*\"| *= *'[^'\\n]*'| *= *[^\\s\"'=<>`]+)?/).getRegex();\nvar paragraph = edit(_paragraph).replace(\"hr\", hr).replace(\"heading\", \" {0,3}#{1,6}(?:\\\\s|$)\").replace(\"|lheading\", \"\").replace(\"|table\", \"\").replace(\"blockquote\", \" {0,3}>\").replace(\"fences\", \" {0,3}(?:`{3,}(?=[^`\\\\n]*\\\\n)|~{3,})[^\\\\n]*\\\\n\").replace(\"list\", \" {0,3}(?:[*+-]|1[.)]) \").replace(\"html\", \"</?(?:tag)(?: +|\\\\n|/?>)|<(?:script|pre|style|textarea|!--)\").replace(\"tag\", _tag).getRegex();\nvar blockquote = edit(/^( {0,3}> ?(paragraph|[^\\n]*)(?:\\n|$))+/).replace(\"paragraph\", paragraph).getRegex();\nvar blockNormal = {\n blockquote,\n code: blockCode,\n def,\n fences,\n heading,\n hr,\n html,\n lheading,\n list,\n newline,\n paragraph,\n table: noopTest,\n text: blockText\n};\nvar gfmTable = edit(\n \"^ *([^\\\\n ].*)\\\\n {0,3}((?:\\\\| *)?:?-+:? *(?:\\\\| *:?-+:? *)*(?:\\\\| *)?)(?:\\\\n((?:(?! *\\\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\\\n|$))*)\\\\n*|$)\"\n).replace(\"hr\", hr).replace(\"heading\", \" {0,3}#{1,6}(?:\\\\s|$)\").replace(\"blockquote\", \" {0,3}>\").replace(\"code\", \"(?: {4}| {0,3}\t)[^\\\\n]\").replace(\"fences\", \" {0,3}(?:`{3,}(?=[^`\\\\n]*\\\\n)|~{3,})[^\\\\n]*\\\\n\").replace(\"list\", \" {0,3}(?:[*+-]|1[.)]) \").replace(\"html\", \"</?(?:tag)(?: +|\\\\n|/?>)|<(?:script|pre|style|textarea|!--)\").replace(\"tag\", _tag).getRegex();\nvar blockGfm = {\n ...blockNormal,\n lheading: lheadingGfm,\n table: gfmTable,\n paragraph: edit(_paragraph).replace(\"hr\", hr).replace(\"heading\", \" {0,3}#{1,6}(?:\\\\s|$)\").replace(\"|lheading\", \"\").replace(\"table\", gfmTable).replace(\"blockquote\", \" {0,3}>\").replace(\"fences\", \" {0,3}(?:`{3,}(?=[^`\\\\n]*\\\\n)|~{3,})[^\\\\n]*\\\\n\").replace(\"list\", \" {0,3}(?:[*+-]|1[.)]) \").replace(\"html\", \"</?(?:tag)(?: +|\\\\n|/?>)|<(?:script|pre|style|textarea|!--)\").replace(\"tag\", _tag).getRegex()\n};\nvar blockPedantic = {\n ...blockNormal,\n html: edit(\n `^ *(?:comment *(?:\\\\n|\\\\s*$)|<(tag)[\\\\s\\\\S]+?</\\\\1> *(?:\\\\n{2,}|\\\\s*$)|<tag(?:\"[^\"]*\"|'[^']*'|\\\\s[^'\"/>\\\\s]*)*?/?> *(?:\\\\n{2,}|\\\\s*$))`\n ).replace(\"comment\", _comment).replace(/tag/g, \"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\\\b)\\\\w+(?!:|[^\\\\w\\\\s@]*@)\\\\b\").getRegex(),\n def: /^ *\\[([^\\]]+)\\]: *<?([^\\s>]+)>?(?: +([\"(][^\\n]+[\")]))? *(?:\\n+|$)/,\n heading: /^(#{1,6})(.*)(?:\\n+|$)/,\n fences: noopTest,\n // fences not supported\n lheading: /^(.+?)\\n {0,3}(=+|-+) *(?:\\n+|$)/,\n paragraph: edit(_paragraph).replace(\"hr\", hr).replace(\"heading\", \" *#{1,6} *[^\\n]\").replace(\"lheading\", lheading).replace(\"|table\", \"\").replace(\"blockquote\", \" {0,3}>\").replace(\"|fences\", \"\").replace(\"|list\", \"\").replace(\"|html\", \"\").replace(\"|tag\", \"\").getRegex()\n};\nvar escape = /^\\\\([!\"#$%&'()*+,\\-./:;<=>?@\\[\\]\\\\^_`{|}~])/;\nvar inlineCode = /^(`+)([^`]|[^`][\\s\\S]*?[^`])\\1(?!`)/;\nvar br = /^( {2,}|\\\\)\\n(?!\\s*$)/;\nvar inlineText = /^(`+|[^`])(?:(?= {2,}\\n)|[\\s\\S]*?(?:(?=[\\\\<!\\[`*_]|\\b_|$)|[^ ](?= {2,}\\n)))/;\nvar _punctuation = /[\\p{P}\\p{S}]/u;\nvar _punctuationOrSpace = /[\\s\\p{P}\\p{S}]/u;\nvar _notPunctuationOrSpace = /[^\\s\\p{P}\\p{S}]/u;\nvar punctuation = edit(/^((?![*_])punctSpace)/, \"u\").replace(/punctSpace/g, _punctuationOrSpace).getRegex();\nvar _punctuationGfmStrongEm = /(?!~)[\\p{P}\\p{S}]/u;\nvar _punctuationOrSpaceGfmStrongEm = /(?!~)[\\s\\p{P}\\p{S}]/u;\nvar _notPunctuationOrSpaceGfmStrongEm = /(?:[^\\s\\p{P}\\p{S}]|~)/u;\nvar blockSkip = /\\[[^[\\]]*?\\]\\((?:\\\\.|[^\\\\\\(\\)]|\\((?:\\\\.|[^\\\\\\(\\)])*\\))*\\)|`[^`]*?`|<[^<>]*?>/g;\nvar emStrongLDelimCore = /^(?:\\*+(?:((?!\\*)punct)|[^\\s*]))|^_+(?:((?!_)punct)|([^\\s_]))/;\nvar emStrongLDelim = edit(emStrongLDelimCore, \"u\").replace(/punct/g, _punctuation).getRegex();\nvar emStrongLDelimGfm = edit(emStrongLDelimCore, \"u\").replace(/punct/g, _punctuationGfmStrongEm).getRegex();\nvar emStrongRDelimAstCore = \"^[^_*]*?__[^_*]*?\\\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\\\*)punct(\\\\*+)(?=[\\\\s]|$)|notPunctSpace(\\\\*+)(?!\\\\*)(?=punctSpace|$)|(?!\\\\*)punctSpace(\\\\*+)(?=notPunctSpace)|[\\\\s](\\\\*+)(?!\\\\*)(?=punct)|(?!\\\\*)punct(\\\\*+)(?!\\\\*)(?=punct)|notPunctSpace(\\\\*+)(?=notPunctSpace)\";\nvar emStrongRDelimAst = edit(emStrongRDelimAstCore, \"gu\").replace(/notPunctSpace/g, _notPunctuationOrSpace).replace(/punctSpace/g, _punctuationOrSpace).replace(/punct/g, _punctuation).getRegex();\nvar emStrongRDelimAstGfm = edit(emStrongRDelimAstCore, \"gu\").replace(/notPunctSpace/g, _notPunctuationOrSpaceGfmStrongEm).replace(/punctSpace/g, _punctuationOrSpaceGfmStrongEm).replace(/punct/g, _punctuationGfmStrongEm).getRegex();\nvar emStrongRDelimUnd = edit(\n \"^[^_*]*?\\\\*\\\\*[^_*]*?_[^_*]*?(?=\\\\*\\\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)\",\n \"gu\"\n).replace(/notPunctSpace/g, _notPunctuationOrSpace).replace(/punctSpace/g, _punctuationOrSpace).replace(/punct/g, _punctuation).getRegex();\nvar anyPunctuation = edit(/\\\\(punct)/, \"gu\").replace(/punct/g, _punctuation).getRegex();\nvar autolink = edit(/^<(scheme:[^\\s\\x00-\\x1f<>]*|email)>/).replace(\"scheme\", /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace(\"email\", /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex();\nvar _inlineComment = edit(_comment).replace(\"(?:-->|$)\", \"-->\").getRegex();\nvar tag = edit(\n \"^comment|^</[a-zA-Z][\\\\w:-]*\\\\s*>|^<[a-zA-Z][\\\\w-]*(?:attribute)*?\\\\s*/?>|^<\\\\?[\\\\s\\\\S]*?\\\\?>|^<![a-zA-Z]+\\\\s[\\\\s\\\\S]*?>|^<!\\\\[CDATA\\\\[[\\\\s\\\\S]*?\\\\]\\\\]>\"\n).replace(\"comment\", _inlineComment).replace(\"attribute\", /\\s+[a-zA-Z:_][\\w.:-]*(?:\\s*=\\s*\"[^\"]*\"|\\s*=\\s*'[^']*'|\\s*=\\s*[^\\s\"'=<>`]+)?/).getRegex();\nvar _inlineLabel = /(?:\\[(?:\\\\.|[^\\[\\]\\\\])*\\]|\\\\.|`[^`]*`|[^\\[\\]\\\\`])*?/;\nvar link = edit(/^!?\\[(label)\\]\\(\\s*(href)(?:(?:[ \\t]*(?:\\n[ \\t]*)?)(title))?\\s*\\)/).replace(\"label\", _inlineLabel).replace(\"href\", /<(?:\\\\.|[^\\n<>\\\\])+>|[^ \\t\\n\\x00-\\x1f]*/).replace(\"title\", /\"(?:\\\\\"?|[^\"\\\\])*\"|'(?:\\\\'?|[^'\\\\])*'|\\((?:\\\\\\)?|[^)\\\\])*\\)/).getRegex();\nvar reflink = edit(/^!?\\[(label)\\]\\[(ref)\\]/).replace(\"label\", _inlineLabel).replace(\"ref\", _blockLabel).getRegex();\nvar nolink = edit(/^!?\\[(ref)\\](?:\\[\\])?/).replace(\"ref\", _blockLabel).getRegex();\nvar reflinkSearch = edit(\"reflink|nolink(?!\\\\()\", \"g\").replace(\"reflink\", reflink).replace(\"nolink\", nolink).getRegex();\nvar inlineNormal = {\n _backpedal: noopTest,\n // only used for GFM url\n anyPunctuation,\n autolink,\n blockSkip,\n br,\n code: inlineCode,\n del: noopTest,\n emStrongLDelim,\n emStrongRDelimAst,\n emStrongRDelimUnd,\n escape,\n link,\n nolink,\n punctuation,\n reflink,\n reflinkSearch,\n tag,\n text: inlineText,\n url: noopTest\n};\nvar inlinePedantic = {\n ...inlineNormal,\n link: edit(/^!?\\[(label)\\]\\((.*?)\\)/).replace(\"label\", _inlineLabel).getRegex(),\n reflink: edit(/^!?\\[(label)\\]\\s*\\[([^\\]]*)\\]/).replace(\"label\", _inlineLabel).getRegex()\n};\nvar inlineGfm = {\n ...inlineNormal,\n emStrongRDelimAst: emStrongRDelimAstGfm,\n emStrongLDelim: emStrongLDelimGfm,\n url: edit(/^((?:ftp|https?):\\/\\/|www\\.)(?:[a-zA-Z0-9\\-]+\\.?)+[^\\s<]*|^email/, \"i\").replace(\"email\", /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),\n _backpedal: /(?:[^?!.,:;*_'\"~()&]+|\\([^)]*\\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'\"~)]+(?!$))+/,\n del: /^(~~?)(?=[^\\s~])((?:\\\\.|[^\\\\])*?(?:\\\\.|[^\\s~\\\\]))\\1(?=[^~]|$)/,\n text: /^([`~]+|[^`~])(?:(?= {2,}\\n)|(?=[a-zA-Z0-9.!#$%&'*+\\/=?_`{\\|}~-]+@)|[\\s\\S]*?(?:(?=[\\\\<!\\[`*~_]|\\b_|https?:\\/\\/|ftp:\\/\\/|www\\.|$)|[^ ](?= {2,}\\n)|[^a-zA-Z0-9.!#$%&'*+\\/=?_`{\\|}~-](?=[a-zA-Z0-9.!#$%&'*+\\/=?_`{\\|}~-]+@)))/\n};\nvar inlineBreaks = {\n ...inlineGfm,\n br: edit(br).replace(\"{2,}\", \"*\").getRegex(),\n text: edit(inlineGfm.text).replace(\"\\\\b_\", \"\\\\b_| {2,}\\\\n\").replace(/\\{2,\\}/g, \"*\").getRegex()\n};\nvar block = {\n normal: blockNormal,\n gfm: blockGfm,\n pedantic: blockPedantic\n};\nvar inline = {\n normal: inlineNormal,\n gfm: inlineGfm,\n breaks: inlineBreaks,\n pedantic: inlinePedantic\n};\n\n// src/helpers.ts\nvar escapeReplacements = {\n \"&\": \"&amp;\",\n \"<\": \"&lt;\",\n \">\": \"&gt;\",\n '\"': \"&quot;\",\n \"'\": \"&#39;\"\n};\nvar getEscapeReplacement = (ch) => escapeReplacements[ch];\nfunction escape2(html2, encode) {\n if (encode) {\n if (other.escapeTest.test(html2)) {\n return html2.replace(other.escapeReplace, getEscapeReplacement);\n }\n } else {\n if (other.escapeTestNoEncode.test(html2)) {\n return html2.replace(other.escapeReplaceNoEncode, getEscapeReplacement);\n }\n }\n return html2;\n}\nfunction cleanUrl(href) {\n try {\n href = encodeURI(href).replace(other.percentDecode, \"%\");\n } catch {\n return null;\n }\n return href;\n}\nfunction splitCells(tableRow, count) {\n const row = tableRow.replace(other.findPipe, (match, offset, str) => {\n let escaped = false;\n let curr = offset;\n while (--curr >= 0 && str[curr] === \"\\\\\") escaped = !escaped;\n if (escaped) {\n return \"|\";\n } else {\n return \" |\";\n }\n }), cells = row.split(other.splitPipe);\n let i = 0;\n if (!cells[0].trim()) {\n cells.shift();\n }\n if (cells.length > 0 && !cells.at(-1)?.trim()) {\n cells.pop();\n }\n if (count) {\n if (cells.length > count) {\n cells.splice(count);\n } else {\n while (cells.length < count) cells.push(\"\");\n }\n }\n for (; i < cells.length; i++) {\n cells[i] = cells[i].trim().replace(other.slashPipe, \"|\");\n }\n return cells;\n}\nfunction rtrim(str, c, invert) {\n const l = str.length;\n if (l === 0) {\n return \"\";\n }\n let suffLen = 0;\n while (suffLen < l) {\n const currChar = str.charAt(l - suffLen - 1);\n if (currChar === c && !invert) {\n suffLen++;\n } else if (currChar !== c && invert) {\n suffLen++;\n } else {\n break;\n }\n }\n return str.slice(0, l - suffLen);\n}\nfunction findClosingBracket(str, b) {\n if (str.indexOf(b[1]) === -1) {\n return -1;\n }\n let level = 0;\n for (let i = 0; i < str.length; i++) {\n if (str[i] === \"\\\\\") {\n i++;\n } else if (str[i] === b[0]) {\n level++;\n } else if (str[i] === b[1]) {\n level--;\n if (level < 0) {\n return i;\n }\n }\n }\n if (level > 0) {\n return -2;\n }\n return -1;\n}\n\n// src/Tokenizer.ts\nfunction outputLink(cap, link2, raw, lexer2, rules) {\n const href = link2.href;\n const title = link2.title || null;\n const text = cap[1].replace(rules.other.outputLinkReplace, \"$1\");\n lexer2.state.inLink = true;\n const token = {\n type: cap[0].charAt(0) === \"!\" ? \"image\" : \"link\",\n raw,\n href,\n title,\n text,\n tokens: lexer2.inlineTokens(text)\n };\n lexer2.state.inLink = false;\n return token;\n}\nfunction indentCodeCompensation(raw, text, rules) {\n const matchIndentToCode = raw.match(rules.other.indentCodeCompensation);\n if (matchIndentToCode === null) {\n return text;\n }\n const indentToCode = matchIndentToCode[1];\n return text.split(\"\\n\").map((node) => {\n const matchIndentInNode = node.match(rules.other.beginningSpace);\n if (matchIndentInNode === null) {\n return node;\n }\n const [indentInNode] = matchIndentInNode;\n if (indentInNode.length >= indentToCode.length) {\n return node.slice(indentToCode.length);\n }\n return node;\n }).join(\"\\n\");\n}\nvar _Tokenizer = class {\n options;\n rules;\n // set by the lexer\n lexer;\n // set by the lexer\n constructor(options2) {\n this.options = options2 || _defaults;\n }\n space(src) {\n const cap = this.rules.block.newline.exec(src);\n if (cap && cap[0].length > 0) {\n return {\n type: \"space\",\n raw: cap[0]\n };\n }\n }\n code(src) {\n const cap = this.rules.block.code.exec(src);\n if (cap) {\n const text = cap[0].replace(this.rules.other.codeRemoveIndent, \"\");\n return {\n type: \"code\",\n raw: cap[0],\n codeBlockStyle: \"indented\",\n text: !this.options.pedantic ? rtrim(text, \"\\n\") : text\n };\n }\n }\n fences(src) {\n const cap = this.rules.block.fences.exec(src);\n if (cap) {\n const raw = cap[0];\n const text = indentCodeCompensation(raw, cap[3] || \"\", this.rules);\n return {\n type: \"code\",\n raw,\n lang: cap[2] ? cap[2].trim().replace(this.rules.inline.anyPunctuation, \"$1\") : cap[2],\n text\n };\n }\n }\n heading(src) {\n const cap = this.rules.block.heading.exec(src);\n if (cap) {\n let text = cap[2].trim();\n if (this.rules.other.endingHash.test(text)) {\n const trimmed = rtrim(text, \"#\");\n if (this.options.pedantic) {\n text = trimmed.trim();\n } else if (!trimmed || this.rules.other.endingSpaceChar.test(trimmed)) {\n text = trimmed.trim();\n }\n }\n return {\n type: \"heading\",\n raw: cap[0],\n depth: cap[1].length,\n text,\n tokens: this.lexer.inline(text)\n };\n }\n }\n hr(src) {\n const cap = this.rules.block.hr.exec(src);\n if (cap) {\n return {\n type: \"hr\",\n raw: rtrim(cap[0], \"\\n\")\n };\n }\n }\n blockquote(src) {\n const cap = this.rules.block.blockquote.exec(src);\n if (cap) {\n let lines = rtrim(cap[0], \"\\n\").split(\"\\n\");\n let raw = \"\";\n let text = \"\";\n const tokens = [];\n while (lines.length > 0) {\n let inBlockquote = false;\n const currentLines = [];\n let i;\n for (i = 0; i < lines.length; i++) {\n if (this.rules.other.blockquoteStart.test(lines[i])) {\n currentLines.push(lines[i]);\n inBlockquote = true;\n } else if (!inBlockquote) {\n currentLines.push(lines[i]);\n } else {\n break;\n }\n }\n lines = lines.slice(i);\n const currentRaw = currentLines.join(\"\\n\");\n const currentText = currentRaw.replace(this.rules.other.blockquoteSetextReplace, \"\\n $1\").replace(this.rules.other.blockquoteSetextReplace2, \"\");\n raw = raw ? `${raw}\n${currentRaw}` : currentRaw;\n text = text ? `${text}\n${currentText}` : currentText;\n const top = this.lexer.state.top;\n this.lexer.state.top = true;\n this.lexer.blockTokens(currentText, tokens, true);\n this.lexer.state.top = top;\n if (lines.length === 0) {\n break;\n }\n const lastToken = tokens.at(-1);\n if (lastToken?.type === \"code\") {\n break;\n } else if (lastToken?.type === \"blockquote\") {\n const oldToken = lastToken;\n const newText = oldToken.raw + \"\\n\" + lines.join(\"\\n\");\n const newToken = this.blockquote(newText);\n tokens[tokens.length - 1] = newToken;\n raw = raw.substring(0, raw.length - oldToken.raw.length) + newToken.raw;\n text = text.substring(0, text.length - oldToken.text.length) + newToken.text;\n break;\n } else if (lastToken?.type === \"list\") {\n const oldToken = lastToken;\n const newText = oldToken.raw + \"\\n\" + lines.join(\"\\n\");\n const newToken = this.list(newText);\n tokens[tokens.length - 1] = newToken;\n raw = raw.substring(0, raw.length - lastToken.raw.length) + newToken.raw;\n text = text.substring(0, text.length - oldToken.raw.length) + newToken.raw;\n lines = newText.substring(tokens.at(-1).raw.length).split(\"\\n\");\n continue;\n }\n }\n return {\n type: \"blockquote\",\n raw,\n tokens,\n text\n };\n }\n }\n list(src) {\n let cap = this.rules.block.list.exec(src);\n if (cap) {\n let bull = cap[1].trim();\n const isordered = bull.length > 1;\n const list2 = {\n type: \"list\",\n raw: \"\",\n ordered: isordered,\n start: isordered ? +bull.slice(0, -1) : \"\",\n loose: false,\n items: []\n };\n bull = isordered ? `\\\\d{1,9}\\\\${bull.slice(-1)}` : `\\\\${bull}`;\n if (this.options.pedantic) {\n bull = isordered ? bull : \"[*+-]\";\n }\n const itemRegex = this.rules.other.listItemRegex(bull);\n let endsWithBlankLine = false;\n while (src) {\n let endEarly = false;\n let raw = \"\";\n let itemContents = \"\";\n if (!(cap = itemRegex.exec(src))) {\n break;\n }\n if (this.rules.block.hr.test(src)) {\n break;\n }\n raw = cap[0];\n src = src.substring(raw.length);\n let line = cap[2].split(\"\\n\", 1)[0].replace(this.rules.other.listReplaceTabs, (t) => \" \".repeat(3 * t.length));\n let nextLine = src.split(\"\\n\", 1)[0];\n let blankLine = !line.trim();\n let indent = 0;\n if (this.options.pedantic) {\n indent = 2;\n itemContents = line.trimStart();\n } else if (blankLine) {\n indent = cap[1].length + 1;\n } else {\n indent = cap[2].search(this.rules.other.nonSpaceChar);\n indent = indent > 4 ? 1 : indent;\n itemContents = line.slice(indent);\n indent += cap[1].length;\n }\n if (blankLine && this.rules.other.blankLine.test(nextLine)) {\n raw += nextLine + \"\\n\";\n src = src.substring(nextLine.length + 1);\n endEarly = true;\n }\n if (!endEarly) {\n const nextBulletRegex = this.rules.other.nextBulletRegex(indent);\n const hrRegex = this.rules.other.hrRegex(indent);\n const fencesBeginRegex = this.rules.other.fencesBeginRegex(indent);\n const headingBeginRegex = this.rules.other.headingBeginRegex(indent);\n const htmlBeginRegex = this.rules.other.htmlBeginRegex(indent);\n while (src) {\n const rawLine = src.split(\"\\n\", 1)[0];\n let nextLineWithoutTabs;\n nextLine = rawLine;\n if (this.options.pedantic) {\n nextLine = nextLine.replace(this.rules.other.listReplaceNesting, \" \");\n nextLineWithoutTabs = nextLine;\n } else {\n nextLineWithoutTabs = nextLine.replace(this.rules.other.tabCharGlobal, \" \");\n }\n if (fencesBeginRegex.test(nextLine)) {\n break;\n }\n if (headingBeginRegex.test(nextLine)) {\n break;\n }\n if (htmlBeginRegex.test(nextLine)) {\n break;\n }\n if (nextBulletRegex.test(nextLine)) {\n break;\n }\n if (hrRegex.test(nextLine)) {\n break;\n }\n if (nextLineWithoutTabs.search(this.rules.other.nonSpaceChar) >= indent || !nextLine.trim()) {\n itemContents += \"\\n\" + nextLineWithoutTabs.slice(indent);\n } else {\n if (blankLine) {\n break;\n }\n if (line.replace(this.rules.other.tabCharGlobal, \" \").search(this.rules.other.nonSpaceChar) >= 4) {\n break;\n }\n if (fencesBeginRegex.test(line)) {\n break;\n }\n if (headingBeginRegex.test(line)) {\n break;\n }\n if (hrRegex.test(line)) {\n break;\n }\n itemContents += \"\\n\" + nextLine;\n }\n if (!blankLine && !nextLine.trim()) {\n blankLine = true;\n }\n raw += rawLine + \"\\n\";\n src = src.substring(rawLine.length + 1);\n line = nextLineWithoutTabs.slice(indent);\n }\n }\n if (!list2.loose) {\n if (endsWithBlankLine) {\n list2.loose = true;\n } else if (this.rules.other.doubleBlankLine.test(raw)) {\n endsWithBlankLine = true;\n }\n }\n let istask = null;\n let ischecked;\n if (this.options.gfm) {\n istask = this.rules.other.listIsTask.exec(itemContents);\n if (istask) {\n ischecked = istask[0] !== \"[ ] \";\n itemContents = itemContents.replace(this.rules.other.listReplaceTask, \"\");\n }\n }\n list2.items.push({\n type: \"list_item\",\n raw,\n task: !!istask,\n checked: ischecked,\n loose: false,\n text: itemContents,\n tokens: []\n });\n list2.raw += raw;\n }\n const lastItem = list2.items.at(-1);\n if (lastItem) {\n lastItem.raw = lastItem.raw.trimEnd();\n lastItem.text = lastItem.text.trimEnd();\n } else {\n return;\n }\n list2.raw = list2.raw.trimEnd();\n for (let i = 0; i < list2.items.length; i++) {\n this.lexer.state.top = false;\n list2.items[i].tokens = this.lexer.blockTokens(list2.items[i].text, []);\n if (!list2.loose) {\n const spacers = list2.items[i].tokens.filter((t) => t.type === \"space\");\n const hasMultipleLineBreaks = spacers.length > 0 && spacers.some((t) => this.rules.other.anyLine.test(t.raw));\n list2.loose = hasMultipleLineBreaks;\n }\n }\n if (list2.loose) {\n for (let i = 0; i < list2.items.length; i++) {\n list2.items[i].loose = true;\n }\n }\n return list2;\n }\n }\n html(src) {\n const cap = this.rules.block.html.exec(src);\n if (cap) {\n const token = {\n type: \"html\",\n block: true,\n raw: cap[0],\n pre: cap[1] === \"pre\" || cap[1] === \"script\" || cap[1] === \"style\",\n text: cap[0]\n };\n return token;\n }\n }\n def(src) {\n const cap = this.rules.block.def.exec(src);\n if (cap) {\n const tag2 = cap[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal, \" \");\n const href = cap[2] ? cap[2].replace(this.rules.other.hrefBrackets, \"$1\").replace(this.rules.inline.anyPunctuation, \"$1\") : \"\";\n const title = cap[3] ? cap[3].substring(1, cap[3].length - 1).replace(this.rules.inline.anyPunctuation, \"$1\") : cap[3];\n return {\n type: \"def\",\n tag: tag2,\n raw: cap[0],\n href,\n title\n };\n }\n }\n table(src) {\n const cap = this.rules.block.table.exec(src);\n if (!cap) {\n return;\n }\n if (!this.rules.other.tableDelimiter.test(cap[2])) {\n return;\n }\n const headers = splitCells(cap[1]);\n const aligns = cap[2].replace(this.rules.other.tableAlignChars, \"\").split(\"|\");\n const rows = cap[3]?.trim() ? cap[3].replace(this.rules.other.tableRowBlankLine, \"\").split(\"\\n\") : [];\n const item = {\n type: \"table\",\n raw: cap[0],\n header: [],\n align: [],\n rows: []\n };\n if (headers.length !== aligns.length) {\n return;\n }\n for (const align of aligns) {\n if (this.rules.other.tableAlignRight.test(align)) {\n item.align.push(\"right\");\n } else if (this.rules.other.tableAlignCenter.test(align)) {\n item.align.push(\"center\");\n } else if (this.rules.other.tableAlignLeft.test(align)) {\n item.align.push(\"left\");\n } else {\n item.align.push(null);\n }\n }\n for (let i = 0; i < headers.length; i++) {\n item.header.push({\n text: headers[i],\n tokens: this.lexer.inline(headers[i]),\n header: true,\n align: item.align[i]\n });\n }\n for (const row of rows) {\n item.rows.push(splitCells(row, item.header.length).map((cell, i) => {\n return {\n text: cell,\n tokens: this.lexer.inline(cell),\n header: false,\n align: item.align[i]\n };\n }));\n }\n return item;\n }\n lheading(src) {\n const cap = this.rules.block.lheading.exec(src);\n if (cap) {\n return {\n type: \"heading\",\n raw: cap[0],\n depth: cap[2].charAt(0) === \"=\" ? 1 : 2,\n text: cap[1],\n tokens: this.lexer.inline(cap[1])\n };\n }\n }\n paragraph(src) {\n const cap = this.rules.block.paragraph.exec(src);\n if (cap) {\n const text = cap[1].charAt(cap[1].length - 1) === \"\\n\" ? cap[1].slice(0, -1) : cap[1];\n return {\n type: \"paragraph\",\n raw: cap[0],\n text,\n tokens: this.lexer.inline(text)\n };\n }\n }\n text(src) {\n const cap = this.rules.block.text.exec(src);\n if (cap) {\n return {\n type: \"text\",\n raw: cap[0],\n text: cap[0],\n tokens: this.lexer.inline(cap[0])\n };\n }\n }\n escape(src) {\n const cap = this.rules.inline.escape.exec(src);\n if (cap) {\n return {\n type: \"escape\",\n raw: cap[0],\n text: cap[1]\n };\n }\n }\n tag(src) {\n const cap = this.rules.inline.tag.exec(src);\n if (cap) {\n if (!this.lexer.state.inLink && this.rules.other.startATag.test(cap[0])) {\n this.lexer.state.inLink = true;\n } else if (this.lexer.state.inLink && this.rules.other.endATag.test(cap[0])) {\n this.lexer.state.inLink = false;\n }\n if (!this.lexer.state.inRawBlock && this.rules.other.startPreScriptTag.test(cap[0])) {\n this.lexer.state.inRawBlock = true;\n } else if (this.lexer.state.inRawBlock && this.rules.other.endPreScriptTag.test(cap[0])) {\n this.lexer.state.inRawBlock = false;\n }\n return {\n type: \"html\",\n raw: cap[0],\n inLink: this.lexer.state.inLink,\n inRawBlock: this.lexer.state.inRawBlock,\n block: false,\n text: cap[0]\n };\n }\n }\n link(src) {\n const cap = this.rules.inline.link.exec(src);\n if (cap) {\n const trimmedUrl = cap[2].trim();\n if (!this.options.pedantic && this.rules.other.startAngleBracket.test(trimmedUrl)) {\n if (!this.rules.other.endAngleBracket.test(trimmedUrl)) {\n return;\n }\n const rtrimSlash = rtrim(trimmedUrl.slice(0, -1), \"\\\\\");\n if ((trimmedUrl.length - rtrimSlash.length) % 2 === 0) {\n return;\n }\n } else {\n const lastParenIndex = findClosingBracket(cap[2], \"()\");\n if (lastParenIndex === -2) {\n return;\n }\n if (lastParenIndex > -1) {\n const start = cap[0].indexOf(\"!\") === 0 ? 5 : 4;\n const linkLen = start + cap[1].length + lastParenIndex;\n cap[2] = cap[2].substring(0, lastParenIndex);\n cap[0] = cap[0].substring(0, linkLen).trim();\n cap[3] = \"\";\n }\n }\n let href = cap[2];\n let title = \"\";\n if (this.options.pedantic) {\n const link2 = this.rules.other.pedanticHrefTitle.exec(href);\n if (link2) {\n href = link2[1];\n title = link2[3];\n }\n } else {\n title = cap[3] ? cap[3].slice(1, -1) : \"\";\n }\n href = href.trim();\n if (this.rules.other.startAngleBracket.test(href)) {\n if (this.options.pedantic && !this.rules.other.endAngleBracket.test(trimmedUrl)) {\n href = href.slice(1);\n } else {\n href = href.slice(1, -1);\n }\n }\n return outputLink(cap, {\n href: href ? href.replace(this.rules.inline.anyPunctuation, \"$1\") : href,\n title: title ? title.replace(this.rules.inline.anyPunctuation, \"$1\") : title\n }, cap[0], this.lexer, this.rules);\n }\n }\n reflink(src, links) {\n let cap;\n if ((cap = this.rules.inline.reflink.exec(src)) || (cap = this.rules.inline.nolink.exec(src))) {\n const linkString = (cap[2] || cap[1]).replace(this.rules.other.multipleSpaceGlobal, \" \");\n const link2 = links[linkString.toLowerCase()];\n if (!link2) {\n const text = cap[0].charAt(0);\n return {\n type: \"text\",\n raw: text,\n text\n };\n }\n return outputLink(cap, link2, cap[0], this.lexer, this.rules);\n }\n }\n emStrong(src, maskedSrc, prevChar = \"\") {\n let match = this.rules.inline.emStrongLDelim.exec(src);\n if (!match) return;\n if (match[3] && prevChar.match(this.rules.other.unicodeAlphaNumeric)) return;\n const nextChar = match[1] || match[2] || \"\";\n if (!nextChar || !prevChar || this.rules.inline.punctuation.exec(prevChar)) {\n const lLength = [...match[0]].length - 1;\n let rDelim, rLength, delimTotal = lLength, midDelimTotal = 0;\n const endReg = match[0][0] === \"*\" ? this.rules.inline.emStrongRDelimAst : this.rules.inline.emStrongRDelimUnd;\n endReg.lastIndex = 0;\n maskedSrc = maskedSrc.slice(-1 * src.length + lLength);\n while ((match = endReg.exec(maskedSrc)) != null) {\n rDelim = match[1] || match[2] || match[3] || match[4] || match[5] || match[6];\n if (!rDelim) continue;\n rLength = [...rDelim].length;\n if (match[3] || match[4]) {\n delimTotal += rLength;\n continue;\n } else if (match[5] || match[6]) {\n if (lLength % 3 && !((lLength + rLength) % 3)) {\n midDelimTotal += rLength;\n continue;\n }\n }\n delimTotal -= rLength;\n if (delimTotal > 0) continue;\n rLength = Math.min(rLength, rLength + delimTotal + midDelimTotal);\n const lastCharLength = [...match[0]][0].length;\n const raw = src.slice(0, lLength + match.index + lastCharLength + rLength);\n if (Math.min(lLength, rLength) % 2) {\n const text2 = raw.slice(1, -1);\n return {\n type: \"em\",\n raw,\n text: text2,\n tokens: this.lexer.inlineTokens(text2)\n };\n }\n const text = raw.slice(2, -2);\n return {\n type: \"strong\",\n raw,\n text,\n tokens: this.lexer.inlineTokens(text)\n };\n }\n }\n }\n codespan(src) {\n const cap = this.rules.inline.code.exec(src);\n if (cap) {\n let text = cap[2].replace(this.rules.other.newLineCharGlobal, \" \");\n const hasNonSpaceChars = this.rules.other.nonSpaceChar.test(text);\n const hasSpaceCharsOnBothEnds = this.rules.other.startingSpaceChar.test(text) && this.rules.other.endingSpaceChar.test(text);\n if (hasNonSpaceChars && hasSpaceCharsOnBothEnds) {\n text = text.substring(1, text.length - 1);\n }\n return {\n type: \"codespan\",\n raw: cap[0],\n text\n };\n }\n }\n br(src) {\n const cap = this.rules.inline.br.exec(src);\n if (cap) {\n return {\n type: \"br\",\n raw: cap[0]\n };\n }\n }\n del(src) {\n const cap = this.rules.inline.del.exec(src);\n if (cap) {\n return {\n type: \"del\",\n raw: cap[0],\n text: cap[2],\n tokens: this.lexer.inlineTokens(cap[2])\n };\n }\n }\n autolink(src) {\n const cap = this.rules.inline.autolink.exec(src);\n if (cap) {\n let text, href;\n if (cap[2] === \"@\") {\n text = cap[1];\n href = \"mailto:\" + text;\n } else {\n text = cap[1];\n href = text;\n }\n return {\n type: \"link\",\n raw: cap[0],\n text,\n href,\n tokens: [\n {\n type: \"text\",\n raw: text,\n text\n }\n ]\n };\n }\n }\n url(src) {\n let cap;\n if (cap = this.rules.inline.url.exec(src)) {\n let text, href;\n if (cap[2] === \"@\") {\n text = cap[0];\n href = \"mailto:\" + text;\n } else {\n let prevCapZero;\n do {\n prevCapZero = cap[0];\n cap[0] = this.rules.inline._backpedal.exec(cap[0])?.[0] ?? \"\";\n } while (prevCapZero !== cap[0]);\n text = cap[0];\n if (cap[1] === \"www.\") {\n href = \"http://\" + cap[0];\n } else {\n href = cap[0];\n }\n }\n return {\n type: \"link\",\n raw: cap[0],\n text,\n href,\n tokens: [\n {\n type: \"text\",\n raw: text,\n text\n }\n ]\n };\n }\n }\n inlineText(src) {\n const cap = this.rules.inline.text.exec(src);\n if (cap) {\n const escaped = this.lexer.state.inRawBlock;\n return {\n type: \"text\",\n raw: cap[0],\n text: cap[0],\n escaped\n };\n }\n }\n};\n\n// src/Lexer.ts\nvar _Lexer = class __Lexer {\n tokens;\n options;\n state;\n tokenizer;\n inlineQueue;\n constructor(options2) {\n this.tokens = [];\n this.tokens.links = /* @__PURE__ */ Object.create(null);\n this.options = options2 || _defaults;\n this.options.tokenizer = this.options.tokenizer || new _Tokenizer();\n this.tokenizer = this.options.tokenizer;\n this.tokenizer.options = this.options;\n this.tokenizer.lexer = this;\n this.inlineQueue = [];\n this.state = {\n inLink: false,\n inRawBlock: false,\n top: true\n };\n const rules = {\n other,\n block: block.normal,\n inline: inline.normal\n };\n if (this.options.pedantic) {\n rules.block = block.pedantic;\n rules.inline = inline.pedantic;\n } else if (this.options.gfm) {\n rules.block = block.gfm;\n if (this.options.breaks) {\n rules.inline = inline.breaks;\n } else {\n rules.inline = inline.gfm;\n }\n }\n this.tokenizer.rules = rules;\n }\n /**\n * Expose Rules\n */\n static get rules() {\n return {\n block,\n inline\n };\n }\n /**\n * Static Lex Method\n */\n static lex(src, options2) {\n const lexer2 = new __Lexer(options2);\n return lexer2.lex(src);\n }\n /**\n * Static Lex Inline Method\n */\n static lexInline(src, options2) {\n const lexer2 = new __Lexer(options2);\n return lexer2.inlineTokens(src);\n }\n /**\n * Preprocessing\n */\n lex(src) {\n src = src.replace(other.carriageReturn, \"\\n\");\n this.blockTokens(src, this.tokens);\n for (let i = 0; i < this.inlineQueue.length; i++) {\n const next = this.inlineQueue[i];\n this.inlineTokens(next.src, next.tokens);\n }\n this.inlineQueue = [];\n return this.tokens;\n }\n blockTokens(src, tokens = [], lastParagraphClipped = false) {\n if (this.options.pedantic) {\n src = src.replace(other.tabCharGlobal, \" \").replace(other.spaceLine, \"\");\n }\n while (src) {\n let token;\n if (this.options.extensions?.block?.some((extTokenizer) => {\n if (token = extTokenizer.call({ lexer: this }, src, tokens)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n return true;\n }\n return false;\n })) {\n continue;\n }\n if (token = this.tokenizer.space(src)) {\n src = src.substring(token.raw.length);\n const lastToken = tokens.at(-1);\n if (token.raw.length === 1 && lastToken !== void 0) {\n lastToken.raw += \"\\n\";\n } else {\n tokens.push(token);\n }\n continue;\n }\n if (token = this.tokenizer.code(src)) {\n src = src.substring(token.raw.length);\n const lastToken = tokens.at(-1);\n if (lastToken?.type === \"paragraph\" || lastToken?.type === \"text\") {\n lastToken.raw += \"\\n\" + token.raw;\n lastToken.text += \"\\n\" + token.text;\n this.inlineQueue.at(-1).src = lastToken.text;\n } else {\n tokens.push(token);\n }\n continue;\n }\n if (token = this.tokenizer.fences(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n if (token = this.tokenizer.heading(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n if (token = this.tokenizer.hr(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n if (token = this.tokenizer.blockquote(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n if (token = this.tokenizer.list(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n if (token = this.tokenizer.html(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n if (token = this.tokenizer.def(src)) {\n src = src.substring(token.raw.length);\n const lastToken = tokens.at(-1);\n if (lastToken?.type === \"paragraph\" || lastToken?.type === \"text\") {\n lastToken.raw += \"\\n\" + token.raw;\n lastToken.text += \"\\n\" + token.raw;\n this.inlineQueue.at(-1).src = lastToken.text;\n } else if (!this.tokens.links[token.tag]) {\n this.tokens.links[token.tag] = {\n href: token.href,\n title: token.title\n };\n }\n continue;\n }\n if (token = this.tokenizer.table(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n if (token = this.tokenizer.lheading(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n let cutSrc = src;\n if (this.options.extensions?.startBlock) {\n let startIndex = Infinity;\n const tempSrc = src.slice(1);\n let tempStart;\n this.options.extensions.startBlock.forEach((getStartIndex) => {\n tempStart = getStartIndex.call({ lexer: this }, tempSrc);\n if (typeof tempStart === \"number\" && tempStart >= 0) {\n startIndex = Math.min(startIndex, tempStart);\n }\n });\n if (startIndex < Infinity && startIndex >= 0) {\n cutSrc = src.substring(0, startIndex + 1);\n }\n }\n if (this.state.top && (token = this.tokenizer.paragraph(cutSrc))) {\n const lastToken = tokens.at(-1);\n if (lastParagraphClipped && lastToken?.type === \"paragraph\") {\n lastToken.raw += \"\\n\" + token.raw;\n lastToken.text += \"\\n\" + token.text;\n this.inlineQueue.pop();\n this.inlineQueue.at(-1).src = lastToken.text;\n } else {\n tokens.push(token);\n }\n lastParagraphClipped = cutSrc.length !== src.length;\n src = src.substring(token.raw.length);\n continue;\n }\n if (token = this.tokenizer.text(src)) {\n src = src.substring(token.raw.length);\n const lastToken = tokens.at(-1);\n if (lastToken?.type === \"text\") {\n lastToken.raw += \"\\n\" + token.raw;\n lastToken.text += \"\\n\" + token.text;\n this.inlineQueue.pop();\n this.inlineQueue.at(-1).src = lastToken.text;\n } else {\n tokens.push(token);\n }\n continue;\n }\n if (src) {\n const errMsg = \"Infinite loop on byte: \" + src.charCodeAt(0);\n if (this.options.silent) {\n console.error(errMsg);\n break;\n } else {\n throw new Error(errMsg);\n }\n }\n }\n this.state.top = true;\n return tokens;\n }\n inline(src, tokens = []) {\n this.inlineQueue.push({ src, tokens });\n return tokens;\n }\n /**\n * Lexing/Compiling\n */\n inlineTokens(src, tokens = []) {\n let maskedSrc = src;\n let match = null;\n if (this.tokens.links) {\n const links = Object.keys(this.tokens.links);\n if (links.length > 0) {\n while ((match = this.tokenizer.rules.inline.reflinkSearch.exec(maskedSrc)) != null) {\n if (links.includes(match[0].slice(match[0].lastIndexOf(\"[\") + 1, -1))) {\n maskedSrc = maskedSrc.slice(0, match.index) + \"[\" + \"a\".repeat(match[0].length - 2) + \"]\" + maskedSrc.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex);\n }\n }\n }\n }\n while ((match = this.tokenizer.rules.inline.anyPunctuation.exec(maskedSrc)) != null) {\n maskedSrc = maskedSrc.slice(0, match.index) + \"++\" + maskedSrc.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);\n }\n while ((match = this.tokenizer.rules.inline.blockSkip.exec(maskedSrc)) != null) {\n maskedSrc = maskedSrc.slice(0, match.index) + \"[\" + \"a\".repeat(match[0].length - 2) + \"]\" + maskedSrc.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);\n }\n let keepPrevChar = false;\n let prevChar = \"\";\n while (src) {\n if (!keepPrevChar) {\n prevChar = \"\";\n }\n keepPrevChar = false;\n let token;\n if (this.options.extensions?.inline?.some((extTokenizer) => {\n if (token = extTokenizer.call({ lexer: this }, src, tokens)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n return true;\n }\n return false;\n })) {\n continue;\n }\n if (token = this.tokenizer.escape(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n if (token = this.tokenizer.tag(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n if (token = this.tokenizer.link(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n if (token = this.tokenizer.reflink(src, this.tokens.links)) {\n src = src.substring(token.raw.length);\n const lastToken = tokens.at(-1);\n if (token.type === \"text\" && lastToken?.type === \"text\") {\n lastToken.raw += token.raw;\n lastToken.text += token.text;\n } else {\n tokens.push(token);\n }\n continue;\n }\n if (token = this.tokenizer.emStrong(src, maskedSrc, prevChar)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n if (token = this.tokenizer.codespan(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n if (token = this.tokenizer.br(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n if (token = this.tokenizer.del(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n if (token = this.tokenizer.autolink(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n if (!this.state.inLink && (token = this.tokenizer.url(src))) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n let cutSrc = src;\n if (this.options.extensions?.startInline) {\n let startIndex = Infinity;\n const tempSrc = src.slice(1);\n let tempStart;\n this.options.extensions.startInline.forEach((getStartIndex) => {\n tempStart = getStartIndex.call({ lexer: this }, tempSrc);\n if (typeof tempStart === \"number\" && tempStart >= 0) {\n startIndex = Math.min(startIndex, tempStart);\n }\n });\n if (startIndex < Infinity && startIndex >= 0) {\n cutSrc = src.substring(0, startIndex + 1);\n }\n }\n if (token = this.tokenizer.inlineText(cutSrc)) {\n src = src.substring(token.raw.length);\n if (token.raw.slice(-1) !== \"_\") {\n prevChar = token.raw.slice(-1);\n }\n keepPrevChar = true;\n const lastToken = tokens.at(-1);\n if (lastToken?.type === \"text\") {\n lastToken.raw += token.raw;\n lastToken.text += token.text;\n } else {\n tokens.push(token);\n }\n continue;\n }\n if (src) {\n const errMsg = \"Infinite loop on byte: \" + src.charCodeAt(0);\n if (this.options.silent) {\n console.error(errMsg);\n break;\n } else {\n throw new Error(errMsg);\n }\n }\n }\n return tokens;\n }\n};\n\n// src/Renderer.ts\nvar _Renderer = class {\n options;\n parser;\n // set by the parser\n constructor(options2) {\n this.options = options2 || _defaults;\n }\n space(token) {\n return \"\";\n }\n code({ text, lang, escaped }) {\n const langString = (lang || \"\").match(other.notSpaceStart)?.[0];\n const code = text.replace(other.endingNewline, \"\") + \"\\n\";\n if (!langString) {\n return \"<pre><code>\" + (escaped ? code : escape2(code, true)) + \"</code></pre>\\n\";\n }\n return '<pre><code class=\"language-' + escape2(langString) + '\">' + (escaped ? code : escape2(code, true)) + \"</code></pre>\\n\";\n }\n blockquote({ tokens }) {\n const body = this.parser.parse(tokens);\n return `<blockquote>\n${body}</blockquote>\n`;\n }\n html({ text }) {\n return text;\n }\n heading({ tokens, depth }) {\n return `<h${depth}>${this.parser.parseInline(tokens)}</h${depth}>\n`;\n }\n hr(token) {\n return \"<hr>\\n\";\n }\n list(token) {\n const ordered = token.ordered;\n const start = token.start;\n let body = \"\";\n for (let j = 0; j < token.items.length; j++) {\n const item = token.items[j];\n body += this.listitem(item);\n }\n const type = ordered ? \"ol\" : \"ul\";\n const startAttr = ordered && start !== 1 ? ' start=\"' + start + '\"' : \"\";\n return \"<\" + type + startAttr + \">\\n\" + body + \"</\" + type + \">\\n\";\n }\n listitem(item) {\n let itemBody = \"\";\n if (item.task) {\n const checkbox = this.checkbox({ checked: !!item.checked });\n if (item.loose) {\n if (item.tokens[0]?.type === \"paragraph\") {\n item.tokens[0].text = checkbox + \" \" + item.tokens[0].text;\n if (item.tokens[0].tokens && item.tokens[0].tokens.length > 0 && item.tokens[0].tokens[0].type === \"text\") {\n item.tokens[0].tokens[0].text = checkbox + \" \" + escape2(item.tokens[0].tokens[0].text);\n item.tokens[0].tokens[0].escaped = true;\n }\n } else {\n item.tokens.unshift({\n type: \"text\",\n raw: checkbox + \" \",\n text: checkbox + \" \",\n escaped: true\n });\n }\n } else {\n itemBody += checkbox + \" \";\n }\n }\n itemBody += this.parser.parse(item.tokens, !!item.loose);\n return `<li>${itemBody}</li>\n`;\n }\n checkbox({ checked }) {\n return \"<input \" + (checked ? 'checked=\"\" ' : \"\") + 'disabled=\"\" type=\"checkbox\">';\n }\n paragraph({ tokens }) {\n return `<p>${this.parser.parseInline(tokens)}</p>\n`;\n }\n table(token) {\n let header = \"\";\n let cell = \"\";\n for (let j = 0; j < token.header.length; j++) {\n cell += this.tablecell(token.header[j]);\n }\n header += this.tablerow({ text: cell });\n let body = \"\";\n for (let j = 0; j < token.rows.length; j++) {\n const row = token.rows[j];\n cell = \"\";\n for (let k = 0; k < row.length; k++) {\n cell += this.tablecell(row[k]);\n }\n body += this.tablerow({ text: cell });\n }\n if (body) body = `<tbody>${body}</tbody>`;\n return \"<table>\\n<thead>\\n\" + header + \"</thead>\\n\" + body + \"</table>\\n\";\n }\n tablerow({ text }) {\n return `<tr>\n${text}</tr>\n`;\n }\n tablecell(token) {\n const content = this.parser.parseInline(token.tokens);\n const type = token.header ? \"th\" : \"td\";\n const tag2 = token.align ? `<${type} align=\"${token.align}\">` : `<${type}>`;\n return tag2 + content + `</${type}>\n`;\n }\n /**\n * span level renderer\n */\n strong({ tokens }) {\n return `<strong>${this.parser.parseInline(tokens)}</strong>`;\n }\n em({ tokens }) {\n return `<em>${this.parser.parseInline(tokens)}</em>`;\n }\n codespan({ text }) {\n return `<code>${escape2(text, true)}</code>`;\n }\n br(token) {\n return \"<br>\";\n }\n del({ tokens }) {\n return `<del>${this.parser.parseInline(tokens)}</del>`;\n }\n link({ href, title, tokens }) {\n const text = this.parser.parseInline(tokens);\n const cleanHref = cleanUrl(href);\n if (cleanHref === null) {\n return text;\n }\n href = cleanHref;\n let out = '<a href=\"' + href + '\"';\n if (title) {\n out += ' title=\"' + escape2(title) + '\"';\n }\n out += \">\" + text + \"</a>\";\n return out;\n }\n image({ href, title, text, tokens }) {\n if (tokens) {\n text = this.parser.parseInline(tokens, this.parser.textRenderer);\n }\n const cleanHref = cleanUrl(href);\n if (cleanHref === null) {\n return escape2(text);\n }\n href = cleanHref;\n let out = `<img src=\"${href}\" alt=\"${text}\"`;\n if (title) {\n out += ` title=\"${escape2(title)}\"`;\n }\n out += \">\";\n return out;\n }\n text(token) {\n return \"tokens\" in token && token.tokens ? this.parser.parseInline(token.tokens) : \"escaped\" in token && token.escaped ? token.text : escape2(token.text);\n }\n};\n\n// src/TextRenderer.ts\nvar _TextRenderer = class {\n // no need for block level renderers\n strong({ text }) {\n return text;\n }\n em({ text }) {\n return text;\n }\n codespan({ text }) {\n return text;\n }\n del({ text }) {\n return text;\n }\n html({ text }) {\n return text;\n }\n text({ text }) {\n return text;\n }\n link({ text }) {\n return \"\" + text;\n }\n image({ text }) {\n return \"\" + text;\n }\n br() {\n return \"\";\n }\n};\n\n// src/Parser.ts\nvar _Parser = class __Parser {\n options;\n renderer;\n textRenderer;\n constructor(options2) {\n this.options = options2 || _defaults;\n this.options.renderer = this.options.renderer || new _Renderer();\n this.renderer = this.options.renderer;\n this.renderer.options = this.options;\n this.renderer.parser = this;\n this.textRenderer = new _TextRenderer();\n }\n /**\n * Static Parse Method\n */\n static parse(tokens, options2) {\n const parser2 = new __Parser(options2);\n return parser2.parse(tokens);\n }\n /**\n * Static Parse Inline Method\n */\n static parseInline(tokens, options2) {\n const parser2 = new __Parser(options2);\n return parser2.parseInline(tokens);\n }\n /**\n * Parse Loop\n */\n parse(tokens, top = true) {\n let out = \"\";\n for (let i = 0; i < tokens.length; i++) {\n const anyToken = tokens[i];\n if (this.options.extensions?.renderers?.[anyToken.type]) {\n const genericToken = anyToken;\n const ret = this.options.extensions.renderers[genericToken.type].call({ parser: this }, genericToken);\n if (ret !== false || ![\"space\", \"hr\", \"heading\", \"code\", \"table\", \"blockquote\", \"list\", \"html\", \"paragraph\", \"text\"].includes(genericToken.type)) {\n out += ret || \"\";\n continue;\n }\n }\n const token = anyToken;\n switch (token.type) {\n case \"space\": {\n out += this.renderer.space(token);\n continue;\n }\n case \"hr\": {\n out += this.renderer.hr(token);\n continue;\n }\n case \"heading\": {\n out += this.renderer.heading(token);\n continue;\n }\n case \"code\": {\n out += this.renderer.code(token);\n continue;\n }\n case \"table\": {\n out += this.renderer.table(token);\n continue;\n }\n case \"blockquote\": {\n out += this.renderer.blockquote(token);\n continue;\n }\n case \"list\": {\n out += this.renderer.list(token);\n continue;\n }\n case \"html\": {\n out += this.renderer.html(token);\n continue;\n }\n case \"paragraph\": {\n out += this.renderer.paragraph(token);\n continue;\n }\n case \"text\": {\n let textToken = token;\n let body = this.renderer.text(textToken);\n while (i + 1 < tokens.length && tokens[i + 1].type === \"text\") {\n textToken = tokens[++i];\n body += \"\\n\" + this.renderer.text(textToken);\n }\n if (top) {\n out += this.renderer.paragraph({\n type: \"paragraph\",\n raw: body,\n text: body,\n tokens: [{ type: \"text\", raw: body, text: body, escaped: true }]\n });\n } else {\n out += body;\n }\n continue;\n }\n default: {\n const errMsg = 'Token with \"' + token.type + '\" type was not found.';\n if (this.options.silent) {\n console.error(errMsg);\n return \"\";\n } else {\n throw new Error(errMsg);\n }\n }\n }\n }\n return out;\n }\n /**\n * Parse Inline Tokens\n */\n parseInline(tokens, renderer = this.renderer) {\n let out = \"\";\n for (let i = 0; i < tokens.length; i++) {\n const anyToken = tokens[i];\n if (this.options.extensions?.renderers?.[anyToken.type]) {\n const ret = this.options.extensions.renderers[anyToken.type].call({ parser: this }, anyToken);\n if (ret !== false || ![\"escape\", \"html\", \"link\", \"image\", \"strong\", \"em\", \"codespan\", \"br\", \"del\", \"text\"].includes(anyToken.type)) {\n out += ret || \"\";\n continue;\n }\n }\n const token = anyToken;\n switch (token.type) {\n case \"escape\": {\n out += renderer.text(token);\n break;\n }\n case \"html\": {\n out += renderer.html(token);\n break;\n }\n case \"link\": {\n out += renderer.link(token);\n break;\n }\n case \"image\": {\n out += renderer.image(token);\n break;\n }\n case \"strong\": {\n out += renderer.strong(token);\n break;\n }\n case \"em\": {\n out += renderer.em(token);\n break;\n }\n case \"codespan\": {\n out += renderer.codespan(token);\n break;\n }\n case \"br\": {\n out += renderer.br(token);\n break;\n }\n case \"del\": {\n out += renderer.del(token);\n break;\n }\n case \"text\": {\n out += renderer.text(token);\n break;\n }\n default: {\n const errMsg = 'Token with \"' + token.type + '\" type was not found.';\n if (this.options.silent) {\n console.error(errMsg);\n return \"\";\n } else {\n throw new Error(errMsg);\n }\n }\n }\n }\n return out;\n }\n};\n\n// src/Hooks.ts\nvar _Hooks = class {\n options;\n block;\n constructor(options2) {\n this.options = options2 || _defaults;\n }\n static passThroughHooks = /* @__PURE__ */ new Set([\n \"preprocess\",\n \"postprocess\",\n \"processAllTokens\"\n ]);\n /**\n * Process markdown before marked\n */\n preprocess(markdown) {\n return markdown;\n }\n /**\n * Process HTML after marked is finished\n */\n postprocess(html2) {\n return html2;\n }\n /**\n * Process all tokens before walk tokens\n */\n processAllTokens(tokens) {\n return tokens;\n }\n /**\n * Provide function to tokenize markdown\n */\n provideLexer() {\n return this.block ? _Lexer.lex : _Lexer.lexInline;\n }\n /**\n * Provide function to parse tokens\n */\n provideParser() {\n return this.block ? _Parser.parse : _Parser.parseInline;\n }\n};\n\n// src/Instance.ts\nvar Marked = class {\n defaults = _getDefaults();\n options = this.setOptions;\n parse = this.parseMarkdown(true);\n parseInline = this.parseMarkdown(false);\n Parser = _Parser;\n Renderer = _Renderer;\n TextRenderer = _TextRenderer;\n Lexer = _Lexer;\n Tokenizer = _Tokenizer;\n Hooks = _Hooks;\n constructor(...args) {\n this.use(...args);\n }\n /**\n * Run callback for every token\n */\n walkTokens(tokens, callback) {\n let values = [];\n for (const token of tokens) {\n values = values.concat(callback.call(this, token));\n switch (token.type) {\n case \"table\": {\n const tableToken = token;\n for (const cell of tableToken.header) {\n values = values.concat(this.walkTokens(cell.tokens, callback));\n }\n for (const row of tableToken.rows) {\n for (const cell of row) {\n values = values.concat(this.walkTokens(cell.tokens, callback));\n }\n }\n break;\n }\n case \"list\": {\n const listToken = token;\n values = values.concat(this.walkTokens(listToken.items, callback));\n break;\n }\n default: {\n const genericToken = token;\n if (this.defaults.extensions?.childTokens?.[genericToken.type]) {\n this.defaults.extensions.childTokens[genericToken.type].forEach((childTokens) => {\n const tokens2 = genericToken[childTokens].flat(Infinity);\n values = values.concat(this.walkTokens(tokens2, callback));\n });\n } else if (genericToken.tokens) {\n values = values.concat(this.walkTokens(genericToken.tokens, callback));\n }\n }\n }\n }\n return values;\n }\n use(...args) {\n const extensions = this.defaults.extensions || { renderers: {}, childTokens: {} };\n args.forEach((pack) => {\n const opts = { ...pack };\n opts.async = this.defaults.async || opts.async || false;\n if (pack.extensions) {\n pack.extensions.forEach((ext) => {\n if (!ext.name) {\n throw new Error(\"extension name required\");\n }\n if (\"renderer\" in ext) {\n const prevRenderer = extensions.renderers[ext.name];\n if (prevRenderer) {\n extensions.renderers[ext.name] = function(...args2) {\n let ret = ext.renderer.apply(this, args2);\n if (ret === false) {\n ret = prevRenderer.apply(this, args2);\n }\n return ret;\n };\n } else {\n extensions.renderers[ext.name] = ext.renderer;\n }\n }\n if (\"tokenizer\" in ext) {\n if (!ext.level || ext.level !== \"block\" && ext.level !== \"inline\") {\n throw new Error(\"extension level must be 'block' or 'inline'\");\n }\n const extLevel = extensions[ext.level];\n if (extLevel) {\n extLevel.unshift(ext.tokenizer);\n } else {\n extensions[ext.level] = [ext.tokenizer];\n }\n if (ext.start) {\n if (ext.level === \"block\") {\n if (extensions.startBlock) {\n extensions.startBlock.push(ext.start);\n } else {\n extensions.startBlock = [ext.start];\n }\n } else if (ext.level === \"inline\") {\n if (extensions.startInline) {\n extensions.startInline.push(ext.start);\n } else {\n extensions.startInline = [ext.start];\n }\n }\n }\n }\n if (\"childTokens\" in ext && ext.childTokens) {\n extensions.childTokens[ext.name] = ext.childTokens;\n }\n });\n opts.extensions = extensions;\n }\n if (pack.renderer) {\n const renderer = this.defaults.renderer || new _Renderer(this.defaults);\n for (const prop in pack.renderer) {\n if (!(prop in renderer)) {\n throw new Error(`renderer '${prop}' does not exist`);\n }\n if ([\"options\", \"parser\"].includes(prop)) {\n continue;\n }\n const rendererProp = prop;\n const rendererFunc = pack.renderer[rendererProp];\n const prevRenderer = renderer[rendererProp];\n renderer[rendererProp] = (...args2) => {\n let ret = rendererFunc.apply(renderer, args2);\n if (ret === false) {\n ret = prevRenderer.apply(renderer, args2);\n }\n return ret || \"\";\n };\n }\n opts.renderer = renderer;\n }\n if (pack.tokenizer) {\n const tokenizer = this.defaults.tokenizer || new _Tokenizer(this.defaults);\n for (const prop in pack.tokenizer) {\n if (!(prop in tokenizer)) {\n throw new Error(`tokenizer '${prop}' does not exist`);\n }\n if ([\"options\", \"rules\", \"lexer\"].includes(prop)) {\n continue;\n }\n const tokenizerProp = prop;\n const tokenizerFunc = pack.tokenizer[tokenizerProp];\n const prevTokenizer = tokenizer[tokenizerProp];\n tokenizer[tokenizerProp] = (...args2) => {\n let ret = tokenizerFunc.apply(tokenizer, args2);\n if (ret === false) {\n ret = prevTokenizer.apply(tokenizer, args2);\n }\n return ret;\n };\n }\n opts.tokenizer = tokenizer;\n }\n if (pack.hooks) {\n const hooks = this.defaults.hooks || new _Hooks();\n for (const prop in pack.hooks) {\n if (!(prop in hooks)) {\n throw new Error(`hook '${prop}' does not exist`);\n }\n if ([\"options\", \"block\"].includes(prop)) {\n continue;\n }\n const hooksProp = prop;\n const hooksFunc = pack.hooks[hooksProp];\n const prevHook = hooks[hooksProp];\n if (_Hooks.passThroughHooks.has(prop)) {\n hooks[hooksProp] = (arg) => {\n if (this.defaults.async) {\n return Promise.resolve(hooksFunc.call(hooks, arg)).then((ret2) => {\n return prevHook.call(hooks, ret2);\n });\n }\n const ret = hooksFunc.call(hooks, arg);\n return prevHook.call(hooks, ret);\n };\n } else {\n hooks[hooksProp] = (...args2) => {\n let ret = hooksFunc.apply(hooks, args2);\n if (ret === false) {\n ret = prevHook.apply(hooks, args2);\n }\n return ret;\n };\n }\n }\n opts.hooks = hooks;\n }\n if (pack.walkTokens) {\n const walkTokens2 = this.defaults.walkTokens;\n const packWalktokens = pack.walkTokens;\n opts.walkTokens = function(token) {\n let values = [];\n values.push(packWalktokens.call(this, token));\n if (walkTokens2) {\n values = values.concat(walkTokens2.call(this, token));\n }\n return values;\n };\n }\n this.defaults = { ...this.defaults, ...opts };\n });\n return this;\n }\n setOptions(opt) {\n this.defaults = { ...this.defaults, ...opt };\n return this;\n }\n lexer(src, options2) {\n return _Lexer.lex(src, options2 ?? this.defaults);\n }\n parser(tokens, options2) {\n return _Parser.parse(tokens, options2 ?? this.defaults);\n }\n parseMarkdown(blockType) {\n const parse2 = (src, options2) => {\n const origOpt = { ...options2 };\n const opt = { ...this.defaults, ...origOpt };\n const throwError = this.onError(!!opt.silent, !!opt.async);\n if (this.defaults.async === true && origOpt.async === false) {\n return throwError(new Error(\"marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise.\"));\n }\n if (typeof src === \"undefined\" || src === null) {\n return throwError(new Error(\"marked(): input parameter is undefined or null\"));\n }\n if (typeof src !== \"string\") {\n return throwError(new Error(\"marked(): input parameter is of type \" + Object.prototype.toString.call(src) + \", string expected\"));\n }\n if (opt.hooks) {\n opt.hooks.options = opt;\n opt.hooks.block = blockType;\n }\n const lexer2 = opt.hooks ? opt.hooks.provideLexer() : blockType ? _Lexer.lex : _Lexer.lexInline;\n const parser2 = opt.hooks ? opt.hooks.provideParser() : blockType ? _Parser.parse : _Parser.parseInline;\n if (opt.async) {\n return Promise.resolve(opt.hooks ? opt.hooks.preprocess(src) : src).then((src2) => lexer2(src2, opt)).then((tokens) => opt.hooks ? opt.hooks.processAllTokens(tokens) : tokens).then((tokens) => opt.walkTokens ? Promise.all(this.walkTokens(tokens, opt.walkTokens)).then(() => tokens) : tokens).then((tokens) => parser2(tokens, opt)).then((html2) => opt.hooks ? opt.hooks.postprocess(html2) : html2).catch(throwError);\n }\n try {\n if (opt.hooks) {\n src = opt.hooks.preprocess(src);\n }\n let tokens = lexer2(src, opt);\n if (opt.hooks) {\n tokens = opt.hooks.processAllTokens(tokens);\n }\n if (opt.walkTokens) {\n this.walkTokens(tokens, opt.walkTokens);\n }\n let html2 = parser2(tokens, opt);\n if (opt.hooks) {\n html2 = opt.hooks.postprocess(html2);\n }\n return html2;\n } catch (e) {\n return throwError(e);\n }\n };\n return parse2;\n }\n onError(silent, async) {\n return (e) => {\n e.message += \"\\nPlease report this to https://github.com/markedjs/marked.\";\n if (silent) {\n const msg = \"<p>An error occurred:</p><pre>\" + escape2(e.message + \"\", true) + \"</pre>\";\n if (async) {\n return Promise.resolve(msg);\n }\n return msg;\n }\n if (async) {\n return Promise.reject(e);\n }\n throw e;\n };\n }\n};\n\n// src/marked.ts\nvar markedInstance = new Marked();\nfunction marked(src, opt) {\n return markedInstance.parse(src, opt);\n}\nmarked.options = marked.setOptions = function(options2) {\n markedInstance.setOptions(options2);\n marked.defaults = markedInstance.defaults;\n changeDefaults(marked.defaults);\n return marked;\n};\nmarked.getDefaults = _getDefaults;\nmarked.defaults = _defaults;\nmarked.use = function(...args) {\n markedInstance.use(...args);\n marked.defaults = markedInstance.defaults;\n changeDefaults(marked.defaults);\n return marked;\n};\nmarked.walkTokens = function(tokens, callback) {\n return markedInstance.walkTokens(tokens, callback);\n};\nmarked.parseInline = markedInstance.parseInline;\nmarked.Parser = _Parser;\nmarked.parser = _Parser.parse;\nmarked.Renderer = _Renderer;\nmarked.TextRenderer = _TextRenderer;\nmarked.Lexer = _Lexer;\nmarked.lexer = _Lexer.lex;\nmarked.Tokenizer = _Tokenizer;\nmarked.Hooks = _Hooks;\nmarked.parse = marked;\nvar options = marked.options;\nvar setOptions = marked.setOptions;\nvar use = marked.use;\nvar walkTokens = marked.walkTokens;\nvar parseInline = marked.parseInline;\nvar parse = marked;\nvar parser = _Parser.parse;\nvar lexer = _Lexer.lex;\nexport {\n _Hooks as Hooks,\n _Lexer as Lexer,\n Marked,\n _Parser as Parser,\n _Renderer as Renderer,\n _TextRenderer as TextRenderer,\n _Tokenizer as Tokenizer,\n _defaults as defaults,\n _getDefaults as getDefaults,\n lexer,\n marked,\n options,\n parse,\n parseInline,\n parser,\n setOptions,\n use,\n walkTokens\n};\n//# sourceMappingURL=marked.esm.js.map\n","/*! @license DOMPurify 3.4.11 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.4.11/LICENSE */\n\nfunction _arrayLikeToArray(r, a) {\n (null == a || a > r.length) && (a = r.length);\n for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];\n return n;\n}\nfunction _arrayWithHoles(r) {\n if (Array.isArray(r)) return r;\n}\nfunction _iterableToArrayLimit(r, l) {\n var t = null == r ? null : \"undefined\" != typeof Symbol && r[Symbol.iterator] || r[\"@@iterator\"];\n if (null != t) {\n var e,\n n,\n i,\n u,\n a = [],\n f = true,\n o = false;\n try {\n if (i = (t = t.call(r)).next, 0 === l) ; else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0);\n } catch (r) {\n o = true, n = r;\n } finally {\n try {\n if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return;\n } finally {\n if (o) throw n;\n }\n }\n return a;\n }\n}\nfunction _nonIterableRest() {\n throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}\nfunction _slicedToArray(r, e) {\n return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest();\n}\nfunction _unsupportedIterableToArray(r, a) {\n if (r) {\n if (\"string\" == typeof r) return _arrayLikeToArray(r, a);\n var t = {}.toString.call(r).slice(8, -1);\n return \"Object\" === t && r.constructor && (t = r.constructor.name), \"Map\" === t || \"Set\" === t ? Array.from(r) : \"Arguments\" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;\n }\n}\n\nconst entries = Object.entries,\n setPrototypeOf = Object.setPrototypeOf,\n isFrozen = Object.isFrozen,\n getPrototypeOf = Object.getPrototypeOf,\n getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;\nlet freeze = Object.freeze,\n seal = Object.seal,\n create = Object.create; // eslint-disable-line import/no-mutable-exports\nlet _ref = typeof Reflect !== 'undefined' && Reflect,\n apply = _ref.apply,\n construct = _ref.construct;\nif (!freeze) {\n freeze = function freeze(x) {\n return x;\n };\n}\nif (!seal) {\n seal = function seal(x) {\n return x;\n };\n}\nif (!apply) {\n apply = function apply(func, thisArg) {\n for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {\n args[_key - 2] = arguments[_key];\n }\n return func.apply(thisArg, args);\n };\n}\nif (!construct) {\n construct = function construct(Func) {\n for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {\n args[_key2 - 1] = arguments[_key2];\n }\n return new Func(...args);\n };\n}\nconst arrayForEach = unapply(Array.prototype.forEach);\nconst arrayLastIndexOf = unapply(Array.prototype.lastIndexOf);\nconst arrayPop = unapply(Array.prototype.pop);\nconst arrayPush = unapply(Array.prototype.push);\nconst arraySplice = unapply(Array.prototype.splice);\nconst arrayIsArray = Array.isArray;\nconst stringToLowerCase = unapply(String.prototype.toLowerCase);\nconst stringToString = unapply(String.prototype.toString);\nconst stringMatch = unapply(String.prototype.match);\nconst stringReplace = unapply(String.prototype.replace);\nconst stringIndexOf = unapply(String.prototype.indexOf);\nconst stringTrim = unapply(String.prototype.trim);\nconst numberToString = unapply(Number.prototype.toString);\nconst booleanToString = unapply(Boolean.prototype.toString);\nconst bigintToString = typeof BigInt === 'undefined' ? null : unapply(BigInt.prototype.toString);\nconst symbolToString = typeof Symbol === 'undefined' ? null : unapply(Symbol.prototype.toString);\nconst objectHasOwnProperty = unapply(Object.prototype.hasOwnProperty);\nconst objectToString = unapply(Object.prototype.toString);\nconst regExpTest = unapply(RegExp.prototype.test);\nconst typeErrorCreate = unconstruct(TypeError);\n/**\n * Creates a new function that calls the given function with a specified thisArg and arguments.\n *\n * @param func - The function to be wrapped and called.\n * @returns A new function that calls the given function with a specified thisArg and arguments.\n */\nfunction unapply(func) {\n return function (thisArg) {\n if (thisArg instanceof RegExp) {\n thisArg.lastIndex = 0;\n }\n for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {\n args[_key3 - 1] = arguments[_key3];\n }\n return apply(func, thisArg, args);\n };\n}\n/**\n * Creates a new function that constructs an instance of the given constructor function with the provided arguments.\n *\n * @param func - The constructor function to be wrapped and called.\n * @returns A new function that constructs an instance of the given constructor function with the provided arguments.\n */\nfunction unconstruct(Func) {\n return function () {\n for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {\n args[_key4] = arguments[_key4];\n }\n return construct(Func, args);\n };\n}\n/**\n * Add properties to a lookup table\n *\n * @param set - The set to which elements will be added.\n * @param array - The array containing elements to be added to the set.\n * @param transformCaseFunc - An optional function to transform the case of each element before adding to the set.\n * @returns The modified set with added elements.\n */\nfunction addToSet(set, array) {\n let transformCaseFunc = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : stringToLowerCase;\n if (setPrototypeOf) {\n // Make 'in' and truthy checks like Boolean(set.constructor)\n // independent of any properties defined on Object.prototype.\n // Prevent prototype setters from intercepting set as a this value.\n setPrototypeOf(set, null);\n }\n if (!arrayIsArray(array)) {\n return set;\n }\n let l = array.length;\n while (l--) {\n let element = array[l];\n if (typeof element === 'string') {\n const lcElement = transformCaseFunc(element);\n if (lcElement !== element) {\n // Config presets (e.g. tags.js, attrs.js) are immutable.\n if (!isFrozen(array)) {\n array[l] = lcElement;\n }\n element = lcElement;\n }\n }\n set[element] = true;\n }\n return set;\n}\n/**\n * Clean up an array to harden against CSPP\n *\n * @param array - The array to be cleaned.\n * @returns The cleaned version of the array\n */\nfunction cleanArray(array) {\n for (let index = 0; index < array.length; index++) {\n const isPropertyExist = objectHasOwnProperty(array, index);\n if (!isPropertyExist) {\n array[index] = null;\n }\n }\n return array;\n}\n/**\n * Shallow clone an object\n *\n * @param object - The object to be cloned.\n * @returns A new object that copies the original.\n */\nfunction clone(object) {\n const newObject = create(null);\n for (const _ref2 of entries(object)) {\n var _ref3 = _slicedToArray(_ref2, 2);\n const property = _ref3[0];\n const value = _ref3[1];\n const isPropertyExist = objectHasOwnProperty(object, property);\n if (isPropertyExist) {\n if (arrayIsArray(value)) {\n newObject[property] = cleanArray(value);\n } else if (value && typeof value === 'object' && value.constructor === Object) {\n newObject[property] = clone(value);\n } else {\n newObject[property] = value;\n }\n }\n }\n return newObject;\n}\n/**\n * Convert non-node values into strings without depending on direct property access.\n *\n * @param value - The value to stringify.\n * @returns A string representation of the provided value.\n */\nfunction stringifyValue(value) {\n switch (typeof value) {\n case 'string':\n {\n return value;\n }\n case 'number':\n {\n return numberToString(value);\n }\n case 'boolean':\n {\n return booleanToString(value);\n }\n case 'bigint':\n {\n return bigintToString ? bigintToString(value) : '0';\n }\n case 'symbol':\n {\n return symbolToString ? symbolToString(value) : 'Symbol()';\n }\n case 'undefined':\n {\n return objectToString(value);\n }\n case 'function':\n case 'object':\n {\n if (value === null) {\n return objectToString(value);\n }\n const valueAsRecord = value;\n const valueToString = lookupGetter(valueAsRecord, 'toString');\n if (typeof valueToString === 'function') {\n const stringified = valueToString(valueAsRecord);\n return typeof stringified === 'string' ? stringified : objectToString(stringified);\n }\n return objectToString(value);\n }\n default:\n {\n return objectToString(value);\n }\n }\n}\n/**\n * This method automatically checks if the prop is function or getter and behaves accordingly.\n *\n * @param object - The object to look up the getter function in its prototype chain.\n * @param prop - The property name for which to find the getter function.\n * @returns The getter function found in the prototype chain or a fallback function.\n */\nfunction lookupGetter(object, prop) {\n while (object !== null) {\n const desc = getOwnPropertyDescriptor(object, prop);\n if (desc) {\n if (desc.get) {\n return unapply(desc.get);\n }\n if (typeof desc.value === 'function') {\n return unapply(desc.value);\n }\n }\n object = getPrototypeOf(object);\n }\n function fallbackValue() {\n return null;\n }\n return fallbackValue;\n}\nfunction isRegex(value) {\n try {\n regExpTest(value, '');\n return true;\n } catch (_unused) {\n return false;\n }\n}\n\nconst html$1 = freeze(['a', 'abbr', 'acronym', 'address', 'area', 'article', 'aside', 'audio', 'b', 'bdi', 'bdo', 'big', 'blink', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'content', 'data', 'datalist', 'dd', 'decorator', 'del', 'details', 'dfn', 'dialog', 'dir', 'div', 'dl', 'dt', 'element', 'em', 'fieldset', 'figcaption', 'figure', 'font', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'img', 'input', 'ins', 'kbd', 'label', 'legend', 'li', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meter', 'nav', 'nobr', 'ol', 'optgroup', 'option', 'output', 'p', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'search', 'section', 'select', 'shadow', 'slot', 'small', 'source', 'spacer', 'span', 'strike', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'time', 'tr', 'track', 'tt', 'u', 'ul', 'var', 'video', 'wbr']);\nconst svg$1 = freeze(['svg', 'a', 'altglyph', 'altglyphdef', 'altglyphitem', 'animatecolor', 'animatemotion', 'animatetransform', 'circle', 'clippath', 'defs', 'desc', 'ellipse', 'enterkeyhint', 'exportparts', 'filter', 'font', 'g', 'glyph', 'glyphref', 'hkern', 'image', 'inputmode', 'line', 'lineargradient', 'marker', 'mask', 'metadata', 'mpath', 'part', 'path', 'pattern', 'polygon', 'polyline', 'radialgradient', 'rect', 'stop', 'style', 'switch', 'symbol', 'text', 'textpath', 'title', 'tref', 'tspan', 'view', 'vkern']);\nconst svgFilters = freeze(['feBlend', 'feColorMatrix', 'feComponentTransfer', 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight', 'feDropShadow', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feImage', 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence']);\n// List of SVG elements that are disallowed by default.\n// We still need to know them so that we can do namespace\n// checks properly in case one wants to add them to\n// allow-list.\nconst svgDisallowed = freeze(['animate', 'color-profile', 'cursor', 'discard', 'font-face', 'font-face-format', 'font-face-name', 'font-face-src', 'font-face-uri', 'foreignobject', 'hatch', 'hatchpath', 'mesh', 'meshgradient', 'meshpatch', 'meshrow', 'missing-glyph', 'script', 'set', 'solidcolor', 'unknown', 'use']);\nconst mathMl$1 = freeze(['math', 'menclose', 'merror', 'mfenced', 'mfrac', 'mglyph', 'mi', 'mlabeledtr', 'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded', 'mphantom', 'mroot', 'mrow', 'ms', 'mspace', 'msqrt', 'mstyle', 'msub', 'msup', 'msubsup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder', 'munderover', 'mprescripts']);\n// Similarly to SVG, we want to know all MathML elements,\n// even those that we disallow by default.\nconst mathMlDisallowed = freeze(['maction', 'maligngroup', 'malignmark', 'mlongdiv', 'mscarries', 'mscarry', 'msgroup', 'mstack', 'msline', 'msrow', 'semantics', 'annotation', 'annotation-xml', 'mprescripts', 'none']);\nconst text = freeze(['#text']);\n\nconst html = freeze(['accept', 'action', 'align', 'alt', 'autocapitalize', 'autocomplete', 'autopictureinpicture', 'autoplay', 'background', 'bgcolor', 'border', 'capture', 'cellpadding', 'cellspacing', 'checked', 'cite', 'class', 'clear', 'color', 'cols', 'colspan', 'command', 'commandfor', 'controls', 'controlslist', 'coords', 'crossorigin', 'datetime', 'decoding', 'default', 'dir', 'disabled', 'disablepictureinpicture', 'disableremoteplayback', 'download', 'draggable', 'enctype', 'enterkeyhint', 'exportparts', 'face', 'for', 'headers', 'height', 'hidden', 'high', 'href', 'hreflang', 'id', 'inert', 'inputmode', 'integrity', 'ismap', 'kind', 'label', 'lang', 'list', 'loading', 'loop', 'low', 'max', 'maxlength', 'media', 'method', 'min', 'minlength', 'multiple', 'muted', 'name', 'nonce', 'noshade', 'novalidate', 'nowrap', 'open', 'optimum', 'part', 'pattern', 'placeholder', 'playsinline', 'popover', 'popovertarget', 'popovertargetaction', 'poster', 'preload', 'pubdate', 'radiogroup', 'readonly', 'rel', 'required', 'rev', 'reversed', 'role', 'rows', 'rowspan', 'spellcheck', 'scope', 'selected', 'shape', 'size', 'sizes', 'slot', 'span', 'srclang', 'start', 'src', 'srcset', 'step', 'style', 'summary', 'tabindex', 'title', 'translate', 'type', 'usemap', 'valign', 'value', 'width', 'wrap', 'xmlns']);\nconst svg = freeze(['accent-height', 'accumulate', 'additive', 'alignment-baseline', 'amplitude', 'ascent', 'attributename', 'attributetype', 'azimuth', 'basefrequency', 'baseline-shift', 'begin', 'bias', 'by', 'class', 'clip', 'clippathunits', 'clip-path', 'clip-rule', 'color', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'cx', 'cy', 'd', 'dx', 'dy', 'diffuseconstant', 'direction', 'display', 'divisor', 'dur', 'edgemode', 'elevation', 'end', 'exponent', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'filterunits', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'fx', 'fy', 'g1', 'g2', 'glyph-name', 'glyphref', 'gradientunits', 'gradienttransform', 'height', 'href', 'id', 'image-rendering', 'in', 'in2', 'intercept', 'k', 'k1', 'k2', 'k3', 'k4', 'kerning', 'keypoints', 'keysplines', 'keytimes', 'lang', 'lengthadjust', 'letter-spacing', 'kernelmatrix', 'kernelunitlength', 'lighting-color', 'local', 'marker-end', 'marker-mid', 'marker-start', 'markerheight', 'markerunits', 'markerwidth', 'maskcontentunits', 'maskunits', 'max', 'mask', 'mask-type', 'media', 'method', 'mode', 'min', 'name', 'numoctaves', 'offset', 'operator', 'opacity', 'order', 'orient', 'orientation', 'origin', 'overflow', 'paint-order', 'path', 'pathlength', 'patterncontentunits', 'patterntransform', 'patternunits', 'points', 'preservealpha', 'preserveaspectratio', 'primitiveunits', 'r', 'rx', 'ry', 'radius', 'refx', 'refy', 'repeatcount', 'repeatdur', 'restart', 'result', 'rotate', 'scale', 'seed', 'shape-rendering', 'slope', 'specularconstant', 'specularexponent', 'spreadmethod', 'startoffset', 'stddeviation', 'stitchtiles', 'stop-color', 'stop-opacity', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke', 'stroke-width', 'style', 'surfacescale', 'systemlanguage', 'tabindex', 'tablevalues', 'targetx', 'targety', 'transform', 'transform-origin', 'text-anchor', 'text-decoration', 'text-rendering', 'textlength', 'type', 'u1', 'u2', 'unicode', 'values', 'viewbox', 'visibility', 'version', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'width', 'word-spacing', 'wrap', 'writing-mode', 'xchannelselector', 'ychannelselector', 'x', 'x1', 'x2', 'xmlns', 'y', 'y1', 'y2', 'z', 'zoomandpan']);\nconst mathMl = freeze(['accent', 'accentunder', 'align', 'bevelled', 'close', 'columnalign', 'columnlines', 'columnspacing', 'columnspan', 'denomalign', 'depth', 'dir', 'display', 'displaystyle', 'encoding', 'fence', 'frame', 'height', 'href', 'id', 'largeop', 'length', 'linethickness', 'lquote', 'lspace', 'mathbackground', 'mathcolor', 'mathsize', 'mathvariant', 'maxsize', 'minsize', 'movablelimits', 'notation', 'numalign', 'open', 'rowalign', 'rowlines', 'rowspacing', 'rowspan', 'rspace', 'rquote', 'scriptlevel', 'scriptminsize', 'scriptsizemultiplier', 'selection', 'separator', 'separators', 'stretchy', 'subscriptshift', 'supscriptshift', 'symmetric', 'voffset', 'width', 'xmlns']);\nconst xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:xlink']);\n\nconst MUSTACHE_EXPR = seal(/{{[\\w\\W]*|^[\\w\\W]*}}/g);\nconst ERB_EXPR = seal(/<%[\\w\\W]*|^[\\w\\W]*%>/g);\nconst TMPLIT_EXPR = seal(/\\${[\\w\\W]*/g);\nconst DATA_ATTR = seal(/^data-[\\-\\w.\\u00B7-\\uFFFF]+$/); // eslint-disable-line no-useless-escape\nconst ARIA_ATTR = seal(/^aria-[\\-\\w]+$/); // eslint-disable-line no-useless-escape\nconst IS_ALLOWED_URI = seal(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\\-]+(?:[^a-z+.\\-:]|$))/i // eslint-disable-line no-useless-escape\n);\nconst IS_SCRIPT_OR_DATA = seal(/^(?:\\w+script|data):/i);\nconst ATTR_WHITESPACE = seal(/[\\u0000-\\u0020\\u00A0\\u1680\\u180E\\u2000-\\u2029\\u205F\\u3000]/g // eslint-disable-line no-control-regex\n);\nconst DOCTYPE_NAME = seal(/^html$/i);\nconst CUSTOM_ELEMENT = seal(/^[a-z][.\\w]*(-[.\\w]+)+$/i);\n// Markup-significant character probes used by _sanitizeElements.\n// Shared module-level instances are safe despite the sticky /g flags:\n// unapply() resets lastIndex for RegExp receivers before every call.\nconst ELEMENT_MARKUP_PROBE = seal(/<[/\\w!]/g);\nconst COMMENT_MARKUP_PROBE = seal(/<[/\\w]/g);\nconst FALLBACK_TAG_CLOSE = seal(/<\\/no(script|embed|frames)/i);\nconst SELF_CLOSING_TAG = seal(/\\/>/i);\n\n// https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType\nconst NODE_TYPE = {\n element: 1,\n attribute: 2,\n text: 3,\n cdataSection: 4,\n entityReference: 5,\n // Deprecated\n entityNode: 6,\n // Deprecated\n processingInstruction: 7,\n comment: 8,\n document: 9,\n documentType: 10,\n documentFragment: 11,\n notation: 12 // Deprecated\n};\nconst getGlobal = function getGlobal() {\n return typeof window === 'undefined' ? null : window;\n};\n/**\n * Creates a no-op policy for internal use only.\n * Don't export this function outside this module!\n * @param trustedTypes The policy factory.\n * @param purifyHostElement The Script element used to load DOMPurify (to determine policy name suffix).\n * @return The policy created (or null, if Trusted Types\n * are not supported or creating the policy failed).\n */\nconst _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTypes, purifyHostElement) {\n if (typeof trustedTypes !== 'object' || typeof trustedTypes.createPolicy !== 'function') {\n return null;\n }\n // Allow the callers to control the unique policy name\n // by adding a data-tt-policy-suffix to the script element with the DOMPurify.\n // Policy creation with duplicate names throws in Trusted Types.\n let suffix = null;\n const ATTR_NAME = 'data-tt-policy-suffix';\n if (purifyHostElement && purifyHostElement.hasAttribute(ATTR_NAME)) {\n suffix = purifyHostElement.getAttribute(ATTR_NAME);\n }\n const policyName = 'dompurify' + (suffix ? '#' + suffix : '');\n try {\n return trustedTypes.createPolicy(policyName, {\n createHTML(html) {\n return html;\n },\n createScriptURL(scriptUrl) {\n return scriptUrl;\n }\n });\n } catch (_) {\n // Policy creation failed (most likely another DOMPurify script has\n // already run). Skip creating the policy, as this will only cause errors\n // if TT are enforced.\n console.warn('TrustedTypes policy ' + policyName + ' could not be created.');\n return null;\n }\n};\nconst _createHooksMap = function _createHooksMap() {\n return {\n afterSanitizeAttributes: [],\n afterSanitizeElements: [],\n afterSanitizeShadowDOM: [],\n beforeSanitizeAttributes: [],\n beforeSanitizeElements: [],\n beforeSanitizeShadowDOM: [],\n uponSanitizeAttribute: [],\n uponSanitizeElement: [],\n uponSanitizeShadowNode: []\n };\n};\n/**\n * Resolve a set-valued configuration option: a fresh set built from\n * cfg[key] when it is an own array property (seeded with a clone of\n * options.base when given, case-normalized via options.transform),\n * the fallback set otherwise.\n *\n * @param cfg the cloned, prototype-free configuration object\n * @param key the configuration property to read\n * @param fallback the set to use when the option is absent or not an array\n * @param options transform and optional base set to merge into\n * @returns the resolved set\n */\nconst _resolveSetOption = function _resolveSetOption(cfg, key, fallback, options) {\n return objectHasOwnProperty(cfg, key) && arrayIsArray(cfg[key]) ? addToSet(options.base ? clone(options.base) : {}, cfg[key], options.transform) : fallback;\n};\nfunction createDOMPurify() {\n let window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal();\n const DOMPurify = root => createDOMPurify(root);\n DOMPurify.version = '3.4.11';\n DOMPurify.removed = [];\n if (!window || !window.document || window.document.nodeType !== NODE_TYPE.document || !window.Element) {\n // Not running in a browser, provide a factory function\n // so that you can pass your own Window\n DOMPurify.isSupported = false;\n return DOMPurify;\n }\n let document = window.document;\n const originalDocument = document;\n const currentScript = originalDocument.currentScript;\n window.DocumentFragment;\n const HTMLTemplateElement = window.HTMLTemplateElement,\n Node = window.Node,\n Element = window.Element,\n NodeFilter = window.NodeFilter,\n _window$NamedNodeMap = window.NamedNodeMap;\n _window$NamedNodeMap === void 0 ? window.NamedNodeMap || window.MozNamedAttrMap : _window$NamedNodeMap;\n window.HTMLFormElement;\n const DOMParser = window.DOMParser,\n trustedTypes = window.trustedTypes;\n const ElementPrototype = Element.prototype;\n const cloneNode = lookupGetter(ElementPrototype, 'cloneNode');\n const remove = lookupGetter(ElementPrototype, 'remove');\n const getNextSibling = lookupGetter(ElementPrototype, 'nextSibling');\n const getChildNodes = lookupGetter(ElementPrototype, 'childNodes');\n const getParentNode = lookupGetter(ElementPrototype, 'parentNode');\n const getShadowRoot = lookupGetter(ElementPrototype, 'shadowRoot');\n const getAttributes = lookupGetter(ElementPrototype, 'attributes');\n const getNodeType = Node && Node.prototype ? lookupGetter(Node.prototype, 'nodeType') : null;\n const getNodeName = Node && Node.prototype ? lookupGetter(Node.prototype, 'nodeName') : null;\n // As per issue #47, the web-components registry is inherited by a\n // new document created via createHTMLDocument. As per the spec\n // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries)\n // a new empty registry is used when creating a template contents owner\n // document, so we use that as our parent document to ensure nothing\n // is inherited.\n if (typeof HTMLTemplateElement === 'function') {\n const template = document.createElement('template');\n if (template.content && template.content.ownerDocument) {\n document = template.content.ownerDocument;\n }\n }\n let trustedTypesPolicy;\n let emptyHTML = '';\n // The instance's own internal Trusted Types policy. Unlike a caller-supplied\n // `TRUSTED_TYPES_POLICY`, this is created at most once — Trusted Types throws\n // on duplicate policy names — and is the only policy allowed to persist\n // across configurations and survive `clearConfig()`.\n let defaultTrustedTypesPolicy;\n let defaultTrustedTypesPolicyResolved = false;\n // Tracks whether we are already inside a call to the configured Trusted Types\n // policy (`createHTML` or `createScriptURL`). If a supplied policy callback\n // itself calls `DOMPurify.sanitize` (the cause of #1422), `sanitize` would\n // re-enter the policy and recurse until the stack overflows. We detect that\n // re-entry and throw a clear, actionable error instead. The guard is shared\n // across both callbacks, because either one re-entering `sanitize` triggers\n // the same unbounded recursion.\n let IN_TRUSTED_TYPES_POLICY = 0;\n const _assertNotInTrustedTypesPolicy = function _assertNotInTrustedTypesPolicy() {\n if (IN_TRUSTED_TYPES_POLICY > 0) {\n throw typeErrorCreate('A configured TRUSTED_TYPES_POLICY callback (createHTML or ' + 'createScriptURL) must not call DOMPurify.sanitize, as that causes ' + 'infinite recursion. Do not pass a policy whose callbacks wrap ' + 'DOMPurify as TRUSTED_TYPES_POLICY; see the \"DOMPurify and Trusted ' + 'Types\" section of the README.');\n }\n };\n const _createTrustedHTML = function _createTrustedHTML(html) {\n _assertNotInTrustedTypesPolicy();\n IN_TRUSTED_TYPES_POLICY++;\n try {\n return trustedTypesPolicy.createHTML(html);\n } finally {\n IN_TRUSTED_TYPES_POLICY--;\n }\n };\n const _createTrustedScriptURL = function _createTrustedScriptURL(scriptUrl) {\n _assertNotInTrustedTypesPolicy();\n IN_TRUSTED_TYPES_POLICY++;\n try {\n return trustedTypesPolicy.createScriptURL(scriptUrl);\n } finally {\n IN_TRUSTED_TYPES_POLICY--;\n }\n };\n // Lazily resolve (and cache) the instance's internal default policy.\n // Resolution is attempted at most once: a successful `createPolicy` cannot be\n // repeated (Trusted Types throws on duplicate names), and a failed or\n // unsupported attempt must not be retried on every parse.\n const _getDefaultTrustedTypesPolicy = function _getDefaultTrustedTypesPolicy() {\n if (!defaultTrustedTypesPolicyResolved) {\n defaultTrustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript);\n defaultTrustedTypesPolicyResolved = true;\n }\n return defaultTrustedTypesPolicy;\n };\n const _document = document,\n implementation = _document.implementation,\n createNodeIterator = _document.createNodeIterator,\n createDocumentFragment = _document.createDocumentFragment,\n getElementsByTagName = _document.getElementsByTagName;\n const importNode = originalDocument.importNode;\n let hooks = _createHooksMap();\n /**\n * Expose whether this browser supports running the full DOMPurify.\n */\n DOMPurify.isSupported = typeof entries === 'function' && typeof getParentNode === 'function' && implementation && implementation.createHTMLDocument !== undefined;\n const MUSTACHE_EXPR$1 = MUSTACHE_EXPR,\n ERB_EXPR$1 = ERB_EXPR,\n TMPLIT_EXPR$1 = TMPLIT_EXPR,\n DATA_ATTR$1 = DATA_ATTR,\n ARIA_ATTR$1 = ARIA_ATTR,\n IS_SCRIPT_OR_DATA$1 = IS_SCRIPT_OR_DATA,\n ATTR_WHITESPACE$1 = ATTR_WHITESPACE,\n CUSTOM_ELEMENT$1 = CUSTOM_ELEMENT;\n let IS_ALLOWED_URI$1 = IS_ALLOWED_URI;\n /**\n * We consider the elements and attributes below to be safe. Ideally\n * don't add any new ones but feel free to remove unwanted ones.\n */\n /* allowed element names */\n let ALLOWED_TAGS = null;\n const DEFAULT_ALLOWED_TAGS = addToSet({}, [...html$1, ...svg$1, ...svgFilters, ...mathMl$1, ...text]);\n /* Allowed attribute names */\n let ALLOWED_ATTR = null;\n const DEFAULT_ALLOWED_ATTR = addToSet({}, [...html, ...svg, ...mathMl, ...xml]);\n /*\n * Configure how DOMPurify should handle custom elements and their attributes as well as customized built-in elements.\n * @property {RegExp|Function|null} tagNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any custom elements)\n * @property {RegExp|Function|null} attributeNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any attributes not on the allow list)\n * @property {boolean} allowCustomizedBuiltInElements allow custom elements derived from built-ins if they pass CUSTOM_ELEMENT_HANDLING.tagNameCheck. Default: `false`.\n */\n let CUSTOM_ELEMENT_HANDLING = Object.seal(create(null, {\n tagNameCheck: {\n writable: true,\n configurable: false,\n enumerable: true,\n value: null\n },\n attributeNameCheck: {\n writable: true,\n configurable: false,\n enumerable: true,\n value: null\n },\n allowCustomizedBuiltInElements: {\n writable: true,\n configurable: false,\n enumerable: true,\n value: false\n }\n }));\n /* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */\n let FORBID_TAGS = null;\n /* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */\n let FORBID_ATTR = null;\n /* Config object to store ADD_TAGS/ADD_ATTR functions (when used as functions) */\n const EXTRA_ELEMENT_HANDLING = Object.seal(create(null, {\n tagCheck: {\n writable: true,\n configurable: false,\n enumerable: true,\n value: null\n },\n attributeCheck: {\n writable: true,\n configurable: false,\n enumerable: true,\n value: null\n }\n }));\n /* Decide if ARIA attributes are okay */\n let ALLOW_ARIA_ATTR = true;\n /* Decide if custom data attributes are okay */\n let ALLOW_DATA_ATTR = true;\n /* Decide if unknown protocols are okay */\n let ALLOW_UNKNOWN_PROTOCOLS = false;\n /* Decide if self-closing tags in attributes are allowed.\n * Usually removed due to a mXSS issue in jQuery 3.0 */\n let ALLOW_SELF_CLOSE_IN_ATTR = true;\n /* Output should be safe for common template engines.\n * This means, DOMPurify removes data attributes, mustaches and ERB\n */\n let SAFE_FOR_TEMPLATES = false;\n /* Output should be safe even for XML used within HTML and alike.\n * This means, DOMPurify removes comments when containing risky content.\n */\n let SAFE_FOR_XML = true;\n /* Decide if document with <html>... should be returned */\n let WHOLE_DOCUMENT = false;\n /* Track whether config is already set on this instance of DOMPurify. */\n let SET_CONFIG = false;\n /* Pristine allowlist bindings captured at setConfig() time. On the\n * persistent-config path sanitize() restores the sets from these before\n * the per-walk hook clone-guard, so a hook's in-call widening cannot\n * carry across calls. Null until setConfig() is called; reset by\n * clearConfig(). */\n let SET_CONFIG_ALLOWED_TAGS = null;\n let SET_CONFIG_ALLOWED_ATTR = null;\n /* Decide if all elements (e.g. style, script) must be children of\n * document.body. By default, browsers might move them to document.head */\n let FORCE_BODY = false;\n /* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html\n * string (or a TrustedHTML object if Trusted Types are supported).\n * If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead\n */\n let RETURN_DOM = false;\n /* Decide if a DOM `DocumentFragment` should be returned, instead of a html\n * string (or a TrustedHTML object if Trusted Types are supported) */\n let RETURN_DOM_FRAGMENT = false;\n /* Try to return a Trusted Type object instead of a string, return a string in\n * case Trusted Types are not supported */\n let RETURN_TRUSTED_TYPE = false;\n /* Output should be free from DOM clobbering attacks?\n * This sanitizes markups named with colliding, clobberable built-in DOM APIs.\n */\n let SANITIZE_DOM = true;\n /* Achieve full DOM Clobbering protection by isolating the namespace of named\n * properties and JS variables, mitigating attacks that abuse the HTML/DOM spec rules.\n *\n * HTML/DOM spec rules that enable DOM Clobbering:\n * - Named Access on Window (§7.3.3)\n * - DOM Tree Accessors (§3.1.5)\n * - Form Element Parent-Child Relations (§4.10.3)\n * - Iframe srcdoc / Nested WindowProxies (§4.8.5)\n * - HTMLCollection (§4.2.10.2)\n *\n * Namespace isolation is implemented by prefixing `id` and `name` attributes\n * with a constant string, i.e., `user-content-`\n */\n let SANITIZE_NAMED_PROPS = false;\n const SANITIZE_NAMED_PROPS_PREFIX = 'user-content-';\n /* Keep element content when removing element? */\n let KEEP_CONTENT = true;\n /* If a `Node` is passed to sanitize(), then performs sanitization in-place instead\n * of importing it into a new Document and returning a sanitized copy */\n let IN_PLACE = false;\n /* Allow usage of profiles like html, svg and mathMl */\n let USE_PROFILES = {};\n /* Tags to ignore content of when KEEP_CONTENT is true */\n let FORBID_CONTENTS = null;\n const DEFAULT_FORBID_CONTENTS = addToSet({}, ['annotation-xml', 'audio', 'colgroup', 'desc', 'foreignobject', 'head', 'iframe', 'math', 'mi', 'mn', 'mo', 'ms', 'mtext', 'noembed', 'noframes', 'noscript', 'plaintext', 'script',\n // <selectedcontent> mirrors the selected <option>'s subtree, cloned by\n // the UA (customizable <select>) — including any on* handlers — and the\n // engine re-mirrors synchronously whenever a removal changes which\n // option/selectedcontent is current, even inside DOMPurify's inert\n // DOMParser document. Hoisting its children on removal re-inserts a fresh\n // mirror target ahead of the walk, which the engine refills, looping\n // forever (DoS) and amplifying output. Dropping its content on removal\n // (rather than hoisting) breaks that cascade; the content is a duplicate\n // of the option, which is sanitized on its own. See campaign-3 F1/F6.\n 'selectedcontent', 'style', 'svg', 'template', 'thead', 'title', 'video', 'xmp']);\n /* Tags that are safe for data: URIs */\n let DATA_URI_TAGS = null;\n const DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']);\n /* Attributes safe for values like \"javascript:\" */\n let URI_SAFE_ATTRIBUTES = null;\n const DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ['alt', 'class', 'for', 'id', 'label', 'name', 'pattern', 'placeholder', 'role', 'summary', 'title', 'value', 'style', 'xmlns']);\n const MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';\n const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';\n const HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';\n /* Document namespace */\n let NAMESPACE = HTML_NAMESPACE;\n let IS_EMPTY_INPUT = false;\n /* Allowed XHTML+XML namespaces */\n let ALLOWED_NAMESPACES = null;\n const DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE], stringToString);\n const DEFAULT_MATHML_TEXT_INTEGRATION_POINTS = freeze(['mi', 'mo', 'mn', 'ms', 'mtext']);\n let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, DEFAULT_MATHML_TEXT_INTEGRATION_POINTS);\n const DEFAULT_HTML_INTEGRATION_POINTS = freeze(['annotation-xml']);\n let HTML_INTEGRATION_POINTS = addToSet({}, DEFAULT_HTML_INTEGRATION_POINTS);\n // Certain elements are allowed in both SVG and HTML\n // namespace. We need to specify them explicitly\n // so that they don't get erroneously deleted from\n // HTML namespace.\n const COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, ['title', 'style', 'font', 'a', 'script']);\n /* Parsing of strict XHTML documents */\n let PARSER_MEDIA_TYPE = null;\n const SUPPORTED_PARSER_MEDIA_TYPES = ['application/xhtml+xml', 'text/html'];\n const DEFAULT_PARSER_MEDIA_TYPE = 'text/html';\n let transformCaseFunc = null;\n /* Keep a reference to config to pass to hooks */\n let CONFIG = null;\n /* Ideally, do not touch anything below this line */\n /* ______________________________________________ */\n const formElement = document.createElement('form');\n const isRegexOrFunction = function isRegexOrFunction(testValue) {\n return testValue instanceof RegExp || testValue instanceof Function;\n };\n /**\n * _parseConfig\n *\n * @param cfg optional config literal\n */\n // eslint-disable-next-line complexity\n const _parseConfig = function _parseConfig() {\n let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n if (CONFIG && CONFIG === cfg) {\n return;\n }\n /* Shield configuration object from tampering */\n if (!cfg || typeof cfg !== 'object') {\n cfg = {};\n }\n /* Shield configuration object from prototype pollution */\n cfg = clone(cfg);\n PARSER_MEDIA_TYPE =\n // eslint-disable-next-line unicorn/prefer-includes\n SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? DEFAULT_PARSER_MEDIA_TYPE : cfg.PARSER_MEDIA_TYPE;\n // HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is.\n transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? stringToString : stringToLowerCase;\n /* Set configuration parameters */\n ALLOWED_TAGS = _resolveSetOption(cfg, 'ALLOWED_TAGS', DEFAULT_ALLOWED_TAGS, {\n transform: transformCaseFunc\n });\n ALLOWED_ATTR = _resolveSetOption(cfg, 'ALLOWED_ATTR', DEFAULT_ALLOWED_ATTR, {\n transform: transformCaseFunc\n });\n ALLOWED_NAMESPACES = _resolveSetOption(cfg, 'ALLOWED_NAMESPACES', DEFAULT_ALLOWED_NAMESPACES, {\n transform: stringToString\n });\n URI_SAFE_ATTRIBUTES = _resolveSetOption(cfg, 'ADD_URI_SAFE_ATTR', DEFAULT_URI_SAFE_ATTRIBUTES, {\n transform: transformCaseFunc,\n base: DEFAULT_URI_SAFE_ATTRIBUTES\n });\n DATA_URI_TAGS = _resolveSetOption(cfg, 'ADD_DATA_URI_TAGS', DEFAULT_DATA_URI_TAGS, {\n transform: transformCaseFunc,\n base: DEFAULT_DATA_URI_TAGS\n });\n FORBID_CONTENTS = _resolveSetOption(cfg, 'FORBID_CONTENTS', DEFAULT_FORBID_CONTENTS, {\n transform: transformCaseFunc\n });\n FORBID_TAGS = _resolveSetOption(cfg, 'FORBID_TAGS', clone({}), {\n transform: transformCaseFunc\n });\n FORBID_ATTR = _resolveSetOption(cfg, 'FORBID_ATTR', clone({}), {\n transform: transformCaseFunc\n });\n USE_PROFILES = objectHasOwnProperty(cfg, 'USE_PROFILES') ? cfg.USE_PROFILES && typeof cfg.USE_PROFILES === 'object' ? clone(cfg.USE_PROFILES) : cfg.USE_PROFILES : false;\n ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true\n ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true\n ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false\n ALLOW_SELF_CLOSE_IN_ATTR = cfg.ALLOW_SELF_CLOSE_IN_ATTR !== false; // Default true\n SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false\n SAFE_FOR_XML = cfg.SAFE_FOR_XML !== false; // Default true\n WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false\n RETURN_DOM = cfg.RETURN_DOM || false; // Default false\n RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false\n RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; // Default false\n FORCE_BODY = cfg.FORCE_BODY || false; // Default false\n SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true\n SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; // Default false\n KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true\n IN_PLACE = cfg.IN_PLACE || false; // Default false\n IS_ALLOWED_URI$1 = isRegex(cfg.ALLOWED_URI_REGEXP) ? cfg.ALLOWED_URI_REGEXP : IS_ALLOWED_URI; // Default regexp\n NAMESPACE = typeof cfg.NAMESPACE === 'string' ? cfg.NAMESPACE : HTML_NAMESPACE; // Default HTML namespace\n MATHML_TEXT_INTEGRATION_POINTS = objectHasOwnProperty(cfg, 'MATHML_TEXT_INTEGRATION_POINTS') && cfg.MATHML_TEXT_INTEGRATION_POINTS && typeof cfg.MATHML_TEXT_INTEGRATION_POINTS === 'object' ? clone(cfg.MATHML_TEXT_INTEGRATION_POINTS) : addToSet({}, DEFAULT_MATHML_TEXT_INTEGRATION_POINTS); // Default built-in map\n HTML_INTEGRATION_POINTS = objectHasOwnProperty(cfg, 'HTML_INTEGRATION_POINTS') && cfg.HTML_INTEGRATION_POINTS && typeof cfg.HTML_INTEGRATION_POINTS === 'object' ? clone(cfg.HTML_INTEGRATION_POINTS) : addToSet({}, DEFAULT_HTML_INTEGRATION_POINTS); // Default built-in map\n const customElementHandling = objectHasOwnProperty(cfg, 'CUSTOM_ELEMENT_HANDLING') && cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING === 'object' ? clone(cfg.CUSTOM_ELEMENT_HANDLING) : create(null);\n CUSTOM_ELEMENT_HANDLING = create(null);\n if (objectHasOwnProperty(customElementHandling, 'tagNameCheck') && isRegexOrFunction(customElementHandling.tagNameCheck)) {\n CUSTOM_ELEMENT_HANDLING.tagNameCheck = customElementHandling.tagNameCheck; // Default undefined\n }\n if (objectHasOwnProperty(customElementHandling, 'attributeNameCheck') && isRegexOrFunction(customElementHandling.attributeNameCheck)) {\n CUSTOM_ELEMENT_HANDLING.attributeNameCheck = customElementHandling.attributeNameCheck; // Default undefined\n }\n if (objectHasOwnProperty(customElementHandling, 'allowCustomizedBuiltInElements') && typeof customElementHandling.allowCustomizedBuiltInElements === 'boolean') {\n CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = customElementHandling.allowCustomizedBuiltInElements; // Default undefined\n }\n seal(CUSTOM_ELEMENT_HANDLING);\n if (SAFE_FOR_TEMPLATES) {\n ALLOW_DATA_ATTR = false;\n }\n if (RETURN_DOM_FRAGMENT) {\n RETURN_DOM = true;\n }\n /* Parse profile info */\n if (USE_PROFILES) {\n ALLOWED_TAGS = addToSet({}, text);\n ALLOWED_ATTR = create(null);\n if (USE_PROFILES.html === true) {\n addToSet(ALLOWED_TAGS, html$1);\n addToSet(ALLOWED_ATTR, html);\n }\n if (USE_PROFILES.svg === true) {\n addToSet(ALLOWED_TAGS, svg$1);\n addToSet(ALLOWED_ATTR, svg);\n addToSet(ALLOWED_ATTR, xml);\n }\n if (USE_PROFILES.svgFilters === true) {\n addToSet(ALLOWED_TAGS, svgFilters);\n addToSet(ALLOWED_ATTR, svg);\n addToSet(ALLOWED_ATTR, xml);\n }\n if (USE_PROFILES.mathMl === true) {\n addToSet(ALLOWED_TAGS, mathMl$1);\n addToSet(ALLOWED_ATTR, mathMl);\n addToSet(ALLOWED_ATTR, xml);\n }\n }\n /* Always reset function-based ADD_TAGS / ADD_ATTR checks to prevent\n * leaking across calls when switching from function to array config */\n EXTRA_ELEMENT_HANDLING.tagCheck = null;\n EXTRA_ELEMENT_HANDLING.attributeCheck = null;\n /* Merge configuration parameters */\n if (objectHasOwnProperty(cfg, 'ADD_TAGS')) {\n if (typeof cfg.ADD_TAGS === 'function') {\n EXTRA_ELEMENT_HANDLING.tagCheck = cfg.ADD_TAGS;\n } else if (arrayIsArray(cfg.ADD_TAGS)) {\n if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {\n ALLOWED_TAGS = clone(ALLOWED_TAGS);\n }\n addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc);\n }\n }\n if (objectHasOwnProperty(cfg, 'ADD_ATTR')) {\n if (typeof cfg.ADD_ATTR === 'function') {\n EXTRA_ELEMENT_HANDLING.attributeCheck = cfg.ADD_ATTR;\n } else if (arrayIsArray(cfg.ADD_ATTR)) {\n if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {\n ALLOWED_ATTR = clone(ALLOWED_ATTR);\n }\n addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc);\n }\n }\n if (objectHasOwnProperty(cfg, 'ADD_URI_SAFE_ATTR') && arrayIsArray(cfg.ADD_URI_SAFE_ATTR)) {\n addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc);\n }\n if (objectHasOwnProperty(cfg, 'FORBID_CONTENTS') && arrayIsArray(cfg.FORBID_CONTENTS)) {\n if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {\n FORBID_CONTENTS = clone(FORBID_CONTENTS);\n }\n addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc);\n }\n if (objectHasOwnProperty(cfg, 'ADD_FORBID_CONTENTS') && arrayIsArray(cfg.ADD_FORBID_CONTENTS)) {\n if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {\n FORBID_CONTENTS = clone(FORBID_CONTENTS);\n }\n addToSet(FORBID_CONTENTS, cfg.ADD_FORBID_CONTENTS, transformCaseFunc);\n }\n /* Add #text in case KEEP_CONTENT is set to true */\n if (KEEP_CONTENT) {\n ALLOWED_TAGS['#text'] = true;\n }\n /* Add html, head and body to ALLOWED_TAGS in case WHOLE_DOCUMENT is true */\n if (WHOLE_DOCUMENT) {\n addToSet(ALLOWED_TAGS, ['html', 'head', 'body']);\n }\n /* Add tbody to ALLOWED_TAGS in case tables are permitted, see #286, #365 */\n if (ALLOWED_TAGS.table) {\n addToSet(ALLOWED_TAGS, ['tbody']);\n delete FORBID_TAGS.tbody;\n }\n // Re-derive the active Trusted Types policy from this configuration on\n // every parse. The active policy must never be sticky closure state that\n // outlives the config that set it: a caller-supplied policy left in place\n // after `clearConfig()` — or after a later call that supplied none, or\n // `TRUSTED_TYPES_POLICY: null` — could sign a subsequent \"default\"\n // `RETURN_TRUSTED_TYPE` result with a foreign, possibly unsafe policy.\n // See GHSA-vxr8-fq34-vvx9.\n if (cfg.TRUSTED_TYPES_POLICY) {\n if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== 'function') {\n throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a \"createHTML\" hook.');\n }\n if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== 'function') {\n throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a \"createScriptURL\" hook.');\n }\n // A caller-supplied policy applies to this configuration only.\n const previousTrustedTypesPolicy = trustedTypesPolicy;\n trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY;\n // Sign local variables required by `sanitize`. If the supplied policy's\n // `createHTML` is circular (i.e. it calls `DOMPurify.sanitize`), this\n // throws via the re-entrancy guard. Restore the previous policy first so\n // the instance is not left in a poisoned state. See #1422.\n try {\n emptyHTML = _createTrustedHTML('');\n } catch (error) {\n trustedTypesPolicy = previousTrustedTypesPolicy;\n throw error;\n }\n } else if (cfg.TRUSTED_TYPES_POLICY === null) {\n // Explicit opt-out for this call: perform no Trusted Types signing and\n // create nothing (so a strict `trusted-types` CSP that disallows a\n // `dompurify` policy can still call `sanitize` from inside its own\n // policy — see #1422). Resetting to `undefined` rather than a sticky\n // `null` also drops any previously retained caller policy, so it cannot\n // resurface on a later call, while still allowing the next config-less\n // call to restore the internal default policy. See GHSA-vxr8-fq34-vvx9.\n trustedTypesPolicy = undefined;\n emptyHTML = '';\n } else {\n // No policy supplied: keep the currently active policy if one is set — a\n // previously supplied policy is intentionally sticky across config-less\n // calls — otherwise fall back to the instance's own internal policy,\n // created at most once. (A policy supplied for a *single* call still\n // lingers by design; what must not linger is a policy whose configuration\n // has been torn down via `clearConfig()`, which restores the default.)\n if (trustedTypesPolicy === undefined) {\n trustedTypesPolicy = _getDefaultTrustedTypesPolicy();\n }\n // Sign internal variables only when a policy is active. A falsy policy\n // (Trusted Types unsupported, creation failed, or an explicit opt-out)\n // leaves `emptyHTML` as a plain string, so we never call `.createHTML` on\n // a non-policy and throw. See #1422.\n if (trustedTypesPolicy && typeof emptyHTML === 'string') {\n emptyHTML = _createTrustedHTML('');\n }\n }\n // Prevent further manipulation of configuration.\n // Not available in IE8, Safari 5, etc.\n if (freeze) {\n freeze(cfg);\n }\n CONFIG = cfg;\n };\n /* Keep track of all possible SVG and MathML tags\n * so that we can perform the namespace checks\n * correctly. */\n const ALL_SVG_TAGS = addToSet({}, [...svg$1, ...svgFilters, ...svgDisallowed]);\n const ALL_MATHML_TAGS = addToSet({}, [...mathMl$1, ...mathMlDisallowed]);\n /**\n * Namespace rules for an element in the SVG namespace.\n *\n * @param tagName the element's lowercase tag name\n * @param parent the (possibly simulated) parent node\n * @param parentTagName the parent's lowercase tag name\n * @returns true if a spec-compliant parser could produce this element\n */\n const _checkSvgNamespace = function _checkSvgNamespace(tagName, parent, parentTagName) {\n // The only way to switch from HTML namespace to SVG\n // is via <svg>. If it happens via any other tag, then\n // it should be killed.\n if (parent.namespaceURI === HTML_NAMESPACE) {\n return tagName === 'svg';\n }\n // The only way to switch from MathML to SVG is via <svg>\n // if the parent is either <annotation-xml> or a MathML\n // text integration point.\n if (parent.namespaceURI === MATHML_NAMESPACE) {\n return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);\n }\n // We only allow elements that are defined in SVG\n // spec. All others are disallowed in SVG namespace.\n return Boolean(ALL_SVG_TAGS[tagName]);\n };\n /**\n * Namespace rules for an element in the MathML namespace.\n *\n * @param tagName the element's lowercase tag name\n * @param parent the (possibly simulated) parent node\n * @param parentTagName the parent's lowercase tag name\n * @returns true if a spec-compliant parser could produce this element\n */\n const _checkMathMlNamespace = function _checkMathMlNamespace(tagName, parent, parentTagName) {\n // The only way to switch from HTML namespace to MathML\n // is via <math>. If it happens via any other tag, then\n // it should be killed.\n if (parent.namespaceURI === HTML_NAMESPACE) {\n return tagName === 'math';\n }\n // The only way to switch from SVG to MathML is via\n // <math> and HTML integration points\n if (parent.namespaceURI === SVG_NAMESPACE) {\n return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];\n }\n // We only allow elements that are defined in MathML\n // spec. All others are disallowed in MathML namespace.\n return Boolean(ALL_MATHML_TAGS[tagName]);\n };\n /**\n * Namespace rules for an element in the HTML namespace.\n *\n * @param tagName the element's lowercase tag name\n * @param parent the (possibly simulated) parent node\n * @param parentTagName the parent's lowercase tag name\n * @returns true if a spec-compliant parser could produce this element\n */\n const _checkHtmlNamespace = function _checkHtmlNamespace(tagName, parent, parentTagName) {\n // The only way to switch from SVG to HTML is via\n // HTML integration points, and from MathML to HTML\n // is via MathML text integration points\n if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {\n return false;\n }\n if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {\n return false;\n }\n // We disallow tags that are specific for MathML\n // or SVG and should never appear in HTML namespace\n return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);\n };\n /**\n * @param element a DOM element whose namespace is being checked\n * @returns Return false if the element has a\n * namespace that a spec-compliant parser would never\n * return. Return true otherwise.\n */\n const _checkValidNamespace = function _checkValidNamespace(element) {\n let parent = getParentNode(element);\n // In JSDOM, if we're inside shadow DOM, then parentNode\n // can be null. We just simulate parent in this case.\n if (!parent || !parent.tagName) {\n parent = {\n namespaceURI: NAMESPACE,\n tagName: 'template'\n };\n }\n const tagName = stringToLowerCase(element.tagName);\n const parentTagName = stringToLowerCase(parent.tagName);\n if (!ALLOWED_NAMESPACES[element.namespaceURI]) {\n return false;\n }\n if (element.namespaceURI === SVG_NAMESPACE) {\n return _checkSvgNamespace(tagName, parent, parentTagName);\n }\n if (element.namespaceURI === MATHML_NAMESPACE) {\n return _checkMathMlNamespace(tagName, parent, parentTagName);\n }\n if (element.namespaceURI === HTML_NAMESPACE) {\n return _checkHtmlNamespace(tagName, parent, parentTagName);\n }\n // For XHTML and XML documents that support custom namespaces\n if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && ALLOWED_NAMESPACES[element.namespaceURI]) {\n return true;\n }\n // The code should never reach this place (this means\n // that the element somehow got namespace that is not\n // HTML, SVG, MathML or allowed via ALLOWED_NAMESPACES).\n // Return false just in case.\n return false;\n };\n /**\n * _forceRemove\n *\n * @param node a DOM node\n */\n const _forceRemove = function _forceRemove(node) {\n arrayPush(DOMPurify.removed, {\n element: node\n });\n try {\n // eslint-disable-next-line unicorn/prefer-dom-node-remove\n getParentNode(node).removeChild(node);\n } catch (_) {\n /* The normal detach failed — this is reached for a parentless node\n (getParentNode() is null, so .removeChild throws). Element.prototype\n .remove() is itself a spec no-op on a parentless node, so a recorded\n \"removal\" would otherwise hand the caller back an intact,\n payload-bearing node (e.g. a detached IN_PLACE root the mXSS canary or\n the style-with-element-child rule decided to kill). Fail closed by\n throwing — exactly as a clobbered root does at the IN_PLACE entry —\n rather than trying to \"neutralize\" the node via its own methods.\n Neutralizing would mean calling getAttributeNames()/removeAttribute()\n on the node, both of which a <form> root can clobber via a named child\n (and _isClobbered does not even probe getAttributeNames), so the\n neutralize step could itself be silently defeated, leaving the payload\n intact. A throw touches only the cached, clobber-safe remove() and\n getParentNode(). Generalizes GHSA-r47g-fvhr-h676 (clobbered-form root)\n to every root-kill reason. REPORT-3.\n This lives inside the catch, so it never fires for a normally-removed\n in-tree node: those have a parent, removeChild() succeeds, and the\n catch is not entered. Only a kept (parentless) root reaches here. */\n remove(node);\n if (!getParentNode(node)) {\n throw typeErrorCreate('a node selected for removal could not be detached from its tree ' + 'and cannot be safely returned; refusing to sanitize in place');\n }\n }\n };\n /**\n * _neutralizeRoot\n *\n * Fail-closed teardown of an in-place root after the sanitize walk aborts\n * (campaign-3 F2). An internal throw mid-walk — e.g. a page-registered\n * custom element's reaction detaches a node so `_forceRemove`'s deliberate\n * parentless guard throws, or any other re-entrant engine mutation — would\n * otherwise leave the caller's *live* tree half-sanitized, with everything\n * after the abort point still carrying its handlers. There is no safe way\n * to resume the walk (the tree mutated under us), so we strip the root bare:\n * remove every child and every attribute, then let the caller's catch see\n * the original error. Clobber-safe (cached `remove`/`childNodes`/`attributes`\n * getters; the root was already clobber-pre-flighted at the IN_PLACE entry).\n *\n * @param root the in-place root to empty\n */\n const _neutralizeRoot = function _neutralizeRoot(root) {\n const childNodes = getChildNodes(root);\n if (childNodes) {\n const snapshot = [];\n arrayForEach(childNodes, child => {\n arrayPush(snapshot, child);\n });\n arrayForEach(snapshot, child => {\n try {\n remove(child);\n } catch (_) {\n /* Best-effort teardown; a still-attached child is handled below */\n }\n });\n }\n const attributes = getAttributes(root);\n if (attributes) {\n for (let i = attributes.length - 1; i >= 0; --i) {\n const attribute = attributes[i];\n const name = attribute && attribute.name;\n if (typeof name === 'string') {\n try {\n root.removeAttribute(name);\n } catch (_) {\n /* Clobbered removeAttribute — ignore (fail-closed best effort) */\n }\n }\n }\n }\n };\n /**\n * _removeAttribute\n *\n * @param name an Attribute name\n * @param element a DOM node\n */\n const _removeAttribute = function _removeAttribute(name, element) {\n try {\n arrayPush(DOMPurify.removed, {\n attribute: element.getAttributeNode(name),\n from: element\n });\n } catch (_) {\n arrayPush(DOMPurify.removed, {\n attribute: null,\n from: element\n });\n }\n element.removeAttribute(name);\n // We void attribute values for unremovable \"is\" attributes\n if (name === 'is') {\n if (RETURN_DOM || RETURN_DOM_FRAGMENT) {\n try {\n _forceRemove(element);\n } catch (_) {}\n } else {\n try {\n element.setAttribute(name, '');\n } catch (_) {}\n }\n }\n };\n /**\n * _stripDisallowedAttributes\n *\n * Removes every attribute the active configuration does not allow from a\n * single element, using the same allowlist as the main attribute pass (so\n * `on*` handlers go, but no `/^on/` blocklist is introduced). Used only to\n * neutralise nodes that are being discarded from an in-place tree.\n *\n * @param element the element to strip\n */\n const _stripDisallowedAttributes = function _stripDisallowedAttributes(element) {\n const attributes = getAttributes(element);\n if (!attributes) {\n return;\n }\n for (let i = attributes.length - 1; i >= 0; --i) {\n const attribute = attributes[i];\n const name = attribute && attribute.name;\n if (typeof name !== 'string' || ALLOWED_ATTR[transformCaseFunc(name)]) {\n continue;\n }\n try {\n element.removeAttribute(name);\n } catch (_) {\n /* Clobbered removeAttribute on a doomed node — ignore */\n }\n }\n };\n /**\n * _neutralizeSubtree\n *\n * Completes the audit-5 F1 fix across every removal path. The KEEP_CONTENT\n * move-hoist neutralises only disallowed-tag removals; clobber, mXSS-canary,\n * namespace, comment, processing-instruction and KEEP_CONTENT:false removals\n * all drop their subtree wholesale via `_forceRemove`. On the IN_PLACE path\n * those dropped nodes are detached from the caller's LIVE tree but a\n * handler-bearing original among them (an `<img onerror>`/`<video>` that was\n * loading) keeps its queued resource event, which fires in page scope after\n * sanitize returns. This walks a removed subtree and strips every attribute\n * the active configuration does not allow — so `on*` handlers are cancelled\n * through the SAME allowlist that governs kept nodes, not a separate `/^on/`\n * blocklist. Run synchronously before sanitize returns, i.e. before any\n * queued event can fire. Hook-free by design: these nodes leave the output,\n * so firing attribute hooks for them would be surprising. Clobber-safe reads;\n * a doomed clobbered node may shadow `removeAttribute` (its own attributes are\n * irrelevant — it is discarded — while its non-clobbered descendants, e.g.\n * the `<img>`, are reached and scrubbed).\n *\n * @param root the root of a removed subtree to neutralise\n */\n const _neutralizeSubtree = function _neutralizeSubtree(root) {\n const stack = [root];\n while (stack.length > 0) {\n const node = stack.pop();\n const nodeType = getNodeType ? getNodeType(node) : node.nodeType;\n if (nodeType === NODE_TYPE.element) {\n _stripDisallowedAttributes(node);\n }\n const childNodes = getChildNodes(node);\n if (childNodes) {\n for (let i = childNodes.length - 1; i >= 0; --i) {\n stack.push(childNodes[i]);\n }\n }\n }\n };\n /**\n * _initDocument\n *\n * @param dirty - a string of dirty markup\n * @return a DOM, filled with the dirty markup\n */\n const _initDocument = function _initDocument(dirty) {\n /* Create a HTML document */\n let doc = null;\n let leadingWhitespace = null;\n if (FORCE_BODY) {\n dirty = '<remove></remove>' + dirty;\n } else {\n /* If FORCE_BODY isn't used, leading whitespace needs to be preserved manually */\n const matches = stringMatch(dirty, /^[\\r\\n\\t ]+/);\n leadingWhitespace = matches && matches[0];\n }\n if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && NAMESPACE === HTML_NAMESPACE) {\n // Root of XHTML doc must contain xmlns declaration (see https://www.w3.org/TR/xhtml1/normative.html#strict)\n dirty = '<html xmlns=\"http://www.w3.org/1999/xhtml\"><head></head><body>' + dirty + '</body></html>';\n }\n const dirtyPayload = trustedTypesPolicy ? _createTrustedHTML(dirty) : dirty;\n /*\n * Use the DOMParser API by default, fallback later if needs be\n * DOMParser not work for svg when has multiple root element.\n */\n if (NAMESPACE === HTML_NAMESPACE) {\n try {\n doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE);\n } catch (_) {}\n }\n /* Use createHTMLDocument in case DOMParser is not available */\n if (!doc || !doc.documentElement) {\n doc = implementation.createDocument(NAMESPACE, 'template', null);\n try {\n doc.documentElement.innerHTML = IS_EMPTY_INPUT ? emptyHTML : dirtyPayload;\n } catch (_) {\n // Syntax error if dirtyPayload is invalid xml\n }\n }\n const body = doc.body || doc.documentElement;\n if (dirty && leadingWhitespace) {\n body.insertBefore(document.createTextNode(leadingWhitespace), body.childNodes[0] || null);\n }\n /* Work on whole document or just its body */\n if (NAMESPACE === HTML_NAMESPACE) {\n return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? 'html' : 'body')[0];\n }\n return WHOLE_DOCUMENT ? doc.documentElement : body;\n };\n /**\n * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document.\n *\n * @param root The root element or node to start traversing on.\n * @return The created NodeIterator\n */\n const _createNodeIterator = function _createNodeIterator(root) {\n return createNodeIterator.call(root.ownerDocument || root, root,\n // eslint-disable-next-line no-bitwise\n NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT | NodeFilter.SHOW_PROCESSING_INSTRUCTION | NodeFilter.SHOW_CDATA_SECTION, null);\n };\n /**\n * Replace template expression syntax (mustache, ERB, template\n * literal) with a space; shared by all SAFE_FOR_TEMPLATES scrub\n * sites. Order matters: mustache, then ERB, then template literal.\n *\n * @param value the string to scrub\n * @returns the scrubbed string\n */\n const _stripTemplateExpressions = function _stripTemplateExpressions(value) {\n value = stringReplace(value, MUSTACHE_EXPR$1, ' ');\n value = stringReplace(value, ERB_EXPR$1, ' ');\n value = stringReplace(value, TMPLIT_EXPR$1, ' ');\n return value;\n };\n /**\n * Strip template-engine expressions ({{...}}, ${...}, <%...%>) from the\n * character data of an element subtree. Used as the final safety net for\n * SAFE_FOR_TEMPLATES on every DOM-returning code path so that expressions\n * which only form after text-node normalization (e.g. fragments split across\n * stripped elements) cannot survive into a template-evaluating framework.\n *\n * Walks text/comment/CDATA/processing-instruction nodes and mutates `.data`\n * in place rather than round-tripping through innerHTML. This preserves\n * descendant node references (important for IN_PLACE callers), avoids a\n * serialize/reparse cycle, and reads literal character data — which means\n * `<%...%>` in text content matches the ERB regex against its real bytes\n * instead of the HTML-entity-escaped form innerHTML would produce.\n *\n * Attribute values are not visited here; SAFE_FOR_TEMPLATES handling for\n * attributes is performed during the per-node `_sanitizeAttributes` pass.\n *\n * @param node The root element whose character data should be scrubbed.\n */\n const _scrubTemplateExpressions2 = function _scrubTemplateExpressions(node) {\n var _node$querySelectorAl;\n node.normalize();\n const walker = createNodeIterator.call(node.ownerDocument || node, node,\n // eslint-disable-next-line no-bitwise\n NodeFilter.SHOW_TEXT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_CDATA_SECTION | NodeFilter.SHOW_PROCESSING_INSTRUCTION, null);\n let currentNode = walker.nextNode();\n while (currentNode) {\n currentNode.data = _stripTemplateExpressions(currentNode.data);\n currentNode = walker.nextNode();\n }\n // NodeIterator does not descend into <template>.content per the DOM spec,\n // so we must explicitly recurse into each template's content fragment,\n // mirroring the approach used by _sanitizeShadowDOM.\n const templates = (_node$querySelectorAl = node.querySelectorAll) === null || _node$querySelectorAl === void 0 ? void 0 : _node$querySelectorAl.call(node, 'template');\n if (templates) {\n arrayForEach(templates, tmpl => {\n if (_isDocumentFragment(tmpl.content)) {\n _scrubTemplateExpressions2(tmpl.content);\n }\n });\n }\n };\n /**\n * _isClobbered\n *\n * Detect DOM-clobbering on HTMLFormElement nodes. Form is the only HTML\n * interface with [LegacyOverrideBuiltIns]; a descendant element with a\n * `name` attribute matching a prototype property shadows that property\n * on direct reads. We use this check at the IN_PLACE entry-point and\n * during attribute sanitization to refuse clobbered forms.\n *\n * @param element element to check for clobbering attacks\n * @return true if clobbered, false if safe\n */\n const _isClobbered = function _isClobbered(element) {\n // Realm-independent tag-name probe. If we can't determine the tag\n // name at all, we can't reason about clobbering — return false\n // (the caller's other defences still apply).\n const realTagName = getNodeName ? getNodeName(element) : null;\n if (typeof realTagName !== 'string') {\n return false;\n }\n if (transformCaseFunc(realTagName) !== 'form') {\n return false;\n }\n return typeof element.nodeName !== 'string' || typeof element.textContent !== 'string' || typeof element.removeChild !== 'function' ||\n // Realm-safe NamedNodeMap detection: equality against the cached\n // prototype getter. Clobbered .attributes (e.g. <input name=\"attributes\">)\n // makes the direct read diverge from the cached read; a clean form\n // (same-realm OR foreign-realm) has both reads pointing at the same\n // canonical NamedNodeMap.\n element.attributes !== getAttributes(element) || typeof element.removeAttribute !== 'function' || typeof element.setAttribute !== 'function' || typeof element.namespaceURI !== 'string' || typeof element.insertBefore !== 'function' || typeof element.hasChildNodes !== 'function' ||\n // NodeType clobbering probe. Cached Node.prototype.nodeType getter\n // returns the integer 1 for any Element regardless of realm; direct\n // read on a clobbered form (e.g. <input name=\"nodeType\">) returns\n // the named child element. Cheap addition — nodeType is read from\n // an internal slot, no serialization cost — and removes a residual\n // clobbering surface used by several mXSS / PI / comment branches\n // in _sanitizeElements that compare currentNode.nodeType directly.\n element.nodeType !== getNodeType(element) ||\n // HTMLFormElement has [LegacyOverrideBuiltIns]: a descendant named\n // \"childNodes\" shadows the prototype getter. Direct reads of\n // form.childNodes from a clobbered form return the named child\n // instead of the real NodeList, so any walk that reads it directly\n // skips the form's real children. Compare the direct read to the\n // cached Node.prototype getter — when the form's named-property\n // getter intercepts the read, the two values differ and we flag\n // the form. This catches every clobbering child type (input,\n // select, etc.) regardless of whether the named child happens to\n // carry a numeric .length, which a typeof-based probe would miss\n // (e.g. HTMLSelectElement.length is a defined unsigned-long).\n element.childNodes !== getChildNodes(element);\n };\n /**\n * Checks whether the given value is a DocumentFragment from any realm.\n *\n * The realm-independent replacement reads `nodeType` through the cached\n * Node.prototype getter and compares to the DOCUMENT_FRAGMENT_NODE\n * constant (11). nodeType is a numeric value resolved from the node's\n * internal slot, identical across realms for the same kind of node.\n *\n * @param value object to check\n * @return true if value is a DocumentFragment-shaped node from any realm\n */\n const _isDocumentFragment = function _isDocumentFragment(value) {\n if (!getNodeType || typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return getNodeType(value) === NODE_TYPE.documentFragment;\n } catch (_) {\n return false;\n }\n };\n /**\n * Checks whether the given object is a DOM node, including nodes that\n * originate from a different window/realm (e.g. an iframe's\n * contentDocument). The previous `value instanceof Node` check was\n * realm-bound: nodes from a different window failed it, causing\n * sanitize() to silently stringify them and reset IN_PLACE to false,\n * returning the original node unsanitized. See GHSA-4w3q-35jp-p934.\n *\n * @param value object to check whether it's a DOM node\n * @return true if value is a DOM node from any realm\n */\n const _isNode = function _isNode(value) {\n if (!getNodeType || typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof getNodeType(value) === 'number';\n } catch (_) {\n return false;\n }\n };\n function _executeHooks(hooks, currentNode, data) {\n if (hooks.length === 0) {\n return;\n }\n arrayForEach(hooks, hook => {\n hook.call(DOMPurify, currentNode, data, CONFIG);\n });\n }\n /**\n * Structural-threat checks that condemn a node regardless of the\n * allowlists: mXSS via namespace confusion, risky CSS construction,\n * processing instructions, markup-bearing comments. Pure predicate;\n * the caller removes. Check order is load-bearing.\n *\n * @param currentNode the node to inspect\n * @param tagName the node's transformCaseFunc'd tag name\n * @return true if the node must be removed\n */\n const _isUnsafeNode = function _isUnsafeNode(currentNode, tagName) {\n /* Detect mXSS attempts abusing namespace confusion */\n if (SAFE_FOR_XML && currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(ELEMENT_MARKUP_PROBE, currentNode.textContent) && regExpTest(ELEMENT_MARKUP_PROBE, currentNode.innerHTML)) {\n return true;\n }\n /* Remove risky CSS construction leading to mXSS */\n if (SAFE_FOR_XML && currentNode.namespaceURI === HTML_NAMESPACE && tagName === 'style' && _isNode(currentNode.firstElementChild)) {\n return true;\n }\n /* Remove any occurrence of processing instructions */\n if (currentNode.nodeType === NODE_TYPE.processingInstruction) {\n return true;\n }\n /* Remove any kind of possibly harmful comments */\n if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(COMMENT_MARKUP_PROBE, currentNode.data)) {\n return true;\n }\n return false;\n };\n /**\n * Handle a node whose tag is forbidden or not allowlisted: keep\n * allowed custom elements (false return exits _sanitizeElements\n * early - namespace/fallback checks and the afterSanitizeElements\n * hook are intentionally skipped for kept custom elements), else\n * hoist content per KEEP_CONTENT and remove.\n *\n * @param currentNode the disallowed node\n * @param tagName the node's transformCaseFunc'd tag name\n * @return true if the node was removed, false if kept\n */\n const _sanitizeDisallowedNode = function _sanitizeDisallowedNode(currentNode, tagName) {\n /* Check if we have a custom element to handle */\n if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) {\n if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) {\n return false;\n }\n if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) {\n return false;\n }\n }\n /* Keep content except for bad-listed elements.\n Use the cached prototype getters exclusively — the previous code\n had `|| currentNode.parentNode` / `|| currentNode.childNodes`\n fallbacks, but the cached getters always return the canonical\n value (or null for a real parent-less node), so the fallback\n path was dead in safe cases and a clobbering surface in unsafe\n ones. Falsy cached results stay falsy; the `if (childNodes &&\n parentNode)` check already gates correctly. */\n if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {\n const parentNode = getParentNode(currentNode);\n const childNodes = getChildNodes(currentNode);\n if (childNodes && parentNode) {\n const childCount = childNodes.length;\n /* In-place: hoist the *original* children so the iterator visits\n and sanitises them through the same allowlist pass as every other\n node. The caller built the tree in the live document, so the\n originals carry already-queued resource events (`<img onerror>`,\n `<video>`/`<audio>` error, lazy/`onload`, …); cloning would leave\n those originals detached but still armed, firing in page scope\n while the returned tree looked clean. Moving is safe in-place: the\n root is pre-validated as an allowed tag and so is never the node\n being removed, which keeps `parentNode` inside the iterator root\n and the relocated child inside the serialised tree.\n Otherwise (string / DOM-copy paths): clone. The iterator is rooted\n at — and the result serialised from — `body`, so a restrictive\n ALLOWED_TAGS that removes `body` itself must leave its content in\n place, which only cloning does; and those paths parse into an\n inert document, so their discarded originals never had a queued\n event to neutralise.\n `childNodes` is live; a tail-to-head walk keeps `childNodes[i]`\n valid whether we move (drops the trailing entry) or clone (leaves\n the list intact). */\n for (let i = childCount - 1; i >= 0; --i) {\n const hoisted = IN_PLACE ? childNodes[i] : cloneNode(childNodes[i], true);\n parentNode.insertBefore(hoisted, getNextSibling(currentNode));\n }\n }\n }\n _forceRemove(currentNode);\n return true;\n };\n /**\n * _sanitizeElements\n *\n * @protect nodeName\n * @protect textContent\n * @protect removeChild\n * @param currentNode to check for permission to exist\n * @return true if node was killed, false if left alive\n */\n const _sanitizeElements = function _sanitizeElements(currentNode) {\n /* Execute a hook if present */\n _executeHooks(hooks.beforeSanitizeElements, currentNode, null);\n /* Check if element is clobbered or can clobber */\n if (_isClobbered(currentNode)) {\n _forceRemove(currentNode);\n return true;\n }\n /* Now let's check the element's type and name */\n const tagName = transformCaseFunc(getNodeName ? getNodeName(currentNode) : currentNode.nodeName);\n /* Execute a hook if present */\n _executeHooks(hooks.uponSanitizeElement, currentNode, {\n tagName,\n allowedTags: ALLOWED_TAGS\n });\n /* Remove mXSS vectors, processing instructions and risky comments */\n if (_isUnsafeNode(currentNode, tagName)) {\n _forceRemove(currentNode);\n return true;\n }\n /* Remove element if anything forbids its presence */\n if (FORBID_TAGS[tagName] || !(EXTRA_ELEMENT_HANDLING.tagCheck instanceof Function && EXTRA_ELEMENT_HANDLING.tagCheck(tagName)) && !ALLOWED_TAGS[tagName]) {\n return _sanitizeDisallowedNode(currentNode, tagName);\n }\n /* Check whether element has a valid namespace.\n Realm-safe check (GHSA-hpcv-96wg-7vj8): use the cached Node.prototype\n nodeType getter rather than `instanceof Element`, which is realm-\n bound and short-circuits to false for any node minted in a different\n realm — letting a foreign-realm element with a forbidden namespace\n slip past the namespace check entirely. */\n const nt = getNodeType ? getNodeType(currentNode) : currentNode.nodeType;\n if (nt === NODE_TYPE.element && !_checkValidNamespace(currentNode)) {\n _forceRemove(currentNode);\n return true;\n }\n /* Make sure that older browsers don't get fallback-tag mXSS */\n if ((tagName === 'noscript' || tagName === 'noembed' || tagName === 'noframes') && regExpTest(FALLBACK_TAG_CLOSE, currentNode.innerHTML)) {\n _forceRemove(currentNode);\n return true;\n }\n /* Sanitize element content to be template-safe */\n if (SAFE_FOR_TEMPLATES && currentNode.nodeType === NODE_TYPE.text) {\n /* Get the element's text content */\n const content = _stripTemplateExpressions(currentNode.textContent);\n if (currentNode.textContent !== content) {\n arrayPush(DOMPurify.removed, {\n element: currentNode.cloneNode()\n });\n currentNode.textContent = content;\n }\n }\n /* Execute a hook if present */\n _executeHooks(hooks.afterSanitizeElements, currentNode, null);\n return false;\n };\n /**\n * _isValidAttribute\n *\n * @param lcTag Lowercase tag name of containing element.\n * @param lcName Lowercase attribute name.\n * @param value Attribute value.\n * @return Returns true if `value` is valid, otherwise false.\n */\n // eslint-disable-next-line complexity\n const _isValidAttribute = function _isValidAttribute(lcTag, lcName, value) {\n /* FORBID_ATTR must always win, even if ADD_ATTR predicate would allow it */\n if (FORBID_ATTR[lcName]) {\n return false;\n }\n /* Make sure attribute cannot clobber */\n if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) {\n return false;\n }\n const nameIsPermitted = ALLOWED_ATTR[lcName] || EXTRA_ELEMENT_HANDLING.attributeCheck instanceof Function && EXTRA_ELEMENT_HANDLING.attributeCheck(lcName, lcTag);\n /* Allow valid data-* attributes: At least one character after \"-\"\n (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)\n XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)\n We don't need to check the value; it's always URI safe. */\n if (ALLOW_DATA_ATTR && regExpTest(DATA_ATTR$1, lcName)) ; else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR$1, lcName)) ; else if (!nameIsPermitted) {\n if (\n // First condition does a very basic check if a) it's basically a valid custom element tagname AND\n // b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck\n // and c) if the attribute name passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.attributeNameCheck\n _isBasicCustomElement(lcTag) && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, lcTag) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(lcTag)) && (CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.attributeNameCheck, lcName) || CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.attributeNameCheck(lcName, lcTag)) ||\n // Alternative, second condition checks if it's an `is`-attribute, AND\n // the value passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck\n lcName === 'is' && CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, value) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(value))) ; else {\n return false;\n }\n /* Check value is safe. First, is attr inert? If so, is safe */\n } else if (URI_SAFE_ATTRIBUTES[lcName]) ; else if (regExpTest(IS_ALLOWED_URI$1, stringReplace(value, ATTR_WHITESPACE$1, ''))) ; else if ((lcName === 'src' || lcName === 'xlink:href' || lcName === 'href') && lcTag !== 'script' && stringIndexOf(value, 'data:') === 0 && DATA_URI_TAGS[lcTag]) ; else if (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA$1, stringReplace(value, ATTR_WHITESPACE$1, ''))) ; else if (value) {\n return false;\n } else ;\n return true;\n };\n /* Names the HTML spec reserves from valid-custom-element-name; these must\n * never be treated as basic custom elements even when a permissive\n * CUSTOM_ELEMENT_HANDLING.tagNameCheck is configured. */\n const RESERVED_CUSTOM_ELEMENT_NAMES = addToSet({}, ['annotation-xml', 'color-profile', 'font-face', 'font-face-format', 'font-face-name', 'font-face-src', 'font-face-uri', 'missing-glyph']);\n /**\n * _isBasicCustomElement\n * checks if at least one dash is included in tagName, and it's not the first char\n * for more sophisticated checking see https://github.com/sindresorhus/validate-element-name\n *\n * @param tagName name of the tag of the node to sanitize\n * @returns Returns true if the tag name meets the basic criteria for a custom element, otherwise false.\n */\n const _isBasicCustomElement = function _isBasicCustomElement(tagName) {\n return !RESERVED_CUSTOM_ELEMENT_NAMES[stringToLowerCase(tagName)] && regExpTest(CUSTOM_ELEMENT$1, tagName);\n };\n /**\n * Wrap an attribute value in the matching Trusted Types object when\n * the active policy requires it. Namespaced attributes pass through\n * unchanged (no TT support yet, see\n * https://bugs.chromium.org/p/chromium/issues/detail?id=1305293).\n *\n * @param lcTag lowercase tag name of the containing element\n * @param lcName lowercase attribute name\n * @param namespaceURI the attribute's namespace, if any\n * @param value the attribute value to wrap\n * @return the value, wrapped when Trusted Types demand it\n */\n const _applyTrustedTypesToAttribute = function _applyTrustedTypesToAttribute(lcTag, lcName, namespaceURI, value) {\n if (trustedTypesPolicy && typeof trustedTypes === 'object' && typeof trustedTypes.getAttributeType === 'function' && !namespaceURI) {\n switch (trustedTypes.getAttributeType(lcTag, lcName)) {\n case 'TrustedHTML':\n {\n return _createTrustedHTML(value);\n }\n case 'TrustedScriptURL':\n {\n return _createTrustedScriptURL(value);\n }\n }\n }\n return value;\n };\n /**\n * Write a modified attribute value back onto the element. On\n * success, re-probe for clobbering introduced by the new value and\n * remove the element when found; otherwise pop the removal entry\n * recorded by the earlier _removeAttribute (long-standing pairing\n * with the SANITIZE_NAMED_PROPS path - do not \"fix\" casually). On\n * failure, remove the attribute instead.\n *\n * @param currentNode the element carrying the attribute\n * @param name the attribute name as present on the element\n * @param namespaceURI the attribute's namespace, if any\n * @param value the new attribute value\n */\n const _setAttributeValue = function _setAttributeValue(currentNode, name, namespaceURI, value) {\n try {\n if (namespaceURI) {\n currentNode.setAttributeNS(namespaceURI, name, value);\n } else {\n /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. \"x-schema\". */\n currentNode.setAttribute(name, value);\n }\n if (_isClobbered(currentNode)) {\n _forceRemove(currentNode);\n } else {\n arrayPop(DOMPurify.removed);\n }\n } catch (_) {\n _removeAttribute(name, currentNode);\n }\n };\n /**\n * _sanitizeAttributes\n *\n * @protect attributes\n * @protect nodeName\n * @protect removeAttribute\n * @protect setAttribute\n *\n * @param currentNode to sanitize\n */\n const _sanitizeAttributes = function _sanitizeAttributes(currentNode) {\n /* Execute a hook if present */\n _executeHooks(hooks.beforeSanitizeAttributes, currentNode, null);\n const attributes = currentNode.attributes;\n /* Check if we have attributes; if not we might have a text node */\n if (!attributes || _isClobbered(currentNode)) {\n return;\n }\n const hookEvent = {\n attrName: '',\n attrValue: '',\n keepAttr: true,\n allowedAttributes: ALLOWED_ATTR,\n forceKeepAttr: undefined\n };\n let l = attributes.length;\n const lcTag = transformCaseFunc(currentNode.nodeName);\n /* Go backwards over all attributes; safely remove bad ones */\n while (l--) {\n const attr = attributes[l];\n const name = attr.name,\n namespaceURI = attr.namespaceURI,\n attrValue = attr.value;\n const lcName = transformCaseFunc(name);\n const initValue = attrValue;\n let value = name === 'value' ? initValue : stringTrim(initValue);\n /* Execute a hook if present */\n hookEvent.attrName = lcName;\n hookEvent.attrValue = value;\n hookEvent.keepAttr = true;\n hookEvent.forceKeepAttr = undefined; // Allows developers to see this is a property they can set\n _executeHooks(hooks.uponSanitizeAttribute, currentNode, hookEvent);\n value = hookEvent.attrValue;\n /* Full DOM Clobbering protection via namespace isolation,\n * Prefix id and name attributes with `user-content-`\n */\n if (SANITIZE_NAMED_PROPS && (lcName === 'id' || lcName === 'name') && stringIndexOf(value, SANITIZE_NAMED_PROPS_PREFIX) !== 0) {\n // Remove the attribute with this value\n _removeAttribute(name, currentNode);\n // Prefix the value and later re-create the attribute with the sanitized value\n value = SANITIZE_NAMED_PROPS_PREFIX + value;\n }\n // Else: already prefixed, leave the attribute alone — the prefix is\n // itself the clobbering protection, and re-applying it is incorrect.\n /* Work around a security issue with comments inside attributes */\n if (SAFE_FOR_XML && regExpTest(/((--!?|])>)|<\\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i, value)) {\n _removeAttribute(name, currentNode);\n continue;\n }\n /* Make sure we cannot easily use animated hrefs, even if animations are allowed */\n if (lcName === 'attributename' && stringMatch(value, 'href')) {\n _removeAttribute(name, currentNode);\n continue;\n }\n /* Did the hooks force-keep the attribute? */\n if (hookEvent.forceKeepAttr) {\n continue;\n }\n /* Did the hooks approve of the attribute? */\n if (!hookEvent.keepAttr) {\n _removeAttribute(name, currentNode);\n continue;\n }\n /* Work around a security issue in jQuery 3.0 */\n if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(SELF_CLOSING_TAG, value)) {\n _removeAttribute(name, currentNode);\n continue;\n }\n /* Sanitize attribute content to be template-safe */\n if (SAFE_FOR_TEMPLATES) {\n value = _stripTemplateExpressions(value);\n }\n /* Is `value` valid for this attribute? */\n if (!_isValidAttribute(lcTag, lcName, value)) {\n _removeAttribute(name, currentNode);\n continue;\n }\n /* Handle attributes that require Trusted Types */\n value = _applyTrustedTypesToAttribute(lcTag, lcName, namespaceURI, value);\n /* Handle invalid data-* attribute set by try-catching it */\n if (value !== initValue) {\n _setAttributeValue(currentNode, name, namespaceURI, value);\n }\n }\n /* Execute a hook if present */\n _executeHooks(hooks.afterSanitizeAttributes, currentNode, null);\n };\n /**\n * _sanitizeShadowDOM\n *\n * @param fragment to iterate over recursively\n */\n const _sanitizeShadowDOM2 = function _sanitizeShadowDOM(fragment) {\n let shadowNode = null;\n const shadowIterator = _createNodeIterator(fragment);\n /* Execute a hook if present */\n _executeHooks(hooks.beforeSanitizeShadowDOM, fragment, null);\n while (shadowNode = shadowIterator.nextNode()) {\n /* Execute a hook if present */\n _executeHooks(hooks.uponSanitizeShadowNode, shadowNode, null);\n /* Sanitize tags and elements */\n _sanitizeElements(shadowNode);\n /* Check attributes next */\n _sanitizeAttributes(shadowNode);\n /* Deep shadow DOM detected.\n Realm-safe check (GHSA-hpcv-96wg-7vj8): use nodeType against the\n DOCUMENT_FRAGMENT_NODE constant rather than instanceof, so we\n recurse into <template>.content from foreign realms too. */\n if (_isDocumentFragment(shadowNode.content)) {\n _sanitizeShadowDOM2(shadowNode.content);\n }\n /* An element iterated here may itself host an attached\n shadow root. The default NodeIterator does not enter shadow\n trees, so a shadow root nested inside template.content was\n previously reached by no walk at all (the pre-pass at\n _sanitizeAttachedShadowRoots descends via childNodes, which\n doesn't enter template.content; the template-content recursion\n above iterates the content but never inspected shadowRoot).\n Walk it explicitly. The nodeType guard avoids reading\n shadowRoot off text / comment / CDATA / PI nodes that the\n iterator also surfaces. */\n const shadowNodeType = getNodeType ? getNodeType(shadowNode) : shadowNode.nodeType;\n if (shadowNodeType === NODE_TYPE.element) {\n const innerSr = getShadowRoot(shadowNode);\n if (_isDocumentFragment(innerSr)) {\n _sanitizeAttachedShadowRoots(innerSr);\n _sanitizeShadowDOM2(innerSr);\n }\n }\n }\n /* Execute a hook if present */\n _executeHooks(hooks.afterSanitizeShadowDOM, fragment, null);\n };\n /**\n * _sanitizeAttachedShadowRoots\n *\n * Walks `root` and feeds every attached shadow root we encounter into\n * the existing _sanitizeShadowDOM pipeline. The default node iterator\n * does not descend into shadow trees, so nodes inside an attached\n * shadow root would otherwise be skipped entirely.\n *\n * Two real input paths put attached shadow roots in front of us:\n * 1. IN_PLACE on a DOM node that already has shadow roots attached.\n * 2. DOM-node input where importNode(dirty, true) deep-clones the\n * shadow root because it was created with `clonable: true`.\n *\n * This pass runs once, up front, so the main iteration loop (and the\n * existing _sanitizeShadowDOM template-content recursion) stay\n * untouched — string-input paths are not affected.\n *\n * @param root the subtree root to walk for attached shadow roots\n */\n const _sanitizeAttachedShadowRoots = function _sanitizeAttachedShadowRoots(root) {\n /* Iterative (explicit stack) rather than per-child recursion. DOM APIs\n impose no depth cap, so an attacker-shaped tree (JSON/CRDT/editor data\n built straight into the DOM — the IN_PLACE surface) deeper than the JS\n call-stack budget would otherwise overflow native recursion here and\n throw at the IN_PLACE entry pre-pass, before a single node is\n sanitized, leaving the caller's live tree untouched (fail-open). See\n campaign-3 F4. A heap stack keeps depth off the call stack.\n Each work item is either a node to descend into, or a deferred\n `_sanitizeShadowDOM` for an already-walked shadow root. The deferred\n form preserves the original post-order discipline: a shadow root's\n nested shadow roots are discovered before the outer shadow is\n sanitized (which may remove hosts). Pushes are in reverse of the\n desired processing order (LIFO): template content, then children, then\n the shadow-sanitize, then the shadow walk — so the order matches the\n previous recursion exactly. */\n const stack = [{\n node: root,\n shadow: null\n }];\n while (stack.length > 0) {\n const item = stack.pop();\n /* Deferred shadow-DOM sanitisation: runs after its subtree was walked. */\n if (item.shadow) {\n _sanitizeShadowDOM2(item.shadow);\n continue;\n }\n const node = item.node;\n const nodeType = getNodeType ? getNodeType(node) : node.nodeType;\n const isElement = nodeType === NODE_TYPE.element;\n /* (pushed last → processed first) Children, snapshotted in reverse so\n the first child is processed first. Snapshotting matters because a\n hook may detach siblings mid-walk. */\n const childNodes = getChildNodes(node);\n if (childNodes) {\n for (let i = childNodes.length - 1; i >= 0; --i) {\n stack.push({\n node: childNodes[i],\n shadow: null\n });\n }\n }\n /* (pushed before children → processed after them, matching the old\n \"template content last\" order) When the node is a <template>,\n descend into its content. */\n if (isElement) {\n const rootName = getNodeName ? getNodeName(node) : null;\n if (typeof rootName === 'string' && transformCaseFunc(rootName) === 'template') {\n const content = node.content;\n if (_isDocumentFragment(content)) {\n stack.push({\n node: content,\n shadow: null\n });\n }\n }\n }\n /* Shadow root (processed first): walk its subtree, then sanitise it.\n Realm-safe check (GHSA-hpcv-96wg-7vj8): nodeType-based detection\n rather than `instanceof DocumentFragment`, which is realm-bound and\n silently skipped foreign-realm shadow roots (e.g.\n iframe.contentDocument attachShadow). */\n if (isElement) {\n const sr = getShadowRoot(node);\n if (_isDocumentFragment(sr)) {\n /* Push the deferred sanitise first so it pops after the shadow\n walk we push next, i.e. nested shadow roots are discovered\n before this one is sanitised. */\n stack.push({\n node: null,\n shadow: sr\n }, {\n node: sr,\n shadow: null\n });\n }\n }\n }\n };\n // eslint-disable-next-line complexity\n DOMPurify.sanitize = function (dirty) {\n let cfg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n let body = null;\n let importedNode = null;\n let currentNode = null;\n let returnNode = null;\n /* Make sure we have a string to sanitize.\n DO NOT return early, as this will return the wrong type if\n the user has requested a DOM object rather than a string */\n IS_EMPTY_INPUT = !dirty;\n if (IS_EMPTY_INPUT) {\n dirty = '<!-->';\n }\n /* Stringify, in case dirty is an object */\n if (typeof dirty !== 'string' && !_isNode(dirty)) {\n dirty = stringifyValue(dirty);\n if (typeof dirty !== 'string') {\n throw typeErrorCreate('dirty is not a string, aborting');\n }\n }\n /* Return dirty HTML if DOMPurify cannot run */\n if (!DOMPurify.isSupported) {\n return dirty;\n }\n /* Assign config vars */\n if (SET_CONFIG) {\n /* Persistent setConfig() path: _parseConfig is skipped, so the sets are\n * not re-derived per call. Restore them from the pristine bindings\n * captured at setConfig() time so a previous call's hook clone (mutated\n * below) does not carry over. */\n ALLOWED_TAGS = SET_CONFIG_ALLOWED_TAGS;\n ALLOWED_ATTR = SET_CONFIG_ALLOWED_ATTR;\n } else {\n _parseConfig(cfg);\n }\n /* Clone the hook-mutable allowlists before the walk whenever an\n * uponSanitize* hook is registered. The hook event exposes ALLOWED_TAGS\n * and ALLOWED_ATTR by reference (as allowedTags / allowedAttributes), so\n * a hook that widens them would otherwise mutate the shared set\n * permanently: across later calls and across every element. Cloning per\n * walk keeps documented in-call widening working while scoping it to the\n * call. A single guard for both config paths - the per-call path rebinds\n * the sets in _parseConfig each call, the persistent path restores them\n * from the captured bindings just above - so the two cannot diverge. */\n if (hooks.uponSanitizeElement.length > 0 || hooks.uponSanitizeAttribute.length > 0) {\n ALLOWED_TAGS = clone(ALLOWED_TAGS);\n }\n if (hooks.uponSanitizeAttribute.length > 0) {\n ALLOWED_ATTR = clone(ALLOWED_ATTR);\n }\n /* Clean up removed elements */\n DOMPurify.removed = [];\n /* Resolve IN_PLACE for this call without mutating persistent config.\n Writing the IN_PLACE closure variable here leaks under setConfig(),\n where _parseConfig is skipped on later calls: a single string call would\n disable in-place mode for every subsequent node call, returning a\n sanitized copy while leaving the caller's node — which in-place callers\n keep using and whose return value they ignore — unsanitized. REPORT-2. */\n const inPlace = IN_PLACE && typeof dirty !== 'string' && _isNode(dirty);\n if (inPlace) {\n /* Do some early pre-sanitization to avoid unsafe root nodes.\n Read nodeName through the cached prototype getter — a clobbering\n child named \"nodeName\" on the form root would otherwise shadow\n the property and let this check skip the root-allowlist\n validation entirely. */\n const nn = getNodeName ? getNodeName(dirty) : dirty.nodeName;\n if (typeof nn === 'string') {\n const tagName = transformCaseFunc(nn);\n if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {\n throw typeErrorCreate('root node is forbidden and cannot be sanitized in-place');\n }\n }\n /* Pre-flight the root through _isClobbered. The iterator-driven\n removal path can not detach a parent-less root: _forceRemove\n falls through to Element.prototype.remove(), which per spec\n is a no-op on a node with no parent. A clobbered root would\n then survive the main loop with its attributes uninspected,\n because _sanitizeAttributes early-returns on _isClobbered. The\n result would be an attacker-controlled form, complete with any\n event-handler attributes the caller passed in, handed back to\n the application unsanitized. Refuse to sanitize such a root\n the same way we refuse a forbidden tag. GHSA-r47g-fvhr-h676. */\n if (_isClobbered(dirty)) {\n throw typeErrorCreate('root node is clobbered and cannot be sanitized in-place');\n }\n /* Sanitize attached shadow roots before the main iterator runs.\n The iterator does not descend into shadow trees. Same fail-closed\n barrier as the main walk (campaign-3 F2): a custom-element reaction\n inside a shadow root could abort this pre-pass before the walk runs,\n which would otherwise leave the entire live tree unsanitized. */\n try {\n _sanitizeAttachedShadowRoots(dirty);\n } catch (error) {\n _neutralizeRoot(dirty);\n throw error;\n }\n } else if (_isNode(dirty)) {\n /* If dirty is a DOM element, append to an empty document to avoid\n elements being stripped by the parser */\n body = _initDocument('<!---->');\n importedNode = body.ownerDocument.importNode(dirty, true);\n if (importedNode.nodeType === NODE_TYPE.element && importedNode.nodeName === 'BODY') {\n /* Node is already a body, use as is */\n body = importedNode;\n } else if (importedNode.nodeName === 'HTML') {\n body = importedNode;\n } else {\n // eslint-disable-next-line unicorn/prefer-dom-node-append\n body.appendChild(importedNode);\n }\n /* Clonable shadow roots are deep-cloned by importNode(); sanitize\n them before the main iterator runs, since the iterator does not\n descend into shadow trees. The walk routes every read through a\n cached prototype getter so clobbering descendants on a form root\n cannot hide a shadow host from this pass. */\n _sanitizeAttachedShadowRoots(importedNode);\n } else {\n /* Exit directly if we have nothing to do */\n if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT &&\n // eslint-disable-next-line unicorn/prefer-includes\n dirty.indexOf('<') === -1) {\n return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? _createTrustedHTML(dirty) : dirty;\n }\n /* Initialize the document to work on */\n body = _initDocument(dirty);\n /* Check we have a DOM node from the data */\n if (!body) {\n return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : '';\n }\n }\n /* Remove first element node (ours) if FORCE_BODY is set */\n if (body && FORCE_BODY) {\n _forceRemove(body.firstChild);\n }\n /* Get node iterator */\n const nodeIterator = _createNodeIterator(inPlace ? dirty : body);\n /* Now start iterating over the created document.\n The walk runs inside an exception barrier (campaign-3 F2): a re-entrant\n engine/custom-element mutation can detach a node mid-walk so\n `_forceRemove`'s parentless guard throws, aborting the loop. Without the\n barrier the caller's in-place tree would be left half-sanitized with the\n unvisited tail still armed. On any throw we fail closed — strip the\n in-place root bare — then rethrow so the existing throw contract is\n preserved. (String/DOM-copy paths never return the partial body, so the\n propagating throw is already fail-closed there.) */\n try {\n while (currentNode = nodeIterator.nextNode()) {\n /* Sanitize tags and elements */\n _sanitizeElements(currentNode);\n /* Check attributes next */\n _sanitizeAttributes(currentNode);\n /* Shadow DOM detected, sanitize it.\n Realm-safe check (GHSA-hpcv-96wg-7vj8): nodeType-based detection\n instead of instanceof, so foreign-realm <template>.content is\n walked correctly. */\n if (_isDocumentFragment(currentNode.content)) {\n _sanitizeShadowDOM2(currentNode.content);\n }\n }\n } catch (error) {\n if (inPlace) {\n _neutralizeRoot(dirty);\n }\n throw error;\n }\n /* If we sanitized `dirty` in-place, return it. */\n if (inPlace) {\n /* Fail-closed completion of the audit-5 F1 fix: every node removed from\n the caller's live tree is detached but may still hold a queued\n resource-event handler that fires in page scope after we return. The\n move-hoist covers only disallowed-tag KEEP_CONTENT removals; strip the\n non-allow-listed attributes off every other removed subtree (clobber,\n mXSS, namespace, comments, KEEP_CONTENT:false, …) so those handlers are\n cancelled before any event can fire. Runs synchronously, pre-return. */\n arrayForEach(DOMPurify.removed, entry => {\n if (entry.element) {\n _neutralizeSubtree(entry.element);\n }\n });\n if (SAFE_FOR_TEMPLATES) {\n _scrubTemplateExpressions2(dirty);\n }\n return dirty;\n }\n /* Return sanitized string or DOM */\n if (RETURN_DOM) {\n if (SAFE_FOR_TEMPLATES) {\n _scrubTemplateExpressions2(body);\n }\n if (RETURN_DOM_FRAGMENT) {\n returnNode = createDocumentFragment.call(body.ownerDocument);\n while (body.firstChild) {\n // eslint-disable-next-line unicorn/prefer-dom-node-append\n returnNode.appendChild(body.firstChild);\n }\n } else {\n returnNode = body;\n }\n if (ALLOWED_ATTR.shadowroot || ALLOWED_ATTR.shadowrootmode) {\n /*\n AdoptNode() is not used because internal state is not reset\n (e.g. the past names map of a HTMLFormElement), this is safe\n in theory but we would rather not risk another attack vector.\n The state that is cloned by importNode() is explicitly defined\n by the specs.\n */\n returnNode = importNode.call(originalDocument, returnNode, true);\n }\n return returnNode;\n }\n let serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;\n /* Serialize doctype if allowed */\n if (WHOLE_DOCUMENT && ALLOWED_TAGS['!doctype'] && body.ownerDocument && body.ownerDocument.doctype && body.ownerDocument.doctype.name && regExpTest(DOCTYPE_NAME, body.ownerDocument.doctype.name)) {\n serializedHTML = '<!DOCTYPE ' + body.ownerDocument.doctype.name + '>\\n' + serializedHTML;\n }\n /* Sanitize final string template-safe */\n if (SAFE_FOR_TEMPLATES) {\n serializedHTML = _stripTemplateExpressions(serializedHTML);\n }\n return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? _createTrustedHTML(serializedHTML) : serializedHTML;\n };\n DOMPurify.setConfig = function () {\n let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n _parseConfig(cfg);\n SET_CONFIG = true;\n SET_CONFIG_ALLOWED_TAGS = ALLOWED_TAGS;\n SET_CONFIG_ALLOWED_ATTR = ALLOWED_ATTR;\n };\n DOMPurify.clearConfig = function () {\n CONFIG = null;\n SET_CONFIG = false;\n SET_CONFIG_ALLOWED_TAGS = null;\n SET_CONFIG_ALLOWED_ATTR = null;\n // Drop any caller-supplied Trusted Types policy so it cannot poison later\n // `RETURN_TRUSTED_TYPE` output. The internal default policy (cached, and\n // never recreated — Trusted Types throws on duplicate names) is restored by\n // the next `_parseConfig`. See GHSA-vxr8-fq34-vvx9.\n trustedTypesPolicy = defaultTrustedTypesPolicy;\n emptyHTML = '';\n };\n DOMPurify.isValidAttribute = function (tag, attr, value) {\n /* Initialize shared config vars if necessary. */\n if (!CONFIG) {\n _parseConfig({});\n }\n const lcTag = transformCaseFunc(tag);\n const lcName = transformCaseFunc(attr);\n return _isValidAttribute(lcTag, lcName, value);\n };\n DOMPurify.addHook = function (entryPoint, hookFunction) {\n if (typeof hookFunction !== 'function') {\n return;\n }\n /* Reject unknown entry points. Without this, a non-hook key (e.g.\n * '__proto__') indexes off the prototype chain rather than a real\n * hook array, and arrayPush then writes to Object.prototype. Guard\n * with an own-property check against the known hook names. */\n if (!objectHasOwnProperty(hooks, entryPoint)) {\n return;\n }\n arrayPush(hooks[entryPoint], hookFunction);\n };\n DOMPurify.removeHook = function (entryPoint, hookFunction) {\n if (!objectHasOwnProperty(hooks, entryPoint)) {\n return undefined;\n }\n if (hookFunction !== undefined) {\n const index = arrayLastIndexOf(hooks[entryPoint], hookFunction);\n return index === -1 ? undefined : arraySplice(hooks[entryPoint], index, 1)[0];\n }\n return arrayPop(hooks[entryPoint]);\n };\n DOMPurify.removeHooks = function (entryPoint) {\n if (!objectHasOwnProperty(hooks, entryPoint)) {\n return;\n }\n hooks[entryPoint] = [];\n };\n DOMPurify.removeAllHooks = function () {\n hooks = _createHooksMap();\n };\n return DOMPurify;\n}\nvar purify = createDOMPurify();\n\nexport { purify as default };\n//# sourceMappingURL=purify.es.mjs.map\n","// Markdown rendering for assistant chat messages.\n//\n// Uses `marked` for GFM parsing and DOMPurify for sanitization. We deliberately\n// keep this dependency-light: no syntax-highlighting engine is bundled (code\n// blocks render as plain monospace, styled via the `prose` classes). The agent\n// output is broadly trusted, but DOMPurify still runs as defense-in-depth so a\n// stray `<script>`/`<img onerror>` in tool output or a pasted snippet cannot\n// execute.\n\nimport {marked} from 'marked';\nimport DOMPurify from 'dompurify';\n\nmarked.setOptions({\n\tgfm: true,\n\tbreaks: true,\n});\n\n// Max characters shown in the collapsed summary of a fenced code block before\n// we truncate with an ellipsis. Keeps long pasted blobs from cluttering the log.\nconst CODE_SUMMARY_MAX = 80;\n\nfunction escapeHtml(s: string): string {\n\treturn s\n\t\t.replace(/&/g, '&amp;')\n\t\t.replace(/</g, '&lt;')\n\t\t.replace(/>/g, '&gt;')\n\t\t.replace(/\"/g, '&quot;');\n}\n\n// Render fenced code blocks as collapsible <details>. The summary shows the\n// language (if any) plus the first non-empty line, truncated, so a long block\n// collapses to a single unobtrusive line. Single-line blocks stay open (nothing\n// gained by collapsing them). DOMPurify below is configured to allow the\n// details/summary tags this produces.\nconst codeRenderer = {\n\tcode(this: unknown, token: {text: string; lang?: string}): string {\n\t\tconst {text, lang} = token;\n\t\tconst langLabel = (lang ?? '').trim().split(/\\s+/)[0] ?? '';\n\t\tconst lines = text.split('\\n');\n\t\tconst nonEmpty = lines.filter((l) => l.trim() !== '');\n\t\tconst multiline = nonEmpty.length > 1;\n\t\tconst codeHtml = `<pre><code>${escapeHtml(text)}</code></pre>`;\n\t\tif (!multiline) {\n\t\t\treturn codeHtml;\n\t\t}\n\t\tconst firstLine = nonEmpty[0] ?? '';\n\t\tlet summaryText = firstLine;\n\t\tif (summaryText.length > CODE_SUMMARY_MAX) {\n\t\t\tsummaryText = summaryText.slice(0, CODE_SUMMARY_MAX) + '…';\n\t\t} else if (nonEmpty.length > 1) {\n\t\t\tsummaryText += ' …';\n\t\t}\n\t\tconst summaryLabel = langLabel\n\t\t\t? `<span class=\"code-lang\">${escapeHtml(langLabel)}</span> ${escapeHtml(summaryText)}`\n\t\t\t: escapeHtml(summaryText);\n\t\treturn `<details class=\"code-collapsible\"><summary>${summaryLabel}</summary>${codeHtml}</details>`;\n\t},\n};\nmarked.use({renderer: codeRenderer});\n\n// Open links in a new tab and harden them against reverse-tabnabbing. The hook\n// runs after sanitization so the attributes survive.\nlet hookRegistered = false;\nfunction ensureHook() {\n\tif (hookRegistered || typeof window === 'undefined') return;\n\thookRegistered = true;\n\tDOMPurify.addHook('afterSanitizeAttributes', (node) => {\n\t\tif (node.tagName === 'A') {\n\t\t\tnode.setAttribute('target', '_blank');\n\t\t\tnode.setAttribute('rel', 'noopener noreferrer');\n\t\t}\n\t});\n}\n\n/**\n * Render a markdown string to sanitized HTML.\n *\n * Server-side (no DOM available) it returns the raw text escaped as-is, since\n * DOMPurify needs a window; the client re-renders on hydration anyway.\n */\nexport function renderMarkdown(raw: string): string {\n\tif (!raw) return '';\n\tconst html = marked.parse(raw, {async: false}) as string;\n\tif (typeof window === 'undefined') {\n\t\t// No DOM to sanitize against during SSR. Return empty; the component shows\n\t\t// a plain-text fallback until the client hydrates and re-renders.\n\t\treturn '';\n\t}\n\tensureHook();\n\treturn DOMPurify.sanitize(html, {\n\t\tADD_ATTR: ['target', 'rel'],\n\t\tADD_TAGS: ['details', 'summary'],\n\t});\n}\n\n// GFM-ish autolink matcher for the link-only path. Matches http(s):// and www.\n// URLs. Trailing punctuation that is usually sentence punctuation (not part of\n// the URL) is trimmed off the match.\nconst URL_RE = /\\b(https?:\\/\\/[^\\s<]+|www\\.[^\\s<]+)/gi;\n\n/**\n * Linkify plain text WITHOUT running full markdown. Used for user messages,\n * where we want bare URLs to be clickable but must not reinterpret characters\n * the user typed literally (asterisks, backticks, hashes). Everything is\n * HTML-escaped first, then only URL matches are wrapped in anchors, then the\n * whole thing is sanitized as defense-in-depth.\n *\n * Returns escaped-but-unlinked text server-side (no DOM for DOMPurify); the\n * client re-renders on hydration.\n */\nexport function linkifyText(raw: string): string {\n\tif (!raw) return '';\n\tif (typeof window === 'undefined') {\n\t\treturn '';\n\t}\n\tlet out = '';\n\tlet lastIndex = 0;\n\tfor (const match of raw.matchAll(URL_RE)) {\n\t\tconst start = match.index ?? 0;\n\t\tout += escapeHtml(raw.slice(lastIndex, start));\n\t\tlet urlText = match[0];\n\t\t// Trim trailing sentence punctuation that is unlikely to be part of the URL.\n\t\tlet trailing = '';\n\t\tconst trailMatch = urlText.match(/[.,;:!?)\\]}'\"]+$/);\n\t\tif (trailMatch) {\n\t\t\ttrailing = trailMatch[0];\n\t\t\turlText = urlText.slice(0, urlText.length - trailing.length);\n\t\t}\n\t\tconst href = urlText.startsWith('www.') ? `https://${urlText}` : urlText;\n\t\tout += `<a href=\"${escapeHtml(href)}\">${escapeHtml(urlText)}</a>`;\n\t\tout += escapeHtml(trailing);\n\t\tlastIndex = start + match[0].length;\n\t}\n\tout += escapeHtml(raw.slice(lastIndex));\n\tensureHook();\n\treturn DOMPurify.sanitize(out, {\n\t\tADD_ATTR: ['target', 'rel'],\n\t});\n}\n","// Pure (non-reactive) helpers for ChatMessageList.svelte.\n//\n// Everything here is free of Svelte runes and DOM/lifecycle state, so it can be\n// unit-tested in isolation and kept out of the .svelte file. Reactive glue\n// (effects, $derived, $state) stays in the component; this module holds only the\n// logic. Per the project convention: NO .svelte.ts/.svelte.js modules — this is a\n// plain .ts module, and rendering caches are module-level Maps (shared across the\n// single chat list, which is the intended memoization scope).\n\nimport {renderMarkdown, linkifyText} from '$lib/core/utils/markdown';\nimport {extractDownloadablePath} from '$lib/core/media-kind';\nimport {extractSayText} from '$lib/core/speak';\nimport {parseSkillInvocation, type ChatMessage} from '$lib/wherever';\n\n// The piState slice that drives message filtering. Kept structural (no import of\n// the store) so this stays a pure function of its arguments.\nexport interface FilterOpts {\n\thideThinking: boolean;\n\thideTools: boolean;\n}\n\n// --- Rendering (memoized) -------------------------------------------------\n\n// Memoize rendered markdown per (message id + content length) so a finalized\n// assistant message is parsed once and its DOM stays stable afterwards. A\n// stable node is what lets a text selection survive (re-parsing on every\n// keystroke would collapse the selection, the bug this fixes). Streaming\n// messages are NOT rendered as markdown -- they show plain text until final.\nconst markdownCache = new Map<string, string>();\nexport function renderAssistant(id: string, content: string): string {\n\tconst key = `${id}:${content.length}`;\n\tlet cached = markdownCache.get(key);\n\tif (cached === undefined) {\n\t\tcached = renderMarkdown(content);\n\t\tmarkdownCache.set(key, cached);\n\t}\n\treturn cached;\n}\n\n// Link-only rendering for user messages: bare URLs become clickable, but the\n// user's literal characters (asterisks, backticks) are NOT reinterpreted as\n// markdown. Memoized on the cleaned content so the DOM stays stable.\nconst linkifyCache = new Map<string, string>();\nexport function renderUser(content: string): string {\n\tlet cached = linkifyCache.get(content);\n\tif (cached === undefined) {\n\t\tcached = linkifyText(content);\n\t\tlinkifyCache.set(content, cached);\n\t}\n\treturn cached;\n}\n\n// --- Formatting -----------------------------------------------------------\n\n// Context-window usage indicator, shown next to the Hide Thinking/Tools\n// toggles. Humanize like the pi CLI: 1_000_000 -> \"1.0M\", 128_000 -> \"128K\".\nexport function formatTokens(n: number): string {\n\tif (n >= 1_000_000) {\n\t\tconst m = n / 1_000_000;\n\t\treturn (m >= 10 ? Math.round(m).toString() : m.toFixed(1)) + 'M';\n\t}\n\tif (n >= 1_000) return Math.round(n / 1_000) + 'K';\n\treturn String(n);\n}\n\nexport function formatTime(timestamp: number) {\n\treturn new Date(timestamp).toLocaleTimeString([], {\n\t\thour: '2-digit',\n\t\tminute: '2-digit',\n\t});\n}\n\n// `/skill:<name> <args>` invocations are recovered from either their raw or\n// their expanded (server-stored) form via the shared parseSkillInvocation()\n// (see @wherever-dev/client), so the composer echo and history reloads render\n// the same compact skill chip.\nexport function parseUserMessage(content: string) {\n\tif (!content) return {cleanContent: '', attachments: [], skill: null};\n\tconst skill = parseSkillInvocation(content);\n\tif (skill) return {cleanContent: '', attachments: [], skill};\n\tconst lines = content.split('\\n');\n\tconst fileRegex = /^\\[Uploaded file: (.+)\\]$/;\n\tconst cleanLines: string[] = [];\n\tconst attachments: string[] = [];\n\n\tfor (const line of lines) {\n\t\tconst match = line.match(fileRegex);\n\t\tif (match) {\n\t\t\tattachments.push(match[1]);\n\t\t} else {\n\t\t\tcleanLines.push(line);\n\t\t}\n\t}\n\n\tlet cleanContent = cleanLines.join('\\n').trim();\n\tif (cleanContent === 'I have uploaded the following file(s) for you:') {\n\t\tcleanContent = '';\n\t}\n\treturn {cleanContent, attachments, skill: null};\n}\n\n// --- Tool message parsing -------------------------------------------------\n\nfunction parseArgsObject(\n\targsStr: string | undefined,\n): Record<string, any> | null {\n\tif (!argsStr) return null;\n\tconst trimmed = argsStr.trim();\n\tif (!trimmed) return null;\n\n\t// If it's JSON\n\tif (trimmed.startsWith('{')) {\n\t\ttry {\n\t\t\treturn JSON.parse(trimmed);\n\t\t} catch (e) {}\n\t}\n\n\t// If it's k1=\"v1\" k2=\"v2\" format, parse it\n\tconst obj: Record<string, any> = {};\n\tconst regex =\n\t\t/([a-zA-Z0-9_-]+)\\s*=\\s*(?:\"([^\"\\\\]*(?:\\\\.[^\"\\\\]*)*)\"|'([^'\\\\]*(?:\\\\.[^'\\\\]*)*)'|(\\S+))/g;\n\tlet match;\n\twhile ((match = regex.exec(trimmed)) !== null) {\n\t\tconst key = match[1];\n\t\tconst val =\n\t\t\tmatch[2] !== undefined\n\t\t\t\t? match[2]\n\t\t\t\t: match[3] !== undefined\n\t\t\t\t\t? match[3]\n\t\t\t\t\t: match[4];\n\t\tobj[key] = val;\n\t}\n\n\tif (Object.keys(obj).length > 0) {\n\t\treturn obj;\n\t}\n\n\treturn null;\n}\n\nfunction getSmartTitleArgs(\n\ttoolName: string,\n\targsObj: Record<string, any> | null,\n\trawArgsStr: string,\n): string {\n\tif (!argsObj) {\n\t\treturn rawArgsStr ? rawArgsStr.trim() : '';\n\t}\n\n\tconst name = toolName.toLowerCase();\n\n\t// 1. read, write, edit, ls: show the path directly\n\tif (['read', 'write', 'edit', 'ls'].includes(name)) {\n\t\tconst pathVal = argsObj.path || argsObj.filepath || argsObj.file;\n\t\tif (pathVal) {\n\t\t\treturn String(pathVal);\n\t\t}\n\t}\n\n\t// 2. bash: show the first few characters of the command\n\tif (name === 'bash') {\n\t\tconst cmd = argsObj.command || argsObj.cmd;\n\t\tif (cmd) {\n\t\t\tconst cleanCmd = String(cmd).replace(/\\s+/g, ' ').trim();\n\t\t\treturn cleanCmd.length > 50 ? cleanCmd.slice(0, 47) + '...' : cleanCmd;\n\t\t}\n\t}\n\n\t// 3. grep: show pattern / pattern in path\n\tif (name === 'grep') {\n\t\tconst pattern = argsObj.pattern;\n\t\tconst pathVal = argsObj.path;\n\t\tif (pattern) {\n\t\t\treturn pathVal ? `\"${pattern}\" in ${pathVal}` : `\"${pattern}\"`;\n\t\t}\n\t}\n\n\t// 4. find: show pattern or path\n\tif (name === 'find') {\n\t\tconst pattern = argsObj.pattern || argsObj.path;\n\t\tif (pattern) {\n\t\t\treturn String(pattern);\n\t\t}\n\t}\n\n\t// Custom tools check for common key names\n\tconst commonPath =\n\t\targsObj.path ||\n\t\targsObj.filepath ||\n\t\targsObj.file ||\n\t\targsObj.name ||\n\t\targsObj.query;\n\tif (commonPath) {\n\t\treturn String(commonPath);\n\t}\n\n\t// Default fallback formatting for title\n\treturn Object.entries(argsObj)\n\t\t.filter(([k, v]) => v !== undefined && v !== '')\n\t\t.map(([k, v]) => `${k}=${typeof v === 'object' ? JSON.stringify(v) : v}`)\n\t\t.join(' ');\n}\n\nfunction getFullArgsFormatted(\n\targsObj: Record<string, any> | null,\n\trawArgsStr: string,\n): string {\n\tif (argsObj) {\n\t\treturn JSON.stringify(argsObj, null, 2);\n\t}\n\treturn rawArgsStr ? rawArgsStr.trim() : '';\n}\n\n// The tools that render as a FIRST-CLASS card (their own affordance, exempt\n// from the \"hide tools\" collapse), not as a generic tool row:\n// - attach_file: an attachment the agent explicitly offered for download.\n// - say: the agent's SHORT spoken-form reply, shown as a distinct \"spoken:\"\n// card so its divergence from the full written reply is spottable. The\n// full reply always stays in the transcript; the say card is additive.\nexport function isFirstClassTool(toolName: string | undefined): boolean {\n\treturn toolName === 'attach_file' || toolName === 'say';\n}\n\n// True when `msg` is a bash tool call produced by a user `!command` /\n// `!!command` (a \"force command\"), as opposed to one the agent issued. The\n// server marks these explicitly (`forceCommand`) both live (tool_start) and in\n// reloaded history (the bashExecution -> tool_call mapping), so this is an\n// unambiguous per-message flag: no structural inference, and it works\n// correctly for back-to-back `!command`s and after a reload.\nexport function isAssociatedWithForceCommand(msg: ChatMessage): boolean {\n\treturn msg.role === 'tool' && msg.forceCommand === true;\n}\n\nexport function shouldAutoExpand(\n\tmsg: ChatMessage,\n\tlist: ChatMessage[],\n): boolean {\n\treturn isAssociatedWithForceCommand(msg);\n}\n\nexport function parseToolMessage(msg: ChatMessage) {\n\tlet toolName = msg.toolName || 'tool';\n\tlet toolArgs = msg.toolArgs !== undefined ? msg.toolArgs : '';\n\tlet toolOutput = msg.toolOutput !== undefined ? msg.toolOutput : '';\n\tlet isError = !!msg.isError;\n\n\t// If we don't have toolArgs or toolOutput, or if they are empty but msg.content is populated,\n\t// let's parse from content to be absolutely sure we get any args embedded in the raw text.\n\tif (!toolArgs && !toolOutput && msg.content) {\n\t\tlet content = msg.content || '';\n\n\t\tif (content.startsWith('Error: ')) {\n\t\t\tisError = true;\n\t\t\tcontent = content.slice(7);\n\t\t} else if (content.startsWith('Tool error: ')) {\n\t\t\tisError = true;\n\t\t\tcontent = content.slice(12);\n\t\t}\n\n\t\tconst firstLineBreak = content.indexOf('\\n');\n\t\tconst headerLine =\n\t\t\tfirstLineBreak !== -1 ? content.slice(0, firstLineBreak) : content;\n\t\ttoolOutput = firstLineBreak !== -1 ? content.slice(firstLineBreak + 1) : '';\n\n\t\tlet header = headerLine.trim();\n\t\tif (header.startsWith('$ ')) {\n\t\t\theader = header.slice(2);\n\t\t}\n\n\t\tconst firstSpace = header.indexOf(' ');\n\t\ttoolName =\n\t\t\tmsg.toolName ||\n\t\t\t(firstSpace !== -1 ? header.slice(0, firstSpace) : header) ||\n\t\t\t'tool';\n\t\ttoolArgs = firstSpace !== -1 ? header.slice(firstSpace + 1) : '';\n\t}\n\n\tconst argsObj = parseArgsObject(toolArgs);\n\tconst smartTitleArgs = getSmartTitleArgs(toolName, argsObj, toolArgs);\n\tconst fullArgs = getFullArgsFormatted(argsObj, toolArgs);\n\n\treturn {\n\t\ttoolName,\n\t\tsmartTitleArgs,\n\t\tfullArgs,\n\t\ttoolOutput,\n\t\tisError,\n\t\t// A tool call that ended with no result (e.g. killed by a CLI takeover).\n\t\t// Outcome unknown: render a neutral \"interrupted\" state, not success.\n\t\tinterrupted: !!msg.interrupted,\n\t\t// The path of a single file this tool operated on, when it is a\n\t\t// file-oriented tool. Drives the per-tool download button + inline\n\t\t// preview. Narrowed to two tools (see extractDownloadablePath):\n\t\t// - `attach_file`: the agent EXPLICITLY offered this file for download\n\t\t// (the intended, agent-driven path, e.g. \"give me the gpx\").\n\t\t// - `read`: the card already carries the exact path the agent read,\n\t\t// so we offer it opportunistically too.\n\t\t// `write`/`edit` (a download of a just-written file is noise) and\n\t\t// `ls`/`grep`/`find` (directory/search scope) are excluded. Suppressed\n\t\t// on errors.\n\t\tdownloadPath: extractDownloadablePath(toolName, argsObj, isError),\n\t\t// The short spoken-form text from a `say` tool call's args ({ text }).\n\t\t// Drives the first-class \"spoken:\" card AND the browser TTS off the SAME\n\t\t// extracted text (see core/speak.ts), so what is shown and what is\n\t\t// spoken cannot diverge. Null for non-say tools or a blank/missing text.\n\t\tsayText: toolName === 'say' ? extractSayText(argsObj) : null,\n\t};\n}\n\n// Format a tool call's run duration the way the pi CLI does: \"N.Ns\" (one\n// decimal). While running, count from startedAt to the live `now`; once ended,\n// freeze at endedAt. Returns null when we have no start time (e.g. a tool\n// reconstructed from loaded history, which carries no timing).\nexport function toolDuration(msg: ChatMessage, now: number): string | null {\n\tif (msg.startedAt === undefined) return null;\n\tconst end = msg.endedAt ?? (msg.isStreaming ? now : undefined);\n\tif (end === undefined) return null;\n\tconst ms = Math.max(0, end - msg.startedAt);\n\treturn `${(ms / 1000).toFixed(1)}s`;\n}\n\n// --- Message-list filtering ----------------------------------------------\n\n// The pure core of the component's `msgList` $derived: filter the raw message\n// stream according to the hide-thinking/hide-tools toggles, and append a\n// fallback loader bubble when the agent is streaming but no streaming node is\n// present yet. `streaming` is whether the session is currently streaming a turn.\nexport function filterMessages(\n\tmessages: ChatMessage[],\n\topts: FilterOpts,\n\tstreaming: boolean,\n): ChatMessage[] {\n\tconst filtered = messages.filter((msg) => {\n\t\tif (msg.role === 'thinking') {\n\t\t\tif (opts.hideThinking) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\tif (msg.role === 'tool') {\n\t\t\t// attach_file (an attachment) and say (a first-class \"spoken:\" card)\n\t\t\t// render as first-class affordances, not tool noise, so they are\n\t\t\t// never suppressed by \"hide tools\".\n\t\t\tif (opts.hideTools && !isFirstClassTool(msg.toolName)) {\n\t\t\t\treturn isAssociatedWithForceCommand(msg) || !!msg.isStreaming;\n\t\t\t}\n\t\t}\n\t\treturn (\n\t\t\t(msg.role !== 'assistant' && msg.role !== 'thinking') ||\n\t\t\tmsg.isStreaming ||\n\t\t\tmsg.content.trim() !== ''\n\t\t);\n\t});\n\n\tconst activeStreamExists = filtered.some((msg) => msg.isStreaming);\n\tif (streaming && !activeStreamExists) {\n\t\tconst isThinking = messages.some(\n\t\t\t(msg) => msg.role === 'thinking' && msg.isStreaming,\n\t\t);\n\t\tfiltered.push({\n\t\t\tid: 'fallback-loader-message-id',\n\t\t\trole: 'thinking',\n\t\t\tcontent: isThinking ? 'FALLBACK_THINKING_LOADER' : 'FALLBACK_LOADER',\n\t\t\ttimestamp: Date.now(),\n\t\t\tisStreaming: true,\n\t\t});\n\t}\n\n\treturn filtered;\n}\n\n// --- Speech helpers -------------------------------------------------------\n\nexport function speechLocale(): string {\n\tif (typeof localStorage === 'undefined') return '';\n\treturn localStorage.getItem('wherever-speech-locale') || '';\n}\n\nexport function lastAssistantReply(\n\tlist: ChatMessage[],\n): {id: string; text: string} | null {\n\tfor (let i = list.length - 1; i >= 0; i--) {\n\t\tconst msg = list[i];\n\t\tif (msg.role === 'user') return null; // nothing said since the human spoke\n\t\tif (msg.role !== 'assistant' || msg.isStreaming) continue;\n\t\treturn {\n\t\t\tid: msg.id,\n\t\t\ttext: typeof msg.content === 'string' ? msg.content : '',\n\t\t};\n\t}\n\treturn null;\n}\n\n// --- Scroll math ----------------------------------------------------------\n\nexport function isScrolledToBottom(el: HTMLDivElement): boolean {\n\tconst threshold = 20;\n\treturn el.scrollHeight - el.scrollTop - el.clientHeight <= threshold;\n}\n","<script lang=\"ts\">\n\timport {\n\t\tmessages,\n\t\tisStreaming,\n\t\tabort,\n\t\tactiveSessionInfo,\n\t\tcreateSession,\n\t\tpiState,\n\t\tupdateConfig,\n\t\tloadMoreHistory,\n\t\thasMoreHistory,\n\t\tisLoadingMoreHistory,\n\t\tisLoadingSession,\n\t\tisResyncing,\n\t\tsessionError,\n\t\tresendMessage,\n\t\tdiscardMessage,\n\t\tcancelSteer,\n\t\tpendingSteering,\n\t\tbeepEnabled,\n\t\tbeepSessionOverride,\n\t\tsetBeepSessionOverride,\n\t\tconversationMode,\n\t\tconversationModeSessionOverride,\n\t\tsetConversationModeBundle,\n\t\tspeakReplies,\n\t\tcollapseLongReplies,\n\t\tgetConversationKnobs,\n\t\tisReadOnly,\n\t\tdownloadFileUrl,\n\t\ttoolImageSrc,\n\t\tforkSession,\n\t} from '$lib/wherever';\n\timport {mediaKind} from '$lib/core/media-kind';\n\timport {\n\t\tarmTtsGestureUnlock,\n\t\tspeakUtterance,\n\t\tunlockTts,\n\t} from '$lib/core/speak';\n\timport {\n\t\tshouldSpeakFallback,\n\t\tspokenFallbackText,\n\t} from '$lib/core/speak-fallback';\n\timport {shouldCollapseReply, isLongReply} from '$lib/core/collapse-reply';\n\timport {isKnobActive} from '$lib/core/conversation-mode';\n\timport {\n\t\tavailableModels,\n\t\tgitInitDefaultStore,\n\t\tcheckPath,\n\t\tautocompletePath,\n\t\tcheckRemoteRepo,\n\t} from '$lib/session-store';\n\timport {onMount} from 'svelte';\n\timport {url} from '$lib/core/utils/web/path';\n\timport {\n\t\trenderAssistant,\n\t\trenderUser,\n\t\tformatTokens,\n\t\tformatTime,\n\t\tparseUserMessage,\n\t\tparseToolMessage,\n\t\ttoolDuration,\n\t\tisFirstClassTool,\n\t\tisAssociatedWithForceCommand,\n\t\tshouldAutoExpand,\n\t\tisScrolledToBottom,\n\t\tlastAssistantReply,\n\t\tspeechLocale,\n\t\tfilterMessages,\n\t} from './chat-message-helpers';\n\n\t// \"11.3% / 1.0M\". Percent omitted (\"–\") right after compaction when tokens are\n\t// momentarily unknown.\n\tlet contextLabel = $derived.by(() => {\n\t\tconst u = $piState.contextUsage;\n\t\tif (!u || !u.contextWindow) return null;\n\t\tconst window = formatTokens(u.contextWindow);\n\t\tif (u.percent == null) return `– / ${window}`;\n\t\treturn `${u.percent.toFixed(1)}% / ${window}`;\n\t});\n\n\tlet newFolderCwd = $state('');\n\tlet completions = $state<string[]>([]);\n\tlet inputFocused = $state(false);\n\tlet inputEl = $state<HTMLInputElement | null>(null);\n\tlet containerEl = $state<HTMLDivElement | null>(null);\n\tlet lastCheckedPath = '';\n\tlet newFolderModel = $state('');\n\tlet newFolderGitInit = $state(false);\n\tlet userManualGitInit = $state<boolean | null>(null);\n\tlet createRemoteRepo = $state(true);\n\tlet repoVisibility = $state<'private' | 'public'>('private');\n\tlet showGitInitConfirmModal = $state(false);\n\t// Clone-existing-remote flow. When creating a session in a non-existing folder\n\t// that matches a remote rule, we probe (at submit time) whether the remote\n\t// repo already exists. If it does, we ask the user whether to CLONE it (SSH)\n\t// instead of creating a fresh empty remote.\n\tlet showCloneConfirmModal = $state(false);\n\tlet checkingRemote = $state(false);\n\tlet cloneRemoteInfo = $state<{provider?: string; sshUrl?: string} | null>(\n\t\tnull,\n\t);\n\n\tfunction submitCreateSession(cloneRemote: boolean) {\n\t\tcreateSession(\n\t\t\tnewFolderCwd.trim(),\n\t\t\tnewFolderModel || undefined,\n\t\t\tcloneRemote ? false : newFolderGitInit,\n\t\t\tcloneRemote\n\t\t\t\t? false\n\t\t\t\t: pathStatus.matchingRule\n\t\t\t\t\t? createRemoteRepo\n\t\t\t\t\t: undefined,\n\t\t\tcloneRemote\n\t\t\t\t? undefined\n\t\t\t\t: pathStatus.matchingRule\n\t\t\t\t\t? repoVisibility\n\t\t\t\t\t: undefined,\n\t\t\tcloneRemote || undefined,\n\t\t);\n\t}\n\n\tlet appState = $derived($piState);\n\tlet modelsData = $derived($availableModels);\n\tlet defaultGitInit = $derived($gitInitDefaultStore);\n\n\t// Sync git init default\n\t$effect(() => {\n\t\tif (userManualGitInit === null) {\n\t\t\tnewFolderGitInit = defaultGitInit;\n\t\t}\n\t});\n\n\tlet pathStatus = $state<{\n\t\texists: boolean | null;\n\t\tisGit: boolean;\n\t\tresolvedPath: string;\n\t\tmatchingRule: {provider: string; visibility: string} | null;\n\t}>({\n\t\texists: null,\n\t\tisGit: false,\n\t\tresolvedPath: '',\n\t\tmatchingRule: null,\n\t});\n\n\tlet isRemoteRepoCreation = $derived(\n\t\tpathStatus.exists !== true && pathStatus.matchingRule && createRemoteRepo,\n\t);\n\n\tlet pathCheckTimeout: ReturnType<typeof setTimeout> | null = null;\n\n\tasync function triggerCheck(pathValue: string, immediate = false) {\n\t\tif (pathCheckTimeout) clearTimeout(pathCheckTimeout);\n\n\t\tif (pathValue === lastCheckedPath && !immediate) return;\n\t\tlastCheckedPath = pathValue;\n\n\t\tif (!pathValue.trim()) {\n\t\t\tpathStatus = {\n\t\t\t\texists: null,\n\t\t\t\tisGit: false,\n\t\t\t\tresolvedPath: '',\n\t\t\t\tmatchingRule: null,\n\t\t\t};\n\t\t\tconst fetchEmpty = async () => {\n\t\t\t\tconst list = await autocompletePath('');\n\t\t\t\tcompletions = list || [];\n\t\t\t};\n\t\t\tif (immediate) {\n\t\t\t\tawait fetchEmpty();\n\t\t\t} else {\n\t\t\t\tpathCheckTimeout = setTimeout(fetchEmpty, 300);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tconst fetchFn = async () => {\n\t\t\tconst [res, list] = await Promise.all([\n\t\t\t\tcheckPath(pathValue),\n\t\t\t\tautocompletePath(pathValue),\n\t\t\t]);\n\t\t\tcompletions = list || [];\n\t\t\tif (res) {\n\t\t\t\tpathStatus = {\n\t\t\t\t\texists: res.exists,\n\t\t\t\t\tisGit: res.isGit,\n\t\t\t\t\tresolvedPath: res.resolvedPath,\n\t\t\t\t\tmatchingRule: (res as any).matchingRule || null,\n\t\t\t\t};\n\t\t\t\tif (!res.exists) {\n\t\t\t\t\tnewFolderGitInit =\n\t\t\t\t\t\tuserManualGitInit !== null ? userManualGitInit : defaultGitInit;\n\t\t\t\t\tcreateRemoteRepo = true; // reset to true for non-existing folders\n\t\t\t\t\tif ((res as any).matchingRule) {\n\t\t\t\t\t\trepoVisibility = (res as any).matchingRule.visibility as\n\t\t\t\t\t\t\t| 'private'\n\t\t\t\t\t\t\t| 'public';\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tpathStatus = {\n\t\t\t\t\texists: null,\n\t\t\t\t\tisGit: false,\n\t\t\t\t\tresolvedPath: '',\n\t\t\t\t\tmatchingRule: null,\n\t\t\t\t};\n\t\t\t}\n\t\t};\n\n\t\tif (immediate) {\n\t\t\tawait fetchFn();\n\t\t} else {\n\t\t\tpathCheckTimeout = setTimeout(fetchFn, 300);\n\t\t}\n\t}\n\n\t$effect(() => {\n\t\tconst pathValue = newFolderCwd;\n\t\ttriggerCheck(pathValue, false);\n\t});\n\n\t// Select default model if any\n\t$effect(() => {\n\t\tif (modelsData.models.length > 0 && !newFolderModel) {\n\t\t\tconst defaultModel = modelsData.models.find((m) => m.isDefault);\n\t\t\tif (defaultModel) {\n\t\t\t\tnewFolderModel = `${defaultModel.provider}:${defaultModel.modelId}`;\n\t\t\t} else {\n\t\t\t\tnewFolderModel = `${modelsData.models[0].provider}:${modelsData.models[0].modelId}`;\n\t\t\t}\n\t\t}\n\t});\n\n\tasync function handleFormCreateSession() {\n\t\tif (!newFolderCwd.trim()) return;\n\t\tif (pathStatus.exists === true) {\n\t\t\tnewFolderGitInit = false; // toggled off by default in modal\n\t\t\tcreateRemoteRepo = false; // toggled off by default in modal\n\t\t\tif (pathStatus.matchingRule) {\n\t\t\t\trepoVisibility = pathStatus.matchingRule.visibility as\n\t\t\t\t\t| 'private'\n\t\t\t\t\t| 'public';\n\t\t\t}\n\t\t\tshowGitInitConfirmModal = true;\n\t\t\treturn;\n\t\t}\n\n\t\t// Non-existing folder. If it matches a remote rule AND the user still\n\t\t// wants a remote, probe (at submit time) whether that remote repo already\n\t\t// exists. If so, offer to CLONE it instead of failing on create.\n\t\tif (pathStatus.matchingRule && createRemoteRepo) {\n\t\t\tcheckingRemote = true;\n\t\t\ttry {\n\t\t\t\tconst probe = await checkRemoteRepo(newFolderCwd.trim());\n\t\t\t\tif (probe && probe.matched && probe.exists) {\n\t\t\t\t\tcloneRemoteInfo = {\n\t\t\t\t\t\tprovider: probe.provider,\n\t\t\t\t\t\tsshUrl: probe.sshUrl,\n\t\t\t\t\t};\n\t\t\t\t\tshowCloneConfirmModal = true;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\tcheckingRemote = false;\n\t\t\t}\n\t\t}\n\n\t\tsubmitCreateSession(false);\n\t}\n\n\tlet messageList = $state<HTMLDivElement>();\n\tlet {onMessageSent}: {onMessageSent: () => void} = $props();\n\n\tlet sessionInfo = $derived($activeSessionInfo);\n\tlet loadingSession = $derived($isLoadingSession);\n\tlet resyncing = $derived($isResyncing);\n\tlet readOnly = $derived($isReadOnly);\n\n\t// Fork-at-user-message (pi's `/fork`, position 'before'). Clicking the fork\n\t// icon on a user message asks the server to branch the session BEFORE that\n\t// message; the response switches us to the new session and pre-fills the\n\t// composer with the forked-at text to edit and resend.\n\tfunction handleFork(entryId: string | undefined) {\n\t\tif (!entryId) return;\n\t\tconst sessionId = sessionInfo.sessionId;\n\t\tif (!sessionId) return;\n\t\tforkSession(sessionId, entryId);\n\t}\n\n\t// Per-session beep control is tri-state: undefined = follow the global\n\t// default, true/false = an explicit choice that sticks to this session.\n\t// Cycling order: Default -> On -> Off -> Default. Showing \"Default\" (rather\n\t// than a plain on/off) is what signals the choice has NOT been set for this\n\t// session, so it tracks the default live.\n\tlet beepOverride = $derived($beepSessionOverride);\n\tlet beepOn = $derived($beepEnabled);\n\t// The Conversation Mode master toggle: one click flips the configured bundle\n\t// of knobs ON at once (and back OFF). The knobs it gates are edited\n\t// individually in Connection Settings.\n\tlet conversationOn = $derived($conversationMode);\n\t// Whether THIS conversation is just following the global default (no explicit\n\t// choice of its own). Surfaced in the toggle's tooltip so the per-conversation\n\t// scope is legible: the same bar toggle in another conversation is independent.\n\tlet conversationFollowsDefault = $derived(\n\t\t$conversationModeSessionOverride === undefined,\n\t);\n\t// This click handler is ALSO the TTS gesture-unlock point. Mobile Chrome / iOS\n\t// Safari / installed PWAs only allow the FIRST speechSynthesis.speak() from\n\t// inside a user gesture, and the `say` reply is spoken from a gesture-less\n\t// WebSocket-driven $effect below -- so without priming here, mobile silently\n\t// drops every spoken reply. Turning conversation mode ON is exactly the user\n\t// opting into spoken replies, so it is the natural gesture to prime from. The\n\t// priming is silent, idempotent and a no-op where speechSynthesis is absent\n\t// (see core/speak.ts), so this is safe on the OFF direction too -- we prime\n\t// unconditionally rather than only when turning on, since a user who toggles\n\t// off and on again would otherwise depend on which tap primed.\n\tfunction toggleConversationMode() {\n\t\tunlockTts();\n\t\tsetConversationModeBundle(!conversationOn);\n\t}\n\n\t// Whether the `collapseLongReplies` knob is currently ACTIVE. Being a gated\n\t// conversation knob, it is active only when the master conversationMode is ALSO\n\t// on (see isKnobActive), so with conversation mode off (or the knob off) long\n\t// replies render exactly as today -- no collapse. Reactive on both stores so the\n\t// transcript re-evaluates the instant either flips. This drives a DISPLAY-only\n\t// collapse: the full written reply is never removed/truncated and always stays\n\t// expandable (see core/collapse-reply.ts + the assistant branch below).\n\tlet collapseActive = $derived(\n\t\tisKnobActive('collapseLongReplies', {\n\t\t\tconversationMode: $conversationMode,\n\t\t\tautoSendOnSpeechEnd: false,\n\t\t\tspeakReplies: false,\n\t\t\tcollapseLongReplies: $collapseLongReplies,\n\t\t\tmicReopensAfterReply: false,\n\t\t}),\n\t);\n\n\t// TTS for the `say` tool. When the `speakReplies` knob is ACTIVE (which, being\n\t// a gated conversation knob, requires the master conversationMode on too — see\n\t// isKnobActive), a completed `say` tool call speaks its short text aloud via\n\t// the browser SpeechSynthesis API, using the configured speech locale for the\n\t// utterance lang. Feature-detected to a graceful no-op when the browser has no\n\t// speechSynthesis (see core/speak.ts). This is ADDITIVE: the full written\n\t// reply always stays in the transcript, and the spoken text comes ONLY from\n\t// the agent's explicit `say` call (never a client-side summary).\n\t//\n\t// Each say message is spoken AT MOST ONCE: its id is recorded on first speak\n\t// so re-renders/reactivity never re-fire the utterance. We wait until the tool\n\t// message has finished streaming so the text is final. With speakReplies off,\n\t// no utterance fires.\n\tconst spokenSayIds = new Set<string>();\n\t// Whether a `say` reply has been spoken for the turn currently in flight. The\n\t// spoken-reply FALLBACK below only speaks a turn the agent left unspoken, so\n\t// the agent's own `say` line always wins.\n\tlet spokeThisTurn = false;\n\n\t$effect(() => {\n\t\t// Subscribe reactively to the message list and the knob store so this re-runs\n\t\t// when a new say message settles or the knob flips.\n\t\tconst list = $messages;\n\t\tvoid $speakReplies;\n\t\tfor (const msg of list) {\n\t\t\tif (msg.role !== 'tool' || msg.toolName !== 'say') continue;\n\t\t\tif (msg.isStreaming) continue; // wait for the final text\n\t\t\tif (spokenSayIds.has(msg.id)) continue;\n\t\t\t// Mark first so a failed/again render never double-speaks.\n\t\t\tspokenSayIds.add(msg.id);\n\t\t\tif (msg.isError) continue;\n\t\t\tif (!isKnobActive('speakReplies', getConversationKnobs())) continue;\n\t\t\tconst parsed = parseToolMessage(msg);\n\t\t\tif (!parsed.sayText) continue;\n\t\t\tspokeThisTurn = true;\n\t\t\tspeakUtterance(parsed.sayText, speechLocale());\n\t\t}\n\t});\n\n\t// Prime browser TTS from the user's FIRST gesture whenever spoken replies are\n\t// active. The explicit unlock points (the Conversation Mode toggle, the mic\n\t// button, settings-save) all assume the user TOUCHES one of them in this page\n\t// load; a returning user whose conversation mode is already persisted ON does\n\t// not, so on mobile every reply was dropped by the user-activation gate while\n\t// desktop spoke fine. See core/speak.ts armTtsGestureUnlock.\n\t$effect(() => {\n\t\tvoid $conversationMode;\n\t\tvoid $speakReplies;\n\t\tif (!isKnobActive('speakReplies', getConversationKnobs())) return;\n\t\tarmTtsGestureUnlock();\n\t});\n\n\t// The spoken-reply FALLBACK. `say` is a REQUEST to the model, and compliance is\n\t// a model property: smaller models skip it for entire turns (measured ~50% on a\n\t// local 35B, and almost never right after a tool result), which left conversation\n\t// mode silent exactly when the user was listening. So when a turn SETTLES with\n\t// spoken replies active and nothing was spoken, speak a short plain lead-in of\n\t// the written reply instead. Additive and display-only-adjacent: the written\n\t// reply in the transcript is never modified, and a turn the agent DID speak is\n\t// never re-spoken. Keyed off the same isStreaming true->false settle edge the\n\t// waiting-for-human beep and the hands-free mic-reopen use.\n\tlet prevStreamingForSpeech = false;\n\tconst fallbackSpokenIds = new Set<string>();\n\n\t$effect(() => {\n\t\tconst list = $messages;\n\t\tconst streamingNow = $isStreaming;\n\t\tvoid $speakReplies;\n\n\t\tif (streamingNow && !prevStreamingForSpeech) {\n\t\t\t// A new turn began: it has not spoken yet.\n\t\t\tspokeThisTurn = false;\n\t\t} else if (!streamingNow && prevStreamingForSpeech) {\n\t\t\tconst reply = lastAssistantReply(list);\n\t\t\tif (reply && !fallbackSpokenIds.has(reply.id)) {\n\t\t\t\tfallbackSpokenIds.add(reply.id);\n\t\t\t\tif (\n\t\t\t\t\tshouldSpeakFallback({\n\t\t\t\t\t\tactive: isKnobActive('speakReplies', getConversationKnobs()),\n\t\t\t\t\t\tspokeThisTurn,\n\t\t\t\t\t\treply: reply.text,\n\t\t\t\t\t})\n\t\t\t\t) {\n\t\t\t\t\tspeakUtterance(spokenFallbackText(reply.text), speechLocale());\n\t\t\t\t}\n\t\t\t}\n\t\t\tspokeThisTurn = false;\n\t\t}\n\t\tprevStreamingForSpeech = streamingNow;\n\t});\n\tfunction cycleBeep() {\n\t\tif (beepOverride === undefined) setBeepSessionOverride(true);\n\t\telse if (beepOverride === true) setBeepSessionOverride(false);\n\t\telse setBeepSessionOverride(undefined);\n\t}\n\n\t// True when we hold a cached session (its file + messages) that is merely\n\t// reconnecting/resyncing, not loading fresh. In this state the conversation\n\t// must stay on screen (with the parent's \"Reconnecting...\" banner over the\n\t// composer) instead of being replaced by the big \"Not connected\" panel or the\n\t// new-session / search empty-state. This is the core of \"block only where it\n\t// matters (this session)\": a dropped socket blocks sending, not reading.\n\tlet hasCachedSession = $derived(!!sessionInfo.sessionFile);\n\t// A load ended in an error with nothing active: a URL hash still naming that\n\t// session must not keep the \"Loading session...\" spinner up (mirrors\n\t// isSessionPendingOpen's loadFailed in +page.svelte).\n\tlet loadFailed = $derived(\n\t\t!!$sessionError && !loadingSession && !resyncing && !hasCachedSession,\n\t);\n\n\tlet shouldAutoScroll = $state(true);\n\tlet forceScroll = $state(false);\n\n\tlet expandedMessages = $state<Record<string, boolean>>({});\n\n\tfunction toggleMessage(id: string, currentVal: boolean) {\n\t\texpandedMessages[id] = !currentVal;\n\t}\n\n\t// Per-assistant-message \"show raw source\" toggle: when true, the message is\n\t// shown as its verbatim markdown text (a <pre>) instead of the rendered HTML.\n\t// Keyed by message id so each message toggles independently and the choice\n\t// survives re-renders.\n\tlet rawMessages = $state<Record<string, boolean>>({});\n\n\tfunction toggleRaw(id: string) {\n\t\trawMessages[id] = !rawMessages[id];\n\t}\n\n\t// Per-message \"copied!\" confirmation. Set to the message id briefly after a\n\t// successful copy so the button can flash feedback, then cleared.\n\tlet copiedMessageId = $state<string | null>(null);\n\tlet copiedTimeout: ReturnType<typeof setTimeout> | null = null;\n\n\tasync function copyMessage(id: string, content: string) {\n\t\ttry {\n\t\t\tif (navigator.clipboard?.writeText) {\n\t\t\t\tawait navigator.clipboard.writeText(content);\n\t\t\t} else {\n\t\t\t\t// Fallback for insecure contexts / older browsers.\n\t\t\t\tconst ta = document.createElement('textarea');\n\t\t\t\tta.value = content;\n\t\t\t\tta.style.position = 'fixed';\n\t\t\t\tta.style.opacity = '0';\n\t\t\t\tdocument.body.appendChild(ta);\n\t\t\t\tta.select();\n\t\t\t\tdocument.execCommand('copy');\n\t\t\t\tdocument.body.removeChild(ta);\n\t\t\t}\n\t\t\tcopiedMessageId = id;\n\t\t\tif (copiedTimeout) clearTimeout(copiedTimeout);\n\t\t\tcopiedTimeout = setTimeout(() => {\n\t\t\t\tcopiedMessageId = null;\n\t\t\t\tcopiedTimeout = null;\n\t\t\t}, 1500);\n\t\t} catch (e) {\n\t\t\tconsole.error('Failed to copy message', e);\n\t\t}\n\t}\n\n\tfunction handleScroll() {\n\t\tif (messageList) {\n\t\t\tshouldAutoScroll = isScrolledToBottom(messageList);\n\t\t}\n\t}\n\n\tfunction scrollToBottom() {\n\t\tif (messageList) {\n\t\t\tmessageList.scrollTop = messageList.scrollHeight;\n\t\t}\n\t}\n\n\tfunction scrollToBottomIfShould() {\n\t\tif (shouldAutoScroll || forceScroll) {\n\t\t\tscrollToBottom();\n\t\t\tforceScroll = false;\n\t\t}\n\t}\n\n\tonMount(scrollToBottom);\n\n\t$effect(() => {\n\t\tif (messageList) {\n\t\t\tmessageList.addEventListener('scroll', handleScroll);\n\t\t\treturn () => {\n\t\t\t\tif (messageList) {\n\t\t\t\t\tmessageList.removeEventListener('scroll', handleScroll);\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t});\n\n\tlet lastSessionFile = $state<string | null>(null);\n\tlet wasLoadingSession = $state(false);\n\n\t// Scroll the freshly-loaded session to the bottom. The session history\n\t// arrives as a separate WS message after the session itself, and the\n\t// rendered messages (markdown, code blocks) keep growing for a few frames\n\t// after they mount, so a single synchronous scroll lands too early. Retry\n\t// across a couple of frames to settle on the true bottom.\n\tfunction scrollToBottomSettled() {\n\t\tforceScroll = true;\n\t\tscrollToBottom();\n\t\trequestAnimationFrame(() => {\n\t\t\tscrollToBottom();\n\t\t\trequestAnimationFrame(scrollToBottom);\n\t\t});\n\t\tsetTimeout(scrollToBottom, 60);\n\t\tsetTimeout(scrollToBottom, 150);\n\t}\n\n\t$effect(() => {\n\t\t// Force scroll to bottom when the active session changes...\n\t\tconst sFile = sessionInfo.sessionFile;\n\t\tif (sFile !== lastSessionFile) {\n\t\t\tlastSessionFile = sFile;\n\t\t\tforceScroll = true;\n\t\t}\n\n\t\t// ...and again once its history finishes loading, since the messages only\n\t\t// render after loadingSession flips back to false.\n\t\tconst isLoading = loadingSession;\n\t\tif (wasLoadingSession && !isLoading) {\n\t\t\tscrollToBottomSettled();\n\t\t}\n\t\twasLoadingSession = isLoading;\n\t});\n\n\tlet msgList = $derived.by(() =>\n\t\tfilterMessages(\n\t\t\t$messages,\n\t\t\t{\n\t\t\t\thideThinking: $piState.hideThinking,\n\t\t\t\thideTools: $piState.hideTools,\n\t\t\t},\n\t\t\tstreaming,\n\t\t),\n\t);\n\tlet streaming = $derived($isStreaming);\n\n\t// A live \"now\" that ticks ~every 100ms ONLY while a tool call is running, so\n\t// the \"Elapsed N.Ns\" duration counts up in real time (mirrors the pi CLI's\n\t// bash tool). The interval is torn down as soon as no tool is streaming, so an\n\t// idle session does no per-frame work. A finished tool freezes its duration\n\t// from startedAt..endedAt and does not depend on this ticker.\n\tlet now = $state(Date.now());\n\tlet anyToolRunning = $derived(\n\t\tmsgList.some((m) => m.role === 'tool' && m.isStreaming),\n\t);\n\t$effect(() => {\n\t\tif (!anyToolRunning) return;\n\t\tnow = Date.now();\n\t\tconst id = setInterval(() => (now = Date.now()), 100);\n\t\treturn () => clearInterval(id);\n\t});\n\n\t$effect.pre(() => {\n\t\t// React to msgList length and content changes of the last message in msgList\n\t\tconst lastMsg = msgList[msgList.length - 1];\n\t\tconst triggerValue = lastMsg\n\t\t\t? `${msgList.length}-${lastMsg.content.length}`\n\t\t\t: '0';\n\n\t\tif (messageList) {\n\t\t\tshouldAutoScroll = isScrolledToBottom(messageList);\n\t\t}\n\t});\n\n\t$effect(() => {\n\t\t// React to msgList length and content changes of the last message in msgList\n\t\tconst lastMsg = msgList[msgList.length - 1];\n\t\tconst triggerValue = lastMsg\n\t\t\t? `${msgList.length}-${lastMsg.content.length}`\n\t\t\t: '0';\n\n\t\tscrollToBottomIfShould();\n\t});\n\n\texport function forceScrollToBottom() {\n\t\tforceScroll = true;\n\t\tsetTimeout(scrollToBottom, 0);\n\t}\n\n\tlet moreHistory = $derived($hasMoreHistory);\n\tlet loadingMore = $derived($isLoadingMoreHistory);\n\n\t// Scroll anchoring: when older messages are prepended, keep the viewport\n\t// anchored on the message that was previously first, and reveal the newly\n\t// loaded messages as a gap above it.\n\t//\n\t// We record the id of the first message before the load. After the older\n\t// window is prepended, we scroll so that anchor message sits just below the\n\t// top of the viewport, leaving REVEAL_GAP_PX of the newly loaded messages\n\t// visible above it as a hint that more history was inserted. If the anchor\n\t// element can't be found (e.g. it was filtered out), we fall back to\n\t// preserving the distance from the bottom so the content at least doesn't\n\t// jump.\n\tconst REVEAL_GAP_PX = 64;\n\tlet pendingAnchorId = $state<string | null>(null);\n\tlet pendingAnchorFromBottom = $state<number | null>(null);\n\n\tfunction handleLoadMore() {\n\t\tif (!messageList || loadingMore || !moreHistory) return;\n\t\t// Anchor on the first currently-rendered message so we can bring it back\n\t\t// to (near) the top after the older window is prepended.\n\t\tpendingAnchorId = msgList[0]?.id ?? null;\n\t\t// Fallback anchor: distance from the bottom, in case the id can't be found.\n\t\tpendingAnchorFromBottom = messageList.scrollHeight - messageList.scrollTop;\n\t\tloadMoreHistory();\n\t}\n\n\t$effect(() => {\n\t\t// When messages change and we have a pending anchor (older history was\n\t\t// just prepended), restore the scroll position.\n\t\tconst _len = $messages.length;\n\t\tif (\n\t\t\t(pendingAnchorId !== null || pendingAnchorFromBottom !== null) &&\n\t\t\tmessageList\n\t\t) {\n\t\t\tconst anchorId = pendingAnchorId;\n\t\t\tconst anchorFromBottom = pendingAnchorFromBottom;\n\t\t\tpendingAnchorId = null;\n\t\t\tpendingAnchorFromBottom = null;\n\t\t\t// Defer until after DOM paints the prepended nodes.\n\t\t\trequestAnimationFrame(() => {\n\t\t\t\tif (!messageList) return;\n\t\t\t\tconst anchorEl = anchorId\n\t\t\t\t\t? messageList.querySelector<HTMLElement>(\n\t\t\t\t\t\t\t`[data-msg-id=\"${CSS.escape(anchorId)}\"]`,\n\t\t\t\t\t\t)\n\t\t\t\t\t: null;\n\t\t\t\tif (anchorEl) {\n\t\t\t\t\t// Position the previously-first message just below the top, leaving\n\t\t\t\t\t// a gap that reveals the newly loaded messages above it. Using\n\t\t\t\t\t// rects (instead of offsetTop) keeps this correct regardless of the\n\t\t\t\t\t// element's offset parent.\n\t\t\t\t\tconst delta =\n\t\t\t\t\t\tanchorEl.getBoundingClientRect().top -\n\t\t\t\t\t\tmessageList.getBoundingClientRect().top;\n\t\t\t\t\tmessageList.scrollTop = Math.max(\n\t\t\t\t\t\t0,\n\t\t\t\t\t\tmessageList.scrollTop + delta - REVEAL_GAP_PX,\n\t\t\t\t\t);\n\t\t\t\t} else if (anchorFromBottom !== null) {\n\t\t\t\t\tmessageList.scrollTop = messageList.scrollHeight - anchorFromBottom;\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t});\n</script>\n\n<div class=\"flex flex-1 flex-col overflow-hidden bg-brand-dark\">\n\t{#if appState.connecting && !hasCachedSession}\n\t\t<div\n\t\t\tclass=\"flex flex-1 flex-col items-center justify-center bg-brand-dark p-6 text-brand-text-muted\"\n\t\t>\n\t\t\t<div class=\"text-center\">\n\t\t\t\t<div\n\t\t\t\t\tclass=\"mb-4 inline-block h-8 w-8 animate-spin rounded-full border-4 border-brand-blue border-t-transparent\"\n\t\t\t\t></div>\n\t\t\t\t<p class=\"text-base font-medium text-brand-text\">\n\t\t\t\t\tConnecting to Wherever Server...\n\t\t\t\t</p>\n\t\t\t\t<p class=\"mt-1 text-xs text-brand-text-muted\">\n\t\t\t\t\tEstablishing secure connection to your agent\n\t\t\t\t</p>\n\t\t\t</div>\n\t\t</div>\n\t{:else if !appState.connected && !hasCachedSession}\n\t\t<div\n\t\t\tclass=\"flex flex-1 flex-col items-center justify-center bg-brand-dark p-6 text-brand-text-muted\"\n\t\t>\n\t\t\t<div\n\t\t\t\tclass=\"w-full max-w-md rounded-lg border border-red-500/30 bg-red-500/10 p-6 text-center text-brand-text\"\n\t\t\t>\n\t\t\t\t<div class=\"mb-3 text-4xl\">⚠️</div>\n\t\t\t\t<h3 class=\"text-lg font-bold text-rose-400\">Not Connected to Server</h3>\n\t\t\t\t<p class=\"mt-2 text-sm text-brand-text-muted\">\n\t\t\t\t\tWe couldn't connect to the Wherever Server. Please verify the server\n\t\t\t\t\tis running and check your connection settings in the sidebar.\n\t\t\t\t</p>\n\t\t\t\t{#if appState.error}\n\t\t\t\t\t<p\n\t\t\t\t\t\tclass=\"mt-3 max-h-24 overflow-y-auto rounded bg-brand-surface-3 p-2 font-mono text-xs text-rose-300/80\"\n\t\t\t\t\t>\n\t\t\t\t\t\t{appState.error}\n\t\t\t\t\t</p>\n\t\t\t\t{/if}\n\t\t\t\t<button\n\t\t\t\t\tonclick={() => {\n\t\t\t\t\t\timport('$lib/wherever').then((m) => m.connect());\n\t\t\t\t\t}}\n\t\t\t\t\tclass=\"mt-5 rounded bg-brand-surface-2 px-4 py-2 text-sm font-semibold text-brand-text transition-colors hover:bg-brand-surface-3\"\n\t\t\t\t>\n\t\t\t\t\tRetry Connection\n\t\t\t\t</button>\n\t\t\t</div>\n\t\t</div>\n\t{:else if !hasCachedSession && (loadingSession || (!loadFailed && typeof window !== 'undefined' && window.location.hash))}\n\t\t<!-- Genuine fresh load of a session we do NOT yet hold. A resync of a\n\t\t cached session does NOT reach here (it keeps hasCachedSession true and\n\t\t falls through to the messages view with the parent's reconnect banner),\n\t\t so returning to the app never flashes this full-screen spinner over an\n\t\t already-loaded conversation. -->\n\t\t<div\n\t\t\tclass=\"flex flex-1 flex-col items-center justify-center bg-brand-dark p-6 text-brand-text-muted\"\n\t\t>\n\t\t\t<div class=\"text-center\">\n\t\t\t\t<div\n\t\t\t\t\tclass=\"mb-4 inline-block h-8 w-8 animate-spin rounded-full border-4 border-brand-blue border-t-transparent\"\n\t\t\t\t></div>\n\t\t\t\t<p class=\"text-base font-medium text-brand-text\">Loading session...</p>\n\t\t\t\t<p class=\"mt-1 text-xs text-brand-text-muted\">\n\t\t\t\t\tRetrieving workspace session history\n\t\t\t\t</p>\n\t\t\t</div>\n\t\t</div>\n\t{:else if !sessionInfo.sessionFile}\n\t\t<div class=\"flex flex-1 items-center justify-center p-6\">\n\t\t\t<div\n\t\t\t\tclass=\"w-full max-w-md rounded-lg border border-brand-border bg-brand-surface/40 p-6 text-brand-text\"\n\t\t\t>\n\t\t\t\t<div class=\"mb-5 text-center\">\n\t\t\t\t\t<div class=\"mb-3 flex justify-center\">\n\t\t\t\t\t\t<img src={url('/logo.svg')} alt=\"Wherever\" class=\"h-16 w-16\" />\n\t\t\t\t\t</div>\n\t\t\t\t\t<h2 class=\"mb-1 text-2xl font-bold\">\n\t\t\t\t\t\t<span class=\"gradient-text\">Wherever</span>\n\t\t\t\t\t</h2>\n\t\t\t\t\t<h3 class=\"text-sm font-semibold text-brand-text\">\n\t\t\t\t\t\tCreate a New Session\n\t\t\t\t\t</h3>\n\t\t\t\t\t<p class=\"mt-1 text-xs text-brand-text-muted\">\n\t\t\t\t\t\tStart a coding session in any folder on your machine, or use the\n\t\t\t\t\t\tsidebar to open an existing session.\n\t\t\t\t\t</p>\n\t\t\t\t</div>\n\n\t\t\t\t<form\n\t\t\t\t\tonsubmit={(e) => {\n\t\t\t\t\t\te.preventDefault();\n\t\t\t\t\t\thandleFormCreateSession();\n\t\t\t\t\t}}\n\t\t\t\t\tclass=\"space-y-4\"\n\t\t\t\t>\n\t\t\t\t\t<div>\n\t\t\t\t\t\t<label\n\t\t\t\t\t\t\tclass=\"mb-1 block text-xs font-bold tracking-wider text-brand-text-muted uppercase\"\n\t\t\t\t\t\t\tfor=\"main-folder-path\">Folder Path</label\n\t\t\t\t\t\t>\n\t\t\t\t\t\t<div class=\"relative\" bind:this={containerEl}>\n\t\t\t\t\t\t\t<input\n\t\t\t\t\t\t\t\tbind:this={inputEl}\n\t\t\t\t\t\t\t\tid=\"main-folder-path\"\n\t\t\t\t\t\t\t\ttype=\"text\"\n\t\t\t\t\t\t\t\tautocomplete=\"off\"\n\t\t\t\t\t\t\t\tspellcheck=\"false\"\n\t\t\t\t\t\t\t\tplaceholder=\"e.g. ~/projects/my-new-app\"\n\t\t\t\t\t\t\t\tbind:value={newFolderCwd}\n\t\t\t\t\t\t\t\tonfocus={() => {\n\t\t\t\t\t\t\t\t\tinputFocused = true;\n\t\t\t\t\t\t\t\t\ttriggerCheck(newFolderCwd, true);\n\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t\tonblur={(e) => {\n\t\t\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t\t\tcontainerEl &&\n\t\t\t\t\t\t\t\t\t\tcontainerEl.contains(e.relatedTarget as Node)\n\t\t\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tinputFocused = false;\n\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t\tonkeydown={(e) => {\n\t\t\t\t\t\t\t\t\tif (e.key === 'Escape') {\n\t\t\t\t\t\t\t\t\t\tinputFocused = false;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t\tclass=\"w-full rounded border px-3 py-2 text-sm text-brand-text placeholder-brand-text-muted transition-all duration-200 focus:outline-none {isRemoteRepoCreation\n\t\t\t\t\t\t\t\t\t? 'border-emerald-500/80 bg-emerald-500/10 focus:border-emerald-400 focus:ring-1 focus:ring-emerald-400/30'\n\t\t\t\t\t\t\t\t\t: 'border-brand-border bg-brand-surface-3 focus:border-brand-blue'}\"\n\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t{#if inputFocused && completions.length > 0}\n\t\t\t\t\t\t\t\t<div\n\t\t\t\t\t\t\t\t\tclass=\"absolute right-0 left-0 z-50 mt-1 max-h-48 overflow-y-auto rounded border border-brand-border bg-brand-surface-2 py-1 shadow-xl\"\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t{#each completions as completion}\n\t\t\t\t\t\t\t\t\t\t<button\n\t\t\t\t\t\t\t\t\t\t\ttype=\"button\"\n\t\t\t\t\t\t\t\t\t\t\tonclick={() => {\n\t\t\t\t\t\t\t\t\t\t\t\tnewFolderCwd = completion;\n\t\t\t\t\t\t\t\t\t\t\t\ttriggerCheck(completion, true);\n\t\t\t\t\t\t\t\t\t\t\t\tinputEl?.focus();\n\t\t\t\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t\t\t\t\tclass=\"block w-full px-3 py-1.5 text-left text-sm text-brand-text transition-colors hover:bg-brand-surface-3 hover:text-brand-text\"\n\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t{completion}\n\t\t\t\t\t\t\t\t\t\t</button>\n\t\t\t\t\t\t\t\t\t{/each}\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t{#if pathStatus.exists === true}\n\t\t\t\t\t\t\t<span class=\"mt-1.5 block text-xs font-medium text-yellow-400\">\n\t\t\t\t\t\t\t\t📁 Folder already exists. Joining will create a session in it.\n\t\t\t\t\t\t\t\t{#if pathStatus.isGit}\n\t\t\t\t\t\t\t\t\t<span class=\"ml-1 font-medium text-emerald-400\"\n\t\t\t\t\t\t\t\t\t\t>(Git repo detected)</span\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t\t</span>\n\t\t\t\t\t\t{:else}\n\t\t\t\t\t\t\t<span class=\"mt-1 block text-[10px] text-brand-text-muted\"\n\t\t\t\t\t\t\t\t>Relative paths are created inside your home folder.</span\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t{/if}\n\t\t\t\t\t</div>\n\n\t\t\t\t\t<div>\n\t\t\t\t\t\t<label\n\t\t\t\t\t\t\tclass=\"mb-1 block text-xs font-bold tracking-wider text-brand-text-muted uppercase\"\n\t\t\t\t\t\t\tfor=\"main-model-select\">Model</label\n\t\t\t\t\t\t>\n\t\t\t\t\t\t{#if modelsData.models.length > 0}\n\t\t\t\t\t\t\t<select\n\t\t\t\t\t\t\t\tid=\"main-model-select\"\n\t\t\t\t\t\t\t\tbind:value={newFolderModel}\n\t\t\t\t\t\t\t\tclass=\"w-full rounded border border-brand-border bg-brand-surface-3 px-3 py-2 text-sm text-brand-text focus:border-brand-blue focus:outline-none\"\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t{#each modelsData.models as model}\n\t\t\t\t\t\t\t\t\t<option value={`${model.provider}:${model.modelId}`}>\n\t\t\t\t\t\t\t\t\t\t{model.label}{model.isDefault ? ' (default)' : ''}\n\t\t\t\t\t\t\t\t\t</option>\n\t\t\t\t\t\t\t\t{/each}\n\t\t\t\t\t\t\t</select>\n\t\t\t\t\t\t{:else}\n\t\t\t\t\t\t\t<input\n\t\t\t\t\t\t\t\tid=\"main-model-select\"\n\t\t\t\t\t\t\t\ttype=\"text\"\n\t\t\t\t\t\t\t\tbind:value={newFolderModel}\n\t\t\t\t\t\t\t\tplaceholder=\"provider:model\"\n\t\t\t\t\t\t\t\tclass=\"w-full rounded border border-brand-border bg-brand-surface-3 px-3 py-2 text-sm text-brand-text placeholder-brand-text-muted focus:border-brand-blue focus:outline-none\"\n\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t{/if}\n\t\t\t\t\t</div>\n\n\t\t\t\t\t{#if pathStatus.exists !== true && pathStatus.matchingRule}\n\t\t\t\t\t\t<div class=\"space-y-1.5 pt-1\">\n\t\t\t\t\t\t\t<div class=\"flex items-center gap-2\">\n\t\t\t\t\t\t\t\t<input\n\t\t\t\t\t\t\t\t\tid=\"main-create-remote\"\n\t\t\t\t\t\t\t\t\ttype=\"checkbox\"\n\t\t\t\t\t\t\t\t\tbind:checked={createRemoteRepo}\n\t\t\t\t\t\t\t\t\tclass=\"h-4 w-4 rounded border-brand-border bg-brand-surface-3 text-brand-blue focus:ring-brand-blue focus:ring-offset-brand-surface\"\n\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t\t<label\n\t\t\t\t\t\t\t\t\tfor=\"main-create-remote\"\n\t\t\t\t\t\t\t\t\tclass=\"cursor-pointer text-sm text-brand-text select-none\"\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\tCreate remote {pathStatus.matchingRule.provider} repository\n\t\t\t\t\t\t\t\t</label>\n\t\t\t\t\t\t\t</div>\n\n\t\t\t\t\t\t\t{#if createRemoteRepo}\n\t\t\t\t\t\t\t\t<div\n\t\t\t\t\t\t\t\t\tclass=\"flex items-center gap-4 pl-6 text-xs text-brand-text-muted\"\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t<span>Visibility:</span>\n\t\t\t\t\t\t\t\t\t<label\n\t\t\t\t\t\t\t\t\t\tclass=\"flex cursor-pointer items-center gap-1.5 transition-colors select-none hover:text-brand-text\"\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t<input\n\t\t\t\t\t\t\t\t\t\t\ttype=\"radio\"\n\t\t\t\t\t\t\t\t\t\t\tname=\"main-visibility\"\n\t\t\t\t\t\t\t\t\t\t\tvalue=\"private\"\n\t\t\t\t\t\t\t\t\t\t\tbind:group={repoVisibility}\n\t\t\t\t\t\t\t\t\t\t\tclass=\"border-brand-border bg-brand-surface-3 text-brand-blue focus:ring-brand-blue\"\n\t\t\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t\t\t\tPrivate\n\t\t\t\t\t\t\t\t\t</label>\n\t\t\t\t\t\t\t\t\t<label\n\t\t\t\t\t\t\t\t\t\tclass=\"flex cursor-pointer items-center gap-1.5 transition-colors select-none hover:text-brand-text\"\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t<input\n\t\t\t\t\t\t\t\t\t\t\ttype=\"radio\"\n\t\t\t\t\t\t\t\t\t\t\tname=\"main-visibility\"\n\t\t\t\t\t\t\t\t\t\t\tvalue=\"public\"\n\t\t\t\t\t\t\t\t\t\t\tbind:group={repoVisibility}\n\t\t\t\t\t\t\t\t\t\t\tclass=\"border-brand-border bg-brand-surface-3 text-brand-blue focus:ring-brand-blue\"\n\t\t\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t\t\t\tPublic\n\t\t\t\t\t\t\t\t\t</label>\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t</div>\n\t\t\t\t\t{/if}\n\n\t\t\t\t\t{#if pathStatus.exists !== true && (!pathStatus.matchingRule || !createRemoteRepo)}\n\t\t\t\t\t\t<div class=\"flex items-center gap-2 pt-1\">\n\t\t\t\t\t\t\t<input\n\t\t\t\t\t\t\t\tid=\"main-git-init\"\n\t\t\t\t\t\t\t\ttype=\"checkbox\"\n\t\t\t\t\t\t\t\tbind:checked={newFolderGitInit}\n\t\t\t\t\t\t\t\tonchange={(e) => {\n\t\t\t\t\t\t\t\t\tuserManualGitInit = e.currentTarget.checked;\n\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t\tclass=\"h-4 w-4 rounded border-brand-border bg-brand-surface-3 text-brand-blue focus:ring-brand-blue focus:ring-offset-brand-surface\"\n\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t<label\n\t\t\t\t\t\t\t\tfor=\"main-git-init\"\n\t\t\t\t\t\t\t\tclass=\"cursor-pointer text-sm text-brand-text select-none\"\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\tInitialize Git repository\n\t\t\t\t\t\t\t</label>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t{/if}\n\n\t\t\t\t\t<button\n\t\t\t\t\t\ttype=\"submit\"\n\t\t\t\t\t\tdisabled={!newFolderCwd.trim() || checkingRemote}\n\t\t\t\t\t\tclass=\"w-full rounded bg-gradient-to-r from-brand-cyan to-brand-blue py-2.5 text-sm font-semibold text-brand-text transition-all hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-50\"\n\t\t\t\t\t>\n\t\t\t\t\t\t{checkingRemote ? 'Checking remote...' : 'Create & Start Session'}\n\t\t\t\t\t</button>\n\t\t\t\t</form>\n\t\t\t</div>\n\t\t</div>\n\t{:else if msgList.length === 0 && (loadingSession || resyncing)}\n\t\t<!-- The session is known (session_created landed, so sessionFile is set)\n\t\t but its history has not arrived yet: the server sends session_created\n\t\t and message_history as two frames, and on a slow link the (large)\n\t\t history frame can trail by seconds. Without this branch that gap fell\n\t\t through to the \"New Session Started\" empty-state below, which lies\n\t\t about an existing conversation. -->\n\t\t<div\n\t\t\tclass=\"flex flex-1 flex-col items-center justify-center bg-brand-dark p-6 text-brand-text-muted\"\n\t\t>\n\t\t\t<div class=\"text-center\">\n\t\t\t\t<div\n\t\t\t\t\tclass=\"mb-4 inline-block h-8 w-8 animate-spin rounded-full border-4 border-brand-blue border-t-transparent\"\n\t\t\t\t></div>\n\t\t\t\t<p class=\"text-base font-medium text-brand-text\">\n\t\t\t\t\tLoading conversation...\n\t\t\t\t</p>\n\t\t\t\t<p class=\"mt-1 text-xs text-brand-text-muted\">\n\t\t\t\t\tRetrieving workspace session history\n\t\t\t\t</p>\n\t\t\t</div>\n\t\t</div>\n\t{:else if msgList.length === 0}\n\t\t<div class=\"flex flex-1 items-center justify-center text-brand-text-muted\">\n\t\t\t<div class=\"text-center\">\n\t\t\t\t<div class=\"mb-4 text-4xl\">💬</div>\n\t\t\t\t<p class=\"mb-2 text-lg font-medium text-brand-text\">\n\t\t\t\t\tNew Session Started\n\t\t\t\t</p>\n\t\t\t\t<p class=\"text-sm\">Type a message below to start building</p>\n\t\t\t</div>\n\t\t</div>\n\t{:else}\n\t\t<div\n\t\t\tbind:this={messageList}\n\t\t\tclass=\"flex-1 space-y-4 overflow-y-auto overscroll-y-contain p-4\"\n\t\t>\n\t\t\t{#if moreHistory}\n\t\t\t\t<div class=\"flex justify-center pb-2\">\n\t\t\t\t\t<button\n\t\t\t\t\t\tonclick={handleLoadMore}\n\t\t\t\t\t\tdisabled={loadingMore}\n\t\t\t\t\t\tclass=\"rounded border border-brand-border bg-brand-surface-2 px-3 py-1.5 text-xs text-brand-text-muted transition-colors hover:bg-brand-surface-3 hover:text-brand-text disabled:cursor-not-allowed disabled:opacity-50\"\n\t\t\t\t\t>\n\t\t\t\t\t\t{#if loadingMore}\n\t\t\t\t\t\t\tLoading older messages...\n\t\t\t\t\t\t{:else}\n\t\t\t\t\t\t\tLoad older messages\n\t\t\t\t\t\t{/if}\n\t\t\t\t\t</button>\n\t\t\t\t</div>\n\t\t\t{/if}\n\t\t\t{#each msgList as msg (msg.id)}\n\t\t\t\t<div\n\t\t\t\t\tdata-msg-id={msg.id}\n\t\t\t\t\tclass=\"flex {msg.role === 'user' ? 'justify-end' : 'justify-start'}\"\n\t\t\t\t>\n\t\t\t\t\t<div\n\t\t\t\t\t\tclass=\"max-w-[85%] rounded-lg px-4 py-3 {msg.role === 'user'\n\t\t\t\t\t\t\t? msg.delivery === 'sending'\n\t\t\t\t\t\t\t\t? 'bg-brand-blue/40 text-brand-text ring-1 ring-brand-blue/50'\n\t\t\t\t\t\t\t\t: msg.delivery === 'failed'\n\t\t\t\t\t\t\t\t\t? 'bg-brand-blue/30 text-brand-text ring-1 ring-amber-400/50'\n\t\t\t\t\t\t\t\t\t: 'bg-brand-blue/80 text-brand-text'\n\t\t\t\t\t\t\t: msg.role === 'thinking'\n\t\t\t\t\t\t\t\t? 'border-l-2 border-brand-border bg-brand-surface/30 text-sm text-brand-text-muted'\n\t\t\t\t\t\t\t\t: msg.role === 'tool' && isFirstClassTool(msg.toolName)\n\t\t\t\t\t\t\t\t\t? 'bg-transparent p-0 text-brand-text'\n\t\t\t\t\t\t\t\t\t: msg.role === 'tool'\n\t\t\t\t\t\t\t\t\t\t? $piState.hideTools && !isAssociatedWithForceCommand(msg)\n\t\t\t\t\t\t\t\t\t\t\t? 'border-l-2 border-brand-border bg-brand-surface/30 text-sm text-brand-text-muted'\n\t\t\t\t\t\t\t\t\t\t\t: `border-l-2 bg-brand-surface-2 font-mono text-sm text-brand-text ${\n\t\t\t\t\t\t\t\t\t\t\t\t\tmsg.isStreaming\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t? 'border-amber-400'\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t: msg.isError\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t? 'border-rose-400'\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t: msg.interrupted\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t? 'border-brand-border'\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t: 'border-emerald-400'\n\t\t\t\t\t\t\t\t\t\t\t\t}`\n\t\t\t\t\t\t\t\t\t\t: msg.role === 'assistant'\n\t\t\t\t\t\t\t\t\t\t\t? 'border-l-2 border-brand-purple bg-brand-purple/10 text-brand-text'\n\t\t\t\t\t\t\t\t\t\t\t: msg.content === '' && msg.isStreaming\n\t\t\t\t\t\t\t\t\t\t\t\t? 'bg-brand-surface-3 text-brand-text-muted italic'\n\t\t\t\t\t\t\t\t\t\t\t\t: 'bg-brand-surface-2 text-brand-text'}\"\n\t\t\t\t\t>\n\t\t\t\t\t\t{#if msg.role === 'thinking'}\n\t\t\t\t\t\t\t{#if msg.content === 'FALLBACK_THINKING_LOADER'}\n\t\t\t\t\t\t\t\t<div\n\t\t\t\t\t\t\t\t\tclass=\"flex items-center gap-2 font-sans text-sm text-brand-text-muted italic select-none\"\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t<svg\n\t\t\t\t\t\t\t\t\t\tclass=\"h-4 w-4 animate-spin text-brand-cyan\"\n\t\t\t\t\t\t\t\t\t\txmlns=\"http://www.w3.org/2000/svg\"\n\t\t\t\t\t\t\t\t\t\tfill=\"none\"\n\t\t\t\t\t\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t<circle\n\t\t\t\t\t\t\t\t\t\t\tclass=\"opacity-25\"\n\t\t\t\t\t\t\t\t\t\t\tcx=\"12\"\n\t\t\t\t\t\t\t\t\t\t\tcy=\"12\"\n\t\t\t\t\t\t\t\t\t\t\tr=\"10\"\n\t\t\t\t\t\t\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\t\t\t\t\t\t\tstroke-width=\"4\"\n\t\t\t\t\t\t\t\t\t\t></circle>\n\t\t\t\t\t\t\t\t\t\t<path\n\t\t\t\t\t\t\t\t\t\t\tclass=\"opacity-75\"\n\t\t\t\t\t\t\t\t\t\t\tfill=\"currentColor\"\n\t\t\t\t\t\t\t\t\t\t\td=\"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z\"\n\t\t\t\t\t\t\t\t\t\t></path>\n\t\t\t\t\t\t\t\t\t</svg>\n\t\t\t\t\t\t\t\t\t<span>Agent is thinking...</span>\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t{:else if msg.content === 'FALLBACK_LOADER'}\n\t\t\t\t\t\t\t\t<div\n\t\t\t\t\t\t\t\t\tclass=\"flex items-center gap-2 font-sans text-sm text-brand-text-muted italic select-none\"\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t<svg\n\t\t\t\t\t\t\t\t\t\tclass=\"h-4 w-4 animate-spin text-brand-cyan\"\n\t\t\t\t\t\t\t\t\t\txmlns=\"http://www.w3.org/2000/svg\"\n\t\t\t\t\t\t\t\t\t\tfill=\"none\"\n\t\t\t\t\t\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t<circle\n\t\t\t\t\t\t\t\t\t\t\tclass=\"opacity-25\"\n\t\t\t\t\t\t\t\t\t\t\tcx=\"12\"\n\t\t\t\t\t\t\t\t\t\t\tcy=\"12\"\n\t\t\t\t\t\t\t\t\t\t\tr=\"10\"\n\t\t\t\t\t\t\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\t\t\t\t\t\t\tstroke-width=\"4\"\n\t\t\t\t\t\t\t\t\t\t></circle>\n\t\t\t\t\t\t\t\t\t\t<path\n\t\t\t\t\t\t\t\t\t\t\tclass=\"opacity-75\"\n\t\t\t\t\t\t\t\t\t\t\tfill=\"currentColor\"\n\t\t\t\t\t\t\t\t\t\t\td=\"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z\"\n\t\t\t\t\t\t\t\t\t\t></path>\n\t\t\t\t\t\t\t\t\t</svg>\n\t\t\t\t\t\t\t\t\t<span>Agent working...</span>\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t{:else if $piState.hideThinking}\n\t\t\t\t\t\t\t\t<div\n\t\t\t\t\t\t\t\t\tclass=\"flex items-center gap-2 font-sans text-sm text-brand-text-muted italic select-none\"\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t<svg\n\t\t\t\t\t\t\t\t\t\tclass=\"h-4 w-4 animate-spin text-brand-cyan\"\n\t\t\t\t\t\t\t\t\t\txmlns=\"http://www.w3.org/2000/svg\"\n\t\t\t\t\t\t\t\t\t\tfill=\"none\"\n\t\t\t\t\t\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t<circle\n\t\t\t\t\t\t\t\t\t\t\tclass=\"opacity-25\"\n\t\t\t\t\t\t\t\t\t\t\tcx=\"12\"\n\t\t\t\t\t\t\t\t\t\t\tcy=\"12\"\n\t\t\t\t\t\t\t\t\t\t\tr=\"10\"\n\t\t\t\t\t\t\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\t\t\t\t\t\t\tstroke-width=\"4\"\n\t\t\t\t\t\t\t\t\t\t></circle>\n\t\t\t\t\t\t\t\t\t\t<path\n\t\t\t\t\t\t\t\t\t\t\tclass=\"opacity-75\"\n\t\t\t\t\t\t\t\t\t\t\tfill=\"currentColor\"\n\t\t\t\t\t\t\t\t\t\t\td=\"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z\"\n\t\t\t\t\t\t\t\t\t\t></path>\n\t\t\t\t\t\t\t\t\t</svg>\n\t\t\t\t\t\t\t\t\t<span>Agent is thinking...</span>\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t{:else}\n\t\t\t\t\t\t\t\t<div class=\"flex flex-col gap-1\">\n\t\t\t\t\t\t\t\t\t{#if msg.isStreaming}\n\t\t\t\t\t\t\t\t\t\t<div\n\t\t\t\t\t\t\t\t\t\t\tclass=\"mb-1 flex items-center gap-1.5 text-[10px] font-bold tracking-wider text-brand-cyan uppercase select-none\"\n\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t<span\n\t\t\t\t\t\t\t\t\t\t\t\tclass=\"inline-block h-1.5 w-1.5 animate-pulse rounded-full bg-brand-cyan\"\n\t\t\t\t\t\t\t\t\t\t\t></span>\n\t\t\t\t\t\t\t\t\t\t\t<span>Thinking</span>\n\t\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t\t\t\t<div class=\"font-mono text-sm whitespace-pre-wrap\">\n\t\t\t\t\t\t\t\t\t\t{msg.content}\n\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t{:else if msg.role === 'tool'}\n\t\t\t\t\t\t\t{#if $piState.hideTools && !isFirstClassTool(msg.toolName) && !isAssociatedWithForceCommand(msg)}\n\t\t\t\t\t\t\t\t<div\n\t\t\t\t\t\t\t\t\tclass=\"flex items-center gap-2 font-sans text-sm text-brand-text-muted italic select-none\"\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t<svg\n\t\t\t\t\t\t\t\t\t\tclass=\"h-4 w-4 animate-spin text-amber-500\"\n\t\t\t\t\t\t\t\t\t\txmlns=\"http://www.w3.org/2000/svg\"\n\t\t\t\t\t\t\t\t\t\tfill=\"none\"\n\t\t\t\t\t\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t<circle\n\t\t\t\t\t\t\t\t\t\t\tclass=\"opacity-25\"\n\t\t\t\t\t\t\t\t\t\t\tcx=\"12\"\n\t\t\t\t\t\t\t\t\t\t\tcy=\"12\"\n\t\t\t\t\t\t\t\t\t\t\tr=\"10\"\n\t\t\t\t\t\t\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\t\t\t\t\t\t\tstroke-width=\"4\"\n\t\t\t\t\t\t\t\t\t\t></circle>\n\t\t\t\t\t\t\t\t\t\t<path\n\t\t\t\t\t\t\t\t\t\t\tclass=\"opacity-75\"\n\t\t\t\t\t\t\t\t\t\t\tfill=\"currentColor\"\n\t\t\t\t\t\t\t\t\t\t\td=\"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z\"\n\t\t\t\t\t\t\t\t\t\t></path>\n\t\t\t\t\t\t\t\t\t</svg>\n\t\t\t\t\t\t\t\t\t<span\n\t\t\t\t\t\t\t\t\t\t>Running tool: <span\n\t\t\t\t\t\t\t\t\t\t\tclass=\"rounded bg-brand-surface-3 px-1 py-0.5 font-mono text-xs font-semibold\"\n\t\t\t\t\t\t\t\t\t\t\t>{msg.toolName || 'agent'}</span\n\t\t\t\t\t\t\t\t\t\t>...</span\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t{#if toolDuration(msg, now)}\n\t\t\t\t\t\t\t\t\t\t<span\n\t\t\t\t\t\t\t\t\t\t\tclass=\"font-mono text-xs text-brand-text-muted tabular-nums\"\n\t\t\t\t\t\t\t\t\t\t\t>{toolDuration(msg, now)}</span\n\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t{:else}\n\t\t\t\t\t\t\t\t{@const parsed = parseToolMessage(msg)}\n\t\t\t\t\t\t\t\t{@const isExpanded =\n\t\t\t\t\t\t\t\t\texpandedMessages[msg.id] !== undefined\n\t\t\t\t\t\t\t\t\t\t? expandedMessages[msg.id]\n\t\t\t\t\t\t\t\t\t\t: shouldAutoExpand(msg, msgList)}\n\t\t\t\t\t\t\t\t{@const dlPath = parsed.downloadPath}\n\t\t\t\t\t\t\t\t{@const dlUrl = dlPath ? downloadFileUrl(dlPath) : null}\n\t\t\t\t\t\t\t\t{@const dlKind = dlPath ? mediaKind(dlPath) : null}\n\t\t\t\t\t\t\t\t{@const isAttachTool = parsed.toolName === 'attach_file'}\n\t\t\t\t\t\t\t\t{@const isSayTool = parsed.toolName === 'say'}\n\t\t\t\t\t\t\t\t{#if isAttachTool}\n\t\t\t\t\t\t\t\t\t<!-- attach_file rendered as a first-class ATTACHMENT, not a\n\t\t\t\t\t\t\t\t\t generic tool card: the agent explicitly offered this file\n\t\t\t\t\t\t\t\t\t for the (remote) user to download. Three states: streaming\n\t\t\t\t\t\t\t\t\t (attaching...), error (could not attach), success (download\n\t\t\t\t\t\t\t\t\t link). A failed attach shows the tool's error text so the\n\t\t\t\t\t\t\t\t\t agent/user can see WHY (e.g. file not found). -->\n\t\t\t\t\t\t\t\t\t{@const fileName = dlPath\n\t\t\t\t\t\t\t\t\t\t? dlPath.split('/').pop() || dlPath\n\t\t\t\t\t\t\t\t\t\t: ''}\n\t\t\t\t\t\t\t\t\t<div class=\"flex max-w-full min-w-[240px] flex-col\">\n\t\t\t\t\t\t\t\t\t\t{#if msg.isStreaming}\n\t\t\t\t\t\t\t\t\t\t\t<div\n\t\t\t\t\t\t\t\t\t\t\t\tclass=\"flex items-center gap-3 rounded-lg border border-brand-border bg-brand-surface-2 px-3 py-2.5 text-brand-text-muted\"\n\t\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t\t<span class=\"animate-pulse text-2xl leading-none\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t>📎</span\n\t\t\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t\t<span class=\"truncate text-sm\">Attaching file…</span>\n\t\t\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t\t{:else if parsed.isError}\n\t\t\t\t\t\t\t\t\t\t\t<div\n\t\t\t\t\t\t\t\t\t\t\t\tclass=\"flex items-start gap-3 rounded-lg border border-rose-400/40 bg-rose-400/10 px-3 py-2.5 text-brand-text\"\n\t\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t\t<span class=\"text-2xl leading-none\">📎</span>\n\t\t\t\t\t\t\t\t\t\t\t\t<span class=\"flex min-w-0 flex-1 flex-col gap-0.5\">\n\t\t\t\t\t\t\t\t\t\t\t\t\t<span class=\"text-sm font-semibold text-rose-300\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t>Could not attach file</span\n\t\t\t\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t\t\t{#if parsed.toolOutput}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t<span\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tclass=\"text-xs break-words text-brand-text-muted\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t>{parsed.toolOutput}</span\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t\t\t\t\t\t\t</span>\n\t\t\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t\t{:else if dlUrl}\n\t\t\t\t\t\t\t\t\t\t\t<a\n\t\t\t\t\t\t\t\t\t\t\t\thref={dlUrl}\n\t\t\t\t\t\t\t\t\t\t\t\tdownload={fileName}\n\t\t\t\t\t\t\t\t\t\t\t\tclass=\"flex items-center gap-3 rounded-lg border border-brand-cyan/40 bg-brand-cyan/10 px-3 py-2.5 text-brand-text no-underline transition-colors hover:bg-brand-cyan/20\"\n\t\t\t\t\t\t\t\t\t\t\t\ttitle={`Download ${dlPath}`}\n\t\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t\t<span class=\"text-2xl leading-none\">📎</span>\n\t\t\t\t\t\t\t\t\t\t\t\t<span class=\"flex min-w-0 flex-1 flex-col\">\n\t\t\t\t\t\t\t\t\t\t\t\t\t<span class=\"truncate text-sm font-semibold\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t>{fileName}</span\n\t\t\t\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t\t\t<span\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tclass=\"truncate text-xs text-brand-text-muted\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\ttitle={dlPath}>{dlPath}</span\n\t\t\t\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t\t</span>\n\t\t\t\t\t\t\t\t\t\t\t\t<span\n\t\t\t\t\t\t\t\t\t\t\t\t\tclass=\"flex shrink-0 items-center gap-1 rounded-md bg-brand-cyan/20 px-2.5 py-1 text-xs font-medium text-brand-cyan\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t>⬇️ Download</span\n\t\t\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t</a>\n\t\t\t\t\t\t\t\t\t\t{:else}\n\t\t\t\t\t\t\t\t\t\t\t<div\n\t\t\t\t\t\t\t\t\t\t\t\tclass=\"flex items-center gap-3 rounded-lg border border-brand-border bg-brand-surface-2 px-3 py-2.5 text-brand-text-muted\"\n\t\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t\t<span class=\"text-2xl leading-none\">📎</span>\n\t\t\t\t\t\t\t\t\t\t\t\t<span class=\"flex min-w-0 flex-1 flex-col\">\n\t\t\t\t\t\t\t\t\t\t\t\t\t<span class=\"truncate text-sm font-semibold\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t>{fileName}</span\n\t\t\t\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t\t\t<span class=\"truncate text-xs\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t>No active session to download from</span\n\t\t\t\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t\t</span>\n\t\t\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t\t{/if}\n\n\t\t\t\t\t\t\t\t\t\t<!-- Inline image preview for an attached image, sourced from the\n\t\t\t\t\t\t\t\t\t\t SAME token-gated download URL as the chip above (NOT from\n\t\t\t\t\t\t\t\t\t\t embedded bytes). Additive: the download chip stays; this is a\n\t\t\t\t\t\t\t\t\t\t tap-to-open, lazy-loaded preview so the image is viewable\n\t\t\t\t\t\t\t\t\t\t without leaving the chat. -->\n\t\t\t\t\t\t\t\t\t\t{#if !msg.isStreaming && !parsed.isError && dlUrl && dlKind === 'image'}\n\t\t\t\t\t\t\t\t\t\t\t<a\n\t\t\t\t\t\t\t\t\t\t\t\thref={dlUrl}\n\t\t\t\t\t\t\t\t\t\t\t\ttarget=\"_blank\"\n\t\t\t\t\t\t\t\t\t\t\t\trel=\"noopener noreferrer\"\n\t\t\t\t\t\t\t\t\t\t\t\tclass=\"mt-2 block\"\n\t\t\t\t\t\t\t\t\t\t\t\ttitle={`Open ${dlPath}`}\n\t\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t\t<img\n\t\t\t\t\t\t\t\t\t\t\t\t\tsrc={dlUrl}\n\t\t\t\t\t\t\t\t\t\t\t\t\talt={dlPath}\n\t\t\t\t\t\t\t\t\t\t\t\t\tloading=\"lazy\"\n\t\t\t\t\t\t\t\t\t\t\t\t\tclass=\"max-h-96 max-w-full rounded border border-brand-border/40 bg-brand-dark/60 object-contain\"\n\t\t\t\t\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t\t\t\t\t</a>\n\t\t\t\t\t\t\t\t\t\t{/if}\n\n\t\t\t\t\t\t\t\t\t\t<!-- Inline AUDIO player for an attached audio file, sourced\n\t\t\t\t\t\t\t\t\t\t from the SAME token-gated download URL as the chip above (NOT\n\t\t\t\t\t\t\t\t\t\t from embedded bytes). Additive: the download chip stays; this\n\t\t\t\t\t\t\t\t\t\t lets the user listen without leaving the chat. `preload`\n\t\t\t\t\t\t\t\t\t\t metadata only, and an unsupported format degrades to the chip\n\t\t\t\t\t\t\t\t\t\t (the browser renders the empty player; the chip above always\n\t\t\t\t\t\t\t\t\t\t remains for save/share). -->\n\t\t\t\t\t\t\t\t\t\t{#if !msg.isStreaming && !parsed.isError && dlUrl && dlKind === 'audio'}\n\t\t\t\t\t\t\t\t\t\t\t<audio\n\t\t\t\t\t\t\t\t\t\t\t\tcontrols\n\t\t\t\t\t\t\t\t\t\t\t\tpreload=\"metadata\"\n\t\t\t\t\t\t\t\t\t\t\t\tsrc={dlUrl}\n\t\t\t\t\t\t\t\t\t\t\t\ttitle={dlPath}\n\t\t\t\t\t\t\t\t\t\t\t\tclass=\"mt-2 block w-full max-w-full\"\n\t\t\t\t\t\t\t\t\t\t\t></audio>\n\t\t\t\t\t\t\t\t\t\t{/if}\n\n\t\t\t\t\t\t\t\t\t\t<!-- Inline VIDEO player for an attached video file, sourced\n\t\t\t\t\t\t\t\t\t\t from the SAME token-gated download URL as the chip above (NOT\n\t\t\t\t\t\t\t\t\t\t from embedded bytes). Additive: the download chip stays; this\n\t\t\t\t\t\t\t\t\t\t lets the user watch (and SEEK — the server honours HTTP Range)\n\t\t\t\t\t\t\t\t\t\t without leaving the chat. `playsinline` keeps iOS from going\n\t\t\t\t\t\t\t\t\t\t fullscreen; `preload` metadata only; an unsupported format\n\t\t\t\t\t\t\t\t\t\t degrades to the chip (empty player, chip always remains). -->\n\t\t\t\t\t\t\t\t\t\t{#if !msg.isStreaming && !parsed.isError && dlUrl && dlKind === 'video'}\n\t\t\t\t\t\t\t\t\t\t\t<video\n\t\t\t\t\t\t\t\t\t\t\t\tcontrols\n\t\t\t\t\t\t\t\t\t\t\t\tplaysinline\n\t\t\t\t\t\t\t\t\t\t\t\tpreload=\"metadata\"\n\t\t\t\t\t\t\t\t\t\t\t\tsrc={dlUrl}\n\t\t\t\t\t\t\t\t\t\t\t\ttitle={dlPath}\n\t\t\t\t\t\t\t\t\t\t\t\tclass=\"mt-2 block max-h-96 w-full max-w-full rounded border border-brand-border/40 bg-brand-dark/60\"\n\t\t\t\t\t\t\t\t\t\t\t></video>\n\t\t\t\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t{:else if isSayTool}\n\t\t\t\t\t\t\t\t\t<!-- say rendered as a first-class \"spoken:\" card, not a generic\n\t\t\t\t\t\t\t\t\t tool card: the agent EXPLICITLY offered this SHORT spoken-form\n\t\t\t\t\t\t\t\t\t reply (the 🔊 pill) so the user can visually compare it against\n\t\t\t\t\t\t\t\t\t the FULL written reply, which always remains present in the\n\t\t\t\t\t\t\t\t\t transcript above/below. The card is ADDITIVE: it never replaces\n\t\t\t\t\t\t\t\t\t or hides the full reply. TTS (when speakReplies is active) fires\n\t\t\t\t\t\t\t\t\t off the SAME text via the $effect below, not from here. -->\n\t\t\t\t\t\t\t\t\t<div class=\"flex max-w-full min-w-[240px] flex-col\">\n\t\t\t\t\t\t\t\t\t\t{#if parsed.isError}\n\t\t\t\t\t\t\t\t\t\t\t<div\n\t\t\t\t\t\t\t\t\t\t\t\tclass=\"flex items-start gap-3 rounded-lg border border-rose-400/40 bg-rose-400/10 px-3 py-2.5 text-brand-text\"\n\t\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t\t<span class=\"text-2xl leading-none\">🔇</span>\n\t\t\t\t\t\t\t\t\t\t\t\t<span class=\"flex min-w-0 flex-1 flex-col gap-0.5\">\n\t\t\t\t\t\t\t\t\t\t\t\t\t<span class=\"text-sm font-semibold text-rose-300\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t>Could not speak</span\n\t\t\t\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t\t\t{#if parsed.toolOutput}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t<span\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tclass=\"text-xs break-words text-brand-text-muted\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t>{parsed.toolOutput}</span\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t\t\t\t\t\t\t</span>\n\t\t\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t\t{:else if parsed.sayText}\n\t\t\t\t\t\t\t\t\t\t\t<div\n\t\t\t\t\t\t\t\t\t\t\t\tclass=\"flex items-start gap-3 rounded-lg border border-brand-cyan/40 bg-brand-cyan/10 px-3 py-2.5 text-brand-text\"\n\t\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t\t<span class=\"text-2xl leading-none\">🔊</span>\n\t\t\t\t\t\t\t\t\t\t\t\t<span class=\"flex min-w-0 flex-1 flex-col gap-1\">\n\t\t\t\t\t\t\t\t\t\t\t\t\t<span\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tclass=\"text-[11px] font-semibold tracking-wide text-brand-cyan uppercase select-none\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t>spoken:</span\n\t\t\t\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t\t\t<span class=\"text-sm break-words text-brand-text\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t>{parsed.sayText}</span\n\t\t\t\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t\t</span>\n\t\t\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t{:else}\n\t\t\t\t\t\t\t\t\t<div\n\t\t\t\t\t\t\t\t\t\tclass=\"flex max-w-full min-w-[280px] flex-col sm:min-w-[400px] md:min-w-[550px]\"\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t<!-- Header of tool execution. The collapse toggle (button) and an\n\t\t\t\t\t\t\t\t\t optional download link (anchor) are SIBLINGS in a flex row so\n\t\t\t\t\t\t\t\t\t the anchor is never nested inside the button. -->\n\t\t\t\t\t\t\t\t\t\t<div class=\"flex w-full items-center gap-1\">\n\t\t\t\t\t\t\t\t\t\t\t<button\n\t\t\t\t\t\t\t\t\t\t\t\tonclick={() => toggleMessage(msg.id, isExpanded)}\n\t\t\t\t\t\t\t\t\t\t\t\tclass=\"flex min-w-0 flex-1 items-center justify-between gap-3 rounded p-1 text-left transition-colors hover:bg-brand-surface-3/30 focus:outline-none\"\n\t\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t\t<div\n\t\t\t\t\t\t\t\t\t\t\t\t\tclass=\"flex flex-1 items-center gap-2 overflow-hidden\"\n\t\t\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t\t\t<!-- Status icon -->\n\t\t\t\t\t\t\t\t\t\t\t\t\t{#if msg.isStreaming}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t<!-- Running -->\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t<span\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tclass=\"inline-block animate-spin font-bold text-amber-400\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t>⚡</span\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t\t\t{:else if parsed.isError}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t<!-- Error -->\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t<span class=\"font-bold text-rose-400\" title=\"Failed\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t>❌</span\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t\t\t{:else if parsed.interrupted}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t<!-- Interrupted: no result (e.g. a CLI took over and the\n\t\t\t\t\t\t\t\t\t\t\t\t running tool was killed). Outcome unknown: neither\n\t\t\t\t\t\t\t\t\t\t\t\t success nor failure. -->\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t<span\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tclass=\"font-bold text-brand-text-muted\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttitle=\"Interrupted, no result (the running tool was stopped, e.g. by a CLI takeover)\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t>⊘</span\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t\t\t{:else}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t<!-- Success -->\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t<span\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tclass=\"font-bold text-emerald-400\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttitle=\"Succeeded\">✅</span\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t\t\t{/if}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t<span\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tclass=\"font-mono text-sm font-bold text-brand-text\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t{parsed.toolName}\n\t\t\t\t\t\t\t\t\t\t\t\t\t</span>\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t{#if parsed.smartTitleArgs}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t<span\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tclass=\"max-w-[180px] truncate font-mono text-xs text-brand-text-muted sm:max-w-[300px] md:max-w-[450px]\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttitle={parsed.smartTitleArgs}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{parsed.smartTitleArgs}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t</span>\n\t\t\t\t\t\t\t\t\t\t\t\t\t{/if}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t{#if toolDuration(msg, now)}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t<span\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tclass=\"shrink-0 font-mono text-xs tabular-nums {msg.isStreaming\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t? 'text-amber-400'\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t: 'text-brand-text-muted'}\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttitle={msg.isStreaming\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t? 'Elapsed time'\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t: 'Time taken'}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{msg.isStreaming ? 'Elapsed' : 'Took'}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{toolDuration(msg, now)}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t</span>\n\t\t\t\t\t\t\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t\t\t\t\t\t\t</div>\n\n\t\t\t\t\t\t\t\t\t\t\t\t<div\n\t\t\t\t\t\t\t\t\t\t\t\t\tclass=\"flex shrink-0 items-center gap-1 font-sans text-xs font-medium whitespace-nowrap text-brand-text-muted select-none hover:text-brand-text\"\n\t\t\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t\t\t{#if isExpanded}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tCollapse <span class=\"text-[10px]\">▲</span>\n\t\t\t\t\t\t\t\t\t\t\t\t\t{:else}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tExpand <span class=\"text-[10px]\">▼</span>\n\t\t\t\t\t\t\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t\t\t</button>\n\n\t\t\t\t\t\t\t\t\t\t\t{#if dlPath}\n\t\t\t\t\t\t\t\t\t\t\t\t{#if dlUrl}\n\t\t\t\t\t\t\t\t\t\t\t\t\t<a\n\t\t\t\t\t\t\t\t\t\t\t\t\t\thref={dlUrl}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tdownload={dlPath.split('/').pop() || ''}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tclass=\"flex shrink-0 items-center gap-1 rounded px-1.5 py-1 text-xs text-brand-cyan transition-colors hover:bg-brand-cyan/15\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\ttitle={`Download ${dlPath}`}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\taria-label={`Download ${dlPath}`}\n\t\t\t\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t<span class=\"text-sm\">⬇️</span>\n\t\t\t\t\t\t\t\t\t\t\t\t\t</a>\n\t\t\t\t\t\t\t\t\t\t\t\t{:else}\n\t\t\t\t\t\t\t\t\t\t\t\t\t<span\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tclass=\"shrink-0 px-1.5 py-1 text-xs text-brand-text-muted opacity-40\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\ttitle=\"No active session to download from\">⬇️</span\n\t\t\t\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t\t\t\t\t</div>\n\n\t\t\t\t\t\t\t\t\t\t<!-- Inline image preview from the DOWNLOAD URL (not embedded\n\t\t\t\t\t\t\t\t\t bytes), for a file-oriented tool (now only `read`) whose path\n\t\t\t\t\t\t\t\t\t is an image. Rendered OUTSIDE the collapsible section so it\n\t\t\t\t\t\t\t\t\t survives collapse, and tap-to-open + lazy-loaded. De-duped\n\t\t\t\t\t\t\t\t\t against the model-facing `msg.images` path below: when the\n\t\t\t\t\t\t\t\t\t tool result already embeds image blocks we render ONLY those,\n\t\t\t\t\t\t\t\t\t so a `read`-on-image shows exactly one preview. -->\n\t\t\t\t\t\t\t\t\t\t{#if !(msg.images && msg.images.length > 0) && dlUrl && dlKind === 'image'}\n\t\t\t\t\t\t\t\t\t\t\t<a\n\t\t\t\t\t\t\t\t\t\t\t\thref={dlUrl}\n\t\t\t\t\t\t\t\t\t\t\t\ttarget=\"_blank\"\n\t\t\t\t\t\t\t\t\t\t\t\trel=\"noopener noreferrer\"\n\t\t\t\t\t\t\t\t\t\t\t\tclass=\"mt-2 block\"\n\t\t\t\t\t\t\t\t\t\t\t\ttitle={`Open ${dlPath}`}\n\t\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t\t<img\n\t\t\t\t\t\t\t\t\t\t\t\t\tsrc={dlUrl}\n\t\t\t\t\t\t\t\t\t\t\t\t\talt={dlPath}\n\t\t\t\t\t\t\t\t\t\t\t\t\tloading=\"lazy\"\n\t\t\t\t\t\t\t\t\t\t\t\t\tclass=\"max-h-96 max-w-full rounded border border-brand-border/40 bg-brand-dark/60 object-contain\"\n\t\t\t\t\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t\t\t\t\t</a>\n\t\t\t\t\t\t\t\t\t\t{/if}\n\n\t\t\t\t\t\t\t\t\t\t<!-- Inline AUDIO player from the DOWNLOAD URL (not embedded\n\t\t\t\t\t\t\t\t\t bytes), for a file-oriented tool (now only `read`) whose path\n\t\t\t\t\t\t\t\t\t is audio. Rendered OUTSIDE the collapsible section so it\n\t\t\t\t\t\t\t\t\t survives collapse; `preload` metadata only. The download chip\n\t\t\t\t\t\t\t\t\t stays, so an unsupported format degrades gracefully to it. -->\n\t\t\t\t\t\t\t\t\t\t{#if dlUrl && dlKind === 'audio'}\n\t\t\t\t\t\t\t\t\t\t\t<audio\n\t\t\t\t\t\t\t\t\t\t\t\tcontrols\n\t\t\t\t\t\t\t\t\t\t\t\tpreload=\"metadata\"\n\t\t\t\t\t\t\t\t\t\t\t\tsrc={dlUrl}\n\t\t\t\t\t\t\t\t\t\t\t\ttitle={dlPath}\n\t\t\t\t\t\t\t\t\t\t\t\tclass=\"mt-2 block w-full max-w-full\"\n\t\t\t\t\t\t\t\t\t\t\t></audio>\n\t\t\t\t\t\t\t\t\t\t{/if}\n\n\t\t\t\t\t\t\t\t\t\t<!-- Inline VIDEO player from the DOWNLOAD URL (not embedded\n\t\t\t\t\t\t\t\t\t bytes), for a file-oriented tool (now only `read`) whose path\n\t\t\t\t\t\t\t\t\t is video. Rendered OUTSIDE the collapsible section so it\n\t\t\t\t\t\t\t\t\t survives collapse; `playsinline` keeps iOS inline; `preload`\n\t\t\t\t\t\t\t\t\t metadata only. The server honours HTTP Range so seeking works.\n\t\t\t\t\t\t\t\t\t The download chip stays, so an unsupported format degrades to\n\t\t\t\t\t\t\t\t\t it. -->\n\t\t\t\t\t\t\t\t\t\t{#if dlUrl && dlKind === 'video'}\n\t\t\t\t\t\t\t\t\t\t\t<video\n\t\t\t\t\t\t\t\t\t\t\t\tcontrols\n\t\t\t\t\t\t\t\t\t\t\t\tplaysinline\n\t\t\t\t\t\t\t\t\t\t\t\tpreload=\"metadata\"\n\t\t\t\t\t\t\t\t\t\t\t\tsrc={dlUrl}\n\t\t\t\t\t\t\t\t\t\t\t\ttitle={dlPath}\n\t\t\t\t\t\t\t\t\t\t\t\tclass=\"mt-2 block max-h-96 w-full max-w-full rounded border border-brand-border/40 bg-brand-dark/60\"\n\t\t\t\t\t\t\t\t\t\t\t></video>\n\t\t\t\t\t\t\t\t\t\t{/if}\n\n\t\t\t\t\t\t\t\t\t\t<!-- Tool image attachments (e.g. read on an image file) that\n\t\t\t\t\t\t\t\t\t ALSO produced model-facing image blocks (base64). Rendered\n\t\t\t\t\t\t\t\t\t OUTSIDE the collapsible section so images stay visible even\n\t\t\t\t\t\t\t\t\t when the tool details are collapsed; the args/output below\n\t\t\t\t\t\t\t\t\t remain collapsible. -->\n\t\t\t\t\t\t\t\t\t\t{#if msg.images && msg.images.length > 0}\n\t\t\t\t\t\t\t\t\t\t\t<div class=\"mt-2 flex flex-col gap-1\">\n\t\t\t\t\t\t\t\t\t\t\t\t<div class=\"flex flex-wrap gap-2\">\n\t\t\t\t\t\t\t\t\t\t\t\t\t{#each msg.images as img}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t<!-- Inline bytes, or a by-reference image loaded lazily\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t (and cached by the browser) from /session/tool-image. -->\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t{@const imgSrc = toolImageSrc(img)}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t{#if imgSrc}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t<a\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\thref={imgSrc}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttarget=\"_blank\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\trel=\"noopener noreferrer\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tclass=\"block\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t<img\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsrc={imgSrc}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\talt=\"Tool output\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tloading=\"lazy\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tclass=\"max-h-96 max-w-full rounded border border-brand-border/40 bg-brand-dark/60 object-contain\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t</a>\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t\t\t\t\t\t\t\t{/each}\n\t\t\t\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t\t{/if}\n\n\t\t\t\t\t\t\t\t\t\t<!-- Tool Output (collapsible) -->\n\t\t\t\t\t\t\t\t\t\t{#if isExpanded}\n\t\t\t\t\t\t\t\t\t\t\t<div\n\t\t\t\t\t\t\t\t\t\t\t\tclass=\"mt-2 flex flex-col gap-3 overflow-hidden border-t border-brand-border/40 pt-2\"\n\t\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t\t<!-- Full Arguments section -->\n\t\t\t\t\t\t\t\t\t\t\t\t{#if parsed.fullArgs && parsed.fullArgs !== '{}'}\n\t\t\t\t\t\t\t\t\t\t\t\t\t<div class=\"flex flex-col gap-1\">\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t<span\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tclass=\"font-sans text-[10px] font-bold tracking-wider text-brand-text-muted uppercase\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t>Arguments</span\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t<pre\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tclass=\"max-h-40 overflow-x-auto rounded border border-brand-border/30 bg-brand-dark/60 p-1.5 font-mono text-[11px] whitespace-pre-wrap text-amber-400\">{parsed.fullArgs}</pre>\n\t\t\t\t\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t\t\t\t{/if}\n\n\t\t\t\t\t\t\t\t\t\t\t\t<!-- Tool Output section -->\n\t\t\t\t\t\t\t\t\t\t\t\t<div class=\"flex flex-col gap-1\">\n\t\t\t\t\t\t\t\t\t\t\t\t\t<span\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tclass=\"font-sans text-[10px] font-bold tracking-wider text-brand-text-muted uppercase\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t>Output</span\n\t\t\t\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t\t\t{#if parsed.toolOutput}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t<pre\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tclass=\"max-h-96 overflow-x-auto rounded border border-brand-border/40 bg-brand-dark/60 p-2 font-mono text-xs whitespace-pre-wrap text-brand-text\">{parsed.toolOutput}</pre>\n\t\t\t\t\t\t\t\t\t\t\t\t\t{:else if msg.isStreaming}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t<div\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tclass=\"animate-pulse p-1 text-xs text-brand-text-muted italic\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tRunning and waiting for output...\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t\t\t\t\t{:else if parsed.interrupted}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t<div\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tclass=\"p-1 text-xs text-brand-text-muted italic\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tInterrupted before a result was returned (the\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\trunning tool was stopped, e.g. by a CLI takeover).\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tIts outcome is unknown.\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t\t\t\t\t{:else}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t<div\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tclass=\"p-1 text-xs text-brand-text-muted italic\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tNo output returned\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t{:else if msg.role === 'assistant' && msg.content !== ''}\n\t\t\t\t\t\t\t{#if msg.isStreaming}\n\t\t\t\t\t\t\t\t<!-- While streaming, render plain text. Re-parsing markdown on\n\t\t\t\t\t\t\t\t every token would rebuild the DOM and collapse any active\n\t\t\t\t\t\t\t\t selection; the finalized branch renders once and stays stable.\n\t\t\t\t\t\t\t\t `wrap-anywhere` mirrors `.markdown-body`'s overflow-wrap so an\n\t\t\t\t\t\t\t\t unbreakable token (a long file path, a URL) wraps instead of\n\t\t\t\t\t\t\t\t overflowing the bubble: without it the tail of such a line was\n\t\t\t\t\t\t\t\t pushed off-screen on a narrow viewport and read as \"words are\n\t\t\t\t\t\t\t\t missing\", until the message finalized and re-rendered wrapped. -->\n\t\t\t\t\t\t\t\t<pre\n\t\t\t\t\t\t\t\t\tclass=\"chat-selectable font-sans text-sm leading-relaxed wrap-anywhere whitespace-pre-wrap\">{msg.content}<span\n\t\t\t\t\t\t\t\t\t\tclass=\"ml-0.5 inline-block h-4 w-1.5 animate-pulse bg-brand-cyan align-text-bottom\"\n\t\t\t\t\t\t\t\t\t></span></pre>\n\t\t\t\t\t\t\t{:else}\n\t\t\t\t\t\t\t\t<!-- Conversation mode's collapseLongReplies knob: when ACTIVE\n\t\t\t\t\t\t\t\t (which requires the master conversationMode on too), a LONG\n\t\t\t\t\t\t\t\t written reply is DE-EMPHASISED so the short spoken summary is\n\t\t\t\t\t\t\t\t the focus and the transcript stays glanceable. Display-only:\n\t\t\t\t\t\t\t\t the full reply is NEVER removed/truncated -- it is clamped\n\t\t\t\t\t\t\t\t behind a fade and stays fully expandable via \"Show full reply\"\n\t\t\t\t\t\t\t\t (reusing the same expandedMessages idiom as the tool cards).\n\t\t\t\t\t\t\t\t Expanding is the reader's escape hatch: an opened reply renders\n\t\t\t\t\t\t\t\t in full and is never re-collapsed. With the knob inactive,\n\t\t\t\t\t\t\t\t replies render exactly as today. -->\n\t\t\t\t\t\t\t\t{@const replyExpanded = expandedMessages[msg.id] === true}\n\t\t\t\t\t\t\t\t{@const replyCollapsed = shouldCollapseReply({\n\t\t\t\t\t\t\t\t\tactive: collapseActive,\n\t\t\t\t\t\t\t\t\texpanded: replyExpanded,\n\t\t\t\t\t\t\t\t\tcontent: msg.content,\n\t\t\t\t\t\t\t\t})}\n\t\t\t\t\t\t\t\t{@const showRaw = rawMessages[msg.id] === true}\n\t\t\t\t\t\t\t\t<div class=\"group flex flex-col\">\n\t\t\t\t\t\t\t\t\t{#if showRaw}\n\t\t\t\t\t\t\t\t\t\t<!-- Raw view: the verbatim markdown source, unrendered. -->\n\t\t\t\t\t\t\t\t\t\t<pre\n\t\t\t\t\t\t\t\t\t\t\tclass=\"chat-selectable overflow-x-auto rounded border border-brand-border/40 bg-brand-dark/60 p-2 font-mono text-xs whitespace-pre-wrap text-brand-text {replyCollapsed\n\t\t\t\t\t\t\t\t\t\t\t\t? 'relative max-h-40 overflow-hidden [mask-image:linear-gradient(to_bottom,black_60%,transparent)] opacity-80'\n\t\t\t\t\t\t\t\t\t\t\t\t: ''}\">{msg.content}</pre>\n\t\t\t\t\t\t\t\t\t{:else}\n\t\t\t\t\t\t\t\t\t\t<!-- eslint-disable-next-line svelte/no-at-html-tags -- output sanitized via DOMPurify in renderMarkdown -->\n\t\t\t\t\t\t\t\t\t\t<div\n\t\t\t\t\t\t\t\t\t\t\tclass=\"chat-selectable markdown-body text-sm leading-relaxed {replyCollapsed\n\t\t\t\t\t\t\t\t\t\t\t\t? 'relative max-h-40 overflow-hidden [mask-image:linear-gradient(to_bottom,black_60%,transparent)] opacity-80'\n\t\t\t\t\t\t\t\t\t\t\t\t: ''}\"\n\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t{@html renderAssistant(msg.id, msg.content)}\n\t\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t\t\t\t<!-- Per-message actions: copy the raw markdown, and toggle\n\t\t\t\t\t\t\t\t\t between the rendered view and the raw source. Kept subtle\n\t\t\t\t\t\t\t\t\t (muted, revealed on hover) so they don't clutter the\n\t\t\t\t\t\t\t\t\t transcript. -->\n\t\t\t\t\t\t\t\t\t<div\n\t\t\t\t\t\t\t\t\t\tclass=\"mt-1 flex items-center gap-1 opacity-0 transition-opacity group-hover:opacity-100 focus-within:opacity-100\"\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t<button\n\t\t\t\t\t\t\t\t\t\t\ttype=\"button\"\n\t\t\t\t\t\t\t\t\t\t\tonclick={() => copyMessage(msg.id, msg.content)}\n\t\t\t\t\t\t\t\t\t\t\tclass=\"flex items-center gap-1 rounded px-1.5 py-0.5 text-xs font-medium text-brand-text-muted transition-colors select-none hover:bg-brand-surface-3/30 hover:text-brand-text\"\n\t\t\t\t\t\t\t\t\t\t\ttitle=\"Copy this message to the clipboard\"\n\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t{#if copiedMessageId === msg.id}\n\t\t\t\t\t\t\t\t\t\t\t\t<svg\n\t\t\t\t\t\t\t\t\t\t\t\t\txmlns=\"http://www.w3.org/2000/svg\"\n\t\t\t\t\t\t\t\t\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\t\t\t\t\t\t\t\t\tfill=\"none\"\n\t\t\t\t\t\t\t\t\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\t\t\t\t\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\t\t\t\t\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\t\t\t\t\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t\t\t\t\t\t\t\t\t\tclass=\"text-brand-green h-3.5 w-3.5\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t><path d=\"M20 6 9 17l-5-5\" /></svg\n\t\t\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t\tCopied\n\t\t\t\t\t\t\t\t\t\t\t{:else}\n\t\t\t\t\t\t\t\t\t\t\t\t<svg\n\t\t\t\t\t\t\t\t\t\t\t\t\txmlns=\"http://www.w3.org/2000/svg\"\n\t\t\t\t\t\t\t\t\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\t\t\t\t\t\t\t\t\tfill=\"none\"\n\t\t\t\t\t\t\t\t\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\t\t\t\t\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\t\t\t\t\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\t\t\t\t\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t\t\t\t\t\t\t\t\t\tclass=\"h-3.5 w-3.5\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t><rect\n\t\t\t\t\t\t\t\t\t\t\t\t\t\twidth=\"14\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\theight=\"14\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tx=\"8\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\ty=\"8\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\trx=\"2\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\try=\"2\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t/><path\n\t\t\t\t\t\t\t\t\t\t\t\t\t\td=\"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t/></svg\n\t\t\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t\tCopy\n\t\t\t\t\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t\t\t\t\t</button>\n\t\t\t\t\t\t\t\t\t\t<button\n\t\t\t\t\t\t\t\t\t\t\ttype=\"button\"\n\t\t\t\t\t\t\t\t\t\t\tonclick={() => toggleRaw(msg.id)}\n\t\t\t\t\t\t\t\t\t\t\tclass=\"flex items-center gap-1 rounded px-1.5 py-0.5 text-xs font-medium text-brand-text-muted transition-colors select-none hover:bg-brand-surface-3/30 hover:text-brand-text\"\n\t\t\t\t\t\t\t\t\t\t\ttitle={showRaw\n\t\t\t\t\t\t\t\t\t\t\t\t? 'Show the rendered markdown'\n\t\t\t\t\t\t\t\t\t\t\t\t: 'Show the raw markdown source'}\n\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t{#if showRaw}\n\t\t\t\t\t\t\t\t\t\t\t\t<svg\n\t\t\t\t\t\t\t\t\t\t\t\t\txmlns=\"http://www.w3.org/2000/svg\"\n\t\t\t\t\t\t\t\t\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\t\t\t\t\t\t\t\t\tfill=\"none\"\n\t\t\t\t\t\t\t\t\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\t\t\t\t\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\t\t\t\t\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\t\t\t\t\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t\t\t\t\t\t\t\t\t\tclass=\"h-3.5 w-3.5\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t><path\n\t\t\t\t\t\t\t\t\t\t\t\t\t\td=\"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t/><circle cx=\"12\" cy=\"12\" r=\"3\" /></svg\n\t\t\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t\tRendered\n\t\t\t\t\t\t\t\t\t\t\t{:else}\n\t\t\t\t\t\t\t\t\t\t\t\t<svg\n\t\t\t\t\t\t\t\t\t\t\t\t\txmlns=\"http://www.w3.org/2000/svg\"\n\t\t\t\t\t\t\t\t\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\t\t\t\t\t\t\t\t\tfill=\"none\"\n\t\t\t\t\t\t\t\t\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\t\t\t\t\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\t\t\t\t\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\t\t\t\t\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t\t\t\t\t\t\t\t\t\tclass=\"h-3.5 w-3.5\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t><path d=\"m18 16 4-4-4-4\" /><path\n\t\t\t\t\t\t\t\t\t\t\t\t\t\td=\"m6 8-4 4 4 4\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t/><path d=\"m14.5 4-5 16\" /></svg\n\t\t\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t\tRaw\n\t\t\t\t\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t\t\t\t\t</button>\n\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t{#if replyCollapsed}\n\t\t\t\t\t\t\t\t\t\t<button\n\t\t\t\t\t\t\t\t\t\t\ttype=\"button\"\n\t\t\t\t\t\t\t\t\t\t\tonclick={() => toggleMessage(msg.id, replyExpanded)}\n\t\t\t\t\t\t\t\t\t\t\tclass=\"mt-1 flex w-fit items-center gap-1 rounded px-1.5 py-0.5 text-xs font-medium text-brand-text-muted transition-colors select-none hover:bg-brand-surface-3/30 hover:text-brand-text\"\n\t\t\t\t\t\t\t\t\t\t\ttitle=\"Show the full written reply (collapsed while conversation mode focuses the spoken summary)\"\n\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\tShow full reply <span class=\"text-[10px]\">▼</span>\n\t\t\t\t\t\t\t\t\t\t</button>\n\t\t\t\t\t\t\t\t\t{:else if collapseActive && replyExpanded && isLongReply(msg.content)}\n\t\t\t\t\t\t\t\t\t\t<button\n\t\t\t\t\t\t\t\t\t\t\ttype=\"button\"\n\t\t\t\t\t\t\t\t\t\t\tonclick={() => toggleMessage(msg.id, replyExpanded)}\n\t\t\t\t\t\t\t\t\t\t\tclass=\"mt-1 flex w-fit items-center gap-1 rounded px-1.5 py-0.5 text-xs font-medium text-brand-text-muted transition-colors select-none hover:bg-brand-surface-3/30 hover:text-brand-text\"\n\t\t\t\t\t\t\t\t\t\t\ttitle=\"Collapse this long reply again\"\n\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\tCollapse <span class=\"text-[10px]\">▲</span>\n\t\t\t\t\t\t\t\t\t\t</button>\n\t\t\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t{:else}\n\t\t\t\t\t\t\t{@const parsedUserMsg = parseUserMessage(msg.content)}\n\t\t\t\t\t\t\t{#if parsedUserMsg.skill}\n\t\t\t\t\t\t\t\t<!-- A `/skill:<name> <args>` invocation. The message is stored/\n\t\t\t\t\t\t\t\t echoed EXPANDED (the full skill body). Display the compact\n\t\t\t\t\t\t\t\t invocation instead: a skill chip with the skill name, plus the\n\t\t\t\t\t\t\t\t trailing args the user typed after the skill name (if any). -->\n\t\t\t\t\t\t\t\t<div class=\"chat-selectable flex flex-col gap-1.5\">\n\t\t\t\t\t\t\t\t\t<span\n\t\t\t\t\t\t\t\t\t\tclass=\"inline-flex w-fit items-center gap-1.5 rounded bg-brand-blue/25 px-2 py-0.5 font-mono text-xs font-medium text-brand-text ring-1 ring-brand-blue/40\"\n\t\t\t\t\t\t\t\t\t\ttitle=\"Skill invocation (expanded for the agent)\"\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t<svg\n\t\t\t\t\t\t\t\t\t\t\txmlns=\"http://www.w3.org/2000/svg\"\n\t\t\t\t\t\t\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\t\t\t\t\t\t\tfill=\"none\"\n\t\t\t\t\t\t\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\t\t\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\t\t\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\t\t\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t\t\t\t\t\t\t\tclass=\"h-3.5 w-3.5\"\n\t\t\t\t\t\t\t\t\t\t\t><path d=\"M13 2 3 14h7l-1 8 10-12h-7l1-8z\" /></svg\n\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t<span>skill:{parsedUserMsg.skill.skillName}</span>\n\t\t\t\t\t\t\t\t\t</span>\n\t\t\t\t\t\t\t\t\t{#if parsedUserMsg.skill.args}\n\t\t\t\t\t\t\t\t\t\t<div\n\t\t\t\t\t\t\t\t\t\t\tclass=\"text-sm leading-relaxed wrap-anywhere whitespace-pre-wrap\"\n\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t{parsedUserMsg.skill.args}\n\t\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t{:else}\n\t\t\t\t\t\t\t\t<!-- User + thinking bubbles are plain text too: same wrap-anywhere\n\t\t\t\t\t\t\t\t guard so a long path/URL cannot push the rest of the line out of\n\t\t\t\t\t\t\t\t the bubble. -->\n\t\t\t\t\t\t\t\t<div\n\t\t\t\t\t\t\t\t\tclass=\"chat-selectable text-sm leading-relaxed wrap-anywhere whitespace-pre-wrap\"\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t{#if parsedUserMsg.cleanContent}\n\t\t\t\t\t\t\t\t\t\t{@const userHtml = renderUser(parsedUserMsg.cleanContent)}\n\t\t\t\t\t\t\t\t\t\t{#if userHtml}\n\t\t\t\t\t\t\t\t\t\t\t<!-- eslint-disable-next-line svelte/no-at-html-tags -- sanitized via DOMPurify in linkifyText -->\n\t\t\t\t\t\t\t\t\t\t\t<span>{@html userHtml}</span>\n\t\t\t\t\t\t\t\t\t\t{:else}\n\t\t\t\t\t\t\t\t\t\t\t{parsedUserMsg.cleanContent}\n\t\t\t\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t\t\t\t{:else if parsedUserMsg.attachments.length > 0}\n\t\t\t\t\t\t\t\t\t\t<span class=\"text-brand-text-muted italic\"\n\t\t\t\t\t\t\t\t\t\t\t>Shared file{parsedUserMsg.attachments.length > 1\n\t\t\t\t\t\t\t\t\t\t\t\t? 's'\n\t\t\t\t\t\t\t\t\t\t\t\t: ''} with agent:</span\n\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t{:else}\n\t\t\t\t\t\t\t\t\t\t{msg.content || (msg.isStreaming ? 'Thinking...' : '')}\n\t\t\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t\t\t\t{#if msg.isStreaming && streaming}\n\t\t\t\t\t\t\t\t\t\t<span\n\t\t\t\t\t\t\t\t\t\t\tclass=\"ml-1 inline-block h-4 w-1.5 animate-pulse bg-brand-cyan\"\n\t\t\t\t\t\t\t\t\t\t></span>\n\t\t\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t\t{#if parsedUserMsg.attachments.length > 0}\n\t\t\t\t\t\t\t\t<div\n\t\t\t\t\t\t\t\t\tclass=\"mt-2 flex flex-col gap-1 border-t border-brand-blue/20 pt-2\"\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t{#each parsedUserMsg.attachments as filePath}\n\t\t\t\t\t\t\t\t\t\t<div\n\t\t\t\t\t\t\t\t\t\t\tclass=\"flex items-center gap-1.5 rounded bg-brand-blue/20 px-2 py-1 font-mono text-xs text-brand-text select-all\"\n\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t<span>📎</span>\n\t\t\t\t\t\t\t\t\t\t\t<span class=\"truncate\" title={filePath}>{filePath}</span>\n\t\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t{/each}\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t{#if msg.role !== 'thinking' && msg.role !== 'tool'}\n\t\t\t\t\t\t\t<div\n\t\t\t\t\t\t\t\tclass=\"mt-1 flex items-center gap-1.5 text-xs opacity-50 {msg.role ===\n\t\t\t\t\t\t\t\t'user'\n\t\t\t\t\t\t\t\t\t? 'justify-end text-brand-text-muted'\n\t\t\t\t\t\t\t\t\t: msg.role === 'assistant'\n\t\t\t\t\t\t\t\t\t\t? 'text-brand-purple'\n\t\t\t\t\t\t\t\t\t\t: 'text-brand-text-muted'}\"\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t{#if msg.role === 'user' && msg.delivery === 'sending'}\n\t\t\t\t\t\t\t\t\t<span\n\t\t\t\t\t\t\t\t\t\tclass=\"inline-block h-3 w-3 animate-spin rounded-full border border-brand-text-muted border-t-transparent\"\n\t\t\t\t\t\t\t\t\t\ttitle=\"Sending, awaiting confirmation\"\n\t\t\t\t\t\t\t\t\t\taria-label=\"Sending\"\n\t\t\t\t\t\t\t\t\t></span>\n\t\t\t\t\t\t\t\t\t<span title=\"Sending, awaiting confirmation\">Sending</span>\n\t\t\t\t\t\t\t\t\t<span>·</span>\n\t\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t\t\t{formatTime(msg.timestamp)}\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t{#if msg.role === 'user' && msg.entryId && sessionInfo.sessionId && !readOnly && msg.delivery === undefined && !$pendingSteering.includes(msg.content)}\n\t\t\t\t\t\t\t\t<!-- Fork-from-here lives OUTSIDE the opacity-50 footer above, so it is\n\t\t\t\t\t\t\t\t fully opaque and its hover state is clearly visible (a parent\n\t\t\t\t\t\t\t\t opacity would otherwise cap the child's hover:opacity-100). -->\n\t\t\t\t\t\t\t\t<div class=\"mt-1 flex justify-end\">\n\t\t\t\t\t\t\t\t\t<button\n\t\t\t\t\t\t\t\t\t\ttype=\"button\"\n\t\t\t\t\t\t\t\t\t\tonclick={() => handleFork(msg.entryId)}\n\t\t\t\t\t\t\t\t\t\tclass=\"inline-flex items-center gap-1 rounded border border-brand-border/60 bg-brand-surface-3/60 px-2 py-0.5 text-xs font-medium text-brand-text-muted transition-colors hover:border-brand-blue hover:bg-brand-blue/15 hover:text-brand-blue\"\n\t\t\t\t\t\t\t\t\t\ttitle=\"Fork the conversation from this message (edit and resend)\"\n\t\t\t\t\t\t\t\t\t\taria-label=\"Fork from this message\"\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t<svg\n\t\t\t\t\t\t\t\t\t\t\txmlns=\"http://www.w3.org/2000/svg\"\n\t\t\t\t\t\t\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\t\t\t\t\t\t\tfill=\"none\"\n\t\t\t\t\t\t\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\t\t\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\t\t\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\t\t\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t\t\t\t\t\t\t\tclass=\"h-3.5 w-3.5\"\n\t\t\t\t\t\t\t\t\t\t\t><circle cx=\"6\" cy=\"6\" r=\"2.2\" /><circle\n\t\t\t\t\t\t\t\t\t\t\t\tcx=\"6\"\n\t\t\t\t\t\t\t\t\t\t\t\tcy=\"18\"\n\t\t\t\t\t\t\t\t\t\t\t\tr=\"2.2\"\n\t\t\t\t\t\t\t\t\t\t\t/><circle cx=\"18\" cy=\"8\" r=\"2.2\" /><path\n\t\t\t\t\t\t\t\t\t\t\t\td=\"M6 8.2v7.6\"\n\t\t\t\t\t\t\t\t\t\t\t/><path d=\"M18 10.2c0 3-3 3.8-6 3.8\" /></svg\n\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\tFork\n\t\t\t\t\t\t\t\t\t</button>\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t\t{#if msg.role === 'user' && $pendingSteering.includes(msg.content)}\n\t\t\t\t\t\t\t\t<!-- This user message is a mid-stream steer that is still QUEUED on\n\t\t\t\t\t\t\t\t the server (pi injects it at the next step boundary). Show a\n\t\t\t\t\t\t\t\t passive per-message badge so the user can SEE which messages are\n\t\t\t\t\t\t\t\t still pending. The cancel ACTION lives at the session level (next\n\t\t\t\t\t\t\t\t to Abort), because pi's clearQueue() drops the WHOLE steer queue\n\t\t\t\t\t\t\t\t at once -- a per-message Cancel would misleadingly imply it only\n\t\t\t\t\t\t\t\t cancels this one. Only server-type sessions report a steer queue,\n\t\t\t\t\t\t\t\t so this never appears for CLI-bridge sessions. -->\n\t\t\t\t\t\t\t\t<div\n\t\t\t\t\t\t\t\t\tclass=\"mt-1.5 flex items-center justify-end gap-1 text-xs font-medium text-brand-text-muted\"\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t<span\n\t\t\t\t\t\t\t\t\t\tclass=\"inline-block h-1.5 w-1.5 animate-pulse rounded-full bg-amber-400\"\n\t\t\t\t\t\t\t\t\t></span>\n\t\t\t\t\t\t\t\t\tQueued (not yet sent to the agent)\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t\t{#if msg.role === 'user' && msg.delivery === 'failed'}\n\t\t\t\t\t\t\t\t<!-- Delivery could NOT be confirmed (a half-open socket may have\n\t\t\t\t\t\t\t\t swallowed the frame). Never silently drop it: offer retry /\n\t\t\t\t\t\t\t\t discard so the user's text is recoverable. -->\n\t\t\t\t\t\t\t\t<div\n\t\t\t\t\t\t\t\t\tclass=\"mt-1.5 flex flex-wrap items-center justify-end gap-2 text-xs\"\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t<span class=\"font-medium text-amber-400\"\n\t\t\t\t\t\t\t\t\t\t>⚠️ Not delivered</span\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t<button\n\t\t\t\t\t\t\t\t\t\ttype=\"button\"\n\t\t\t\t\t\t\t\t\t\tonclick={() => resendMessage(msg.id)}\n\t\t\t\t\t\t\t\t\t\tclass=\"rounded bg-brand-blue/80 px-2 py-0.5 font-medium text-brand-text transition-colors hover:bg-brand-blue\"\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\tRetry\n\t\t\t\t\t\t\t\t\t</button>\n\t\t\t\t\t\t\t\t\t<button\n\t\t\t\t\t\t\t\t\t\ttype=\"button\"\n\t\t\t\t\t\t\t\t\t\tonclick={() => discardMessage(msg.id)}\n\t\t\t\t\t\t\t\t\t\tclass=\"rounded bg-brand-surface-3 px-2 py-0.5 font-medium text-brand-text-muted transition-colors hover:text-brand-text\"\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\tDiscard\n\t\t\t\t\t\t\t\t\t</button>\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t{/if}\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n\t\t\t{/each}\n\t\t</div>\n\t{/if}\n\n\t<div\n\t\tclass=\"app-chrome flex flex-wrap items-center justify-between gap-x-4 gap-y-2 border-t border-brand-border p-2\"\n\t>\n\t\t<div class=\"flex flex-wrap items-center gap-x-4 gap-y-2\">\n\t\t\t<label\n\t\t\t\tclass=\"flex cursor-pointer items-center gap-1.5 text-xs text-brand-text-muted select-none hover:text-brand-text\"\n\t\t\t>\n\t\t\t\t<input\n\t\t\t\t\ttype=\"checkbox\"\n\t\t\t\t\tchecked={$piState.hideThinking}\n\t\t\t\t\tonchange={(e) =>\n\t\t\t\t\t\tupdateConfig({\n\t\t\t\t\t\t\thideThinking: (e.currentTarget as HTMLInputElement).checked,\n\t\t\t\t\t\t})}\n\t\t\t\t\tclass=\"h-3.5 w-3.5 rounded border-brand-border bg-brand-surface-3 text-brand-blue focus:ring-brand-blue\"\n\t\t\t\t/>\n\t\t\t\tHide Thinking\n\t\t\t</label>\n\n\t\t\t<!-- Per-session waiting-for-human beep, tri-state. Cycles\n\t\t\t Default -> On -> Off -> Default. \"Default\" means this session has no\n\t\t\t explicit choice and follows the global default live; On/Off stick to\n\t\t\t this session regardless of later default changes. Only for a live,\n\t\t\t drivable session. -->\n\t\t\t{#if sessionInfo.sessionFile && !$isReadOnly}\n\t\t\t\t<button\n\t\t\t\t\ttype=\"button\"\n\t\t\t\t\tonclick={cycleBeep}\n\t\t\t\t\tclass=\"flex items-center gap-1.5 rounded px-1.5 py-0.5 text-xs select-none hover:text-brand-text {beepOverride ===\n\t\t\t\t\tundefined\n\t\t\t\t\t\t? 'text-brand-text-muted'\n\t\t\t\t\t\t: 'text-brand-blue'}\"\n\t\t\t\t\ttitle={beepOverride === undefined\n\t\t\t\t\t\t? `Beep when the agent is waiting: following the default (${beepOn ? 'on' : 'off'}). Click to set On for this session.`\n\t\t\t\t\t\t: beepOverride === true\n\t\t\t\t\t\t\t? 'Beep when the agent is waiting: ON for this session. Click to set Off.'\n\t\t\t\t\t\t\t: 'Beep when the agent is waiting: OFF for this session. Click to follow the default.'}\n\t\t\t\t\taria-label=\"Cycle waiting-for-human beep for this session\"\n\t\t\t\t>\n\t\t\t\t\t<span>{beepOn ? '🔔' : '🔕'}</span>\n\t\t\t\t\t<span>\n\t\t\t\t\t\t{beepOverride === undefined\n\t\t\t\t\t\t\t? `Beep: Default (${beepOn ? 'on' : 'off'})`\n\t\t\t\t\t\t\t: beepOverride\n\t\t\t\t\t\t\t\t? 'Beep: On'\n\t\t\t\t\t\t\t\t: 'Beep: Off'}\n\t\t\t\t\t</span>\n\t\t\t\t</button>\n\t\t\t{/if}\n\n\t\t\t<!-- Conversation Mode master toggle: flips the configured knob bundle on\n\t\t\t at once (speak replies, collapse long replies, hands-free mic re-open)\n\t\t\t FOR THIS CONVERSATION ONLY -- other conversations keep their own state,\n\t\t\t and untouched ones follow the default. With no conversation open there is\n\t\t\t nothing to scope to, so it edits that default instead. Individual knobs\n\t\t\t (and the default) are edited in Connection Settings. -->\n\t\t\t<button\n\t\t\t\ttype=\"button\"\n\t\t\t\tonclick={toggleConversationMode}\n\t\t\t\tclass=\"flex items-center gap-1.5 rounded px-1.5 py-0.5 text-xs select-none hover:text-brand-text {conversationOn\n\t\t\t\t\t? 'text-brand-blue'\n\t\t\t\t\t: 'text-brand-text-muted'}\"\n\t\t\t\ttitle={`Conversation Mode for THIS conversation: ${\n\t\t\t\t\tconversationOn ? 'ON' : 'OFF'\n\t\t\t\t}${\n\t\t\t\t\tconversationFollowsDefault\n\t\t\t\t\t\t? ' (following your default)'\n\t\t\t\t\t\t: ' (set for this conversation)'\n\t\t\t\t}. ${\n\t\t\t\t\tconversationOn\n\t\t\t\t\t\t? 'Click to turn it off here (the configured knobs go dormant); other conversations are unaffected.'\n\t\t\t\t\t\t: 'Click to flip your configured bundle of speech/voice knobs on here; other conversations are unaffected.'\n\t\t\t\t} The default for conversations you have not toggled is in Connection Settings.`}\n\t\t\t\taria-label=\"Toggle conversation mode\"\n\t\t\t>\n\t\t\t\t<span>{conversationOn ? '🗣️' : '💬'}</span>\n\t\t\t\t<span>{conversationOn ? 'Conversation: On' : 'Conversation: Off'}</span>\n\t\t\t</button>\n\n\t\t\t<!-- Context-window usage, e.g. \"11.3% / 1.0M\" -->\n\t\t\t{#if contextLabel}\n\t\t\t\t<div\n\t\t\t\t\tclass=\"flex items-center gap-1 text-xs text-brand-text-muted\"\n\t\t\t\t\ttitle={$piState.contextUsage?.tokens != null\n\t\t\t\t\t\t? `${$piState.contextUsage.tokens.toLocaleString()} context tokens of ${$piState.contextUsage.contextWindow.toLocaleString()}`\n\t\t\t\t\t\t: 'Context window size'}\n\t\t\t\t>\n\t\t\t\t\t<span class=\"flex-shrink-0\">🧠</span>\n\t\t\t\t\t<span class=\"whitespace-nowrap tabular-nums\">{contextLabel}</span>\n\t\t\t\t</div>\n\t\t\t{/if}\n\t\t</div>\n\t\t<div class=\"flex items-center gap-2\">\n\t\t\t<!-- Cancel ALL queued steers without aborting the running turn. pi's\n\t\t\t clearQueue() is all-or-nothing, so this is a single session-level\n\t\t\t action (not per-message). Shown only when something is queued. -->\n\t\t\t{#if $pendingSteering.length > 0}\n\t\t\t\t<button\n\t\t\t\t\tonclick={cancelSteer}\n\t\t\t\t\tclass=\"rounded border border-amber-400/50 bg-brand-surface-3 px-3 py-1.5 text-xs text-brand-text-muted transition-colors hover:bg-rose-500/80 hover:text-brand-text\"\n\t\t\t\t\ttitle=\"Cancel the queued steer message{$pendingSteering.length > 1\n\t\t\t\t\t\t? 's'\n\t\t\t\t\t\t: ''} (does not abort the current turn)\"\n\t\t\t\t>\n\t\t\t\t\tCancel queued{$pendingSteering.length > 1\n\t\t\t\t\t\t? ` (${$pendingSteering.length})`\n\t\t\t\t\t\t: ''}\n\t\t\t\t</button>\n\t\t\t{/if}\n\t\t\t<button\n\t\t\t\tonclick={abort}\n\t\t\t\tdisabled={!streaming}\n\t\t\t\tclass=\"rounded bg-rose-500 px-3 py-1.5 text-xs text-brand-text transition-colors hover:bg-rose-600 disabled:cursor-not-allowed disabled:opacity-50\"\n\t\t\t\ttitle=\"Abort\"\n\t\t\t>\n\t\t\t\tAbort\n\t\t\t</button>\n\t\t</div>\n\t</div>\n\n\t<!-- Custom Confirm Modal for Existing Folders -->\n\t{#if showGitInitConfirmModal}\n\t\t<div\n\t\t\tclass=\"fixed inset-0 z-50 flex items-center justify-center bg-brand-dark/65 p-4\"\n\t\t\trole=\"dialog\"\n\t\t\taria-modal=\"true\"\n\t\t>\n\t\t\t<div\n\t\t\t\tclass=\"w-full max-w-sm rounded-lg border border-brand-border bg-brand-surface-2 p-6 text-brand-text\"\n\t\t\t>\n\t\t\t\t<h3 class=\"mb-2 text-base font-bold text-brand-text\">\n\t\t\t\t\tFolder Already Exists\n\t\t\t\t</h3>\n\t\t\t\t<p class=\"mb-4 text-sm text-brand-text-muted\">\n\t\t\t\t\tThe folder <span class=\"font-mono text-xs text-brand-text\"\n\t\t\t\t\t\t>{newFolderCwd}</span\n\t\t\t\t\t> already exists. Do you want to initialize a Git repository in it?\n\t\t\t\t</p>\n\n\t\t\t\t<div class=\"mb-6 flex flex-col gap-3.5\">\n\t\t\t\t\t<div class=\"flex items-center gap-2\">\n\t\t\t\t\t\t<input\n\t\t\t\t\t\t\tid=\"modal-git-init\"\n\t\t\t\t\t\t\ttype=\"checkbox\"\n\t\t\t\t\t\t\tbind:checked={newFolderGitInit}\n\t\t\t\t\t\t\tdisabled={pathStatus.isGit}\n\t\t\t\t\t\t\tclass=\"h-4 w-4 rounded border-brand-border bg-brand-surface-3 text-brand-blue focus:ring-brand-blue disabled:opacity-50\"\n\t\t\t\t\t\t/>\n\t\t\t\t\t\t<label\n\t\t\t\t\t\t\tfor=\"modal-git-init\"\n\t\t\t\t\t\t\tclass=\"cursor-pointer text-sm text-brand-text select-none disabled:opacity-50\"\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\tInitialize Git repository\n\t\t\t\t\t\t\t{#if pathStatus.isGit}\n\t\t\t\t\t\t\t\t<span class=\"ml-1 text-xs text-brand-text-muted\"\n\t\t\t\t\t\t\t\t\t>(already a Git repository)</span\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t{:else}\n\t\t\t\t\t\t\t\t<span class=\"ml-1 text-xs font-medium text-yellow-500\"\n\t\t\t\t\t\t\t\t\t>(folder not empty)</span\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t</label>\n\t\t\t\t\t</div>\n\n\t\t\t\t\t{#if pathStatus.matchingRule}\n\t\t\t\t\t\t<div class=\"space-y-1.5\">\n\t\t\t\t\t\t\t<div class=\"flex items-center gap-2\">\n\t\t\t\t\t\t\t\t<input\n\t\t\t\t\t\t\t\t\tid=\"modal-create-remote\"\n\t\t\t\t\t\t\t\t\ttype=\"checkbox\"\n\t\t\t\t\t\t\t\t\tbind:checked={createRemoteRepo}\n\t\t\t\t\t\t\t\t\tclass=\"h-4 w-4 rounded border-brand-border bg-brand-surface-3 text-brand-blue focus:ring-brand-blue\"\n\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t\t<label\n\t\t\t\t\t\t\t\t\tfor=\"modal-create-remote\"\n\t\t\t\t\t\t\t\t\tclass=\"cursor-pointer text-sm text-brand-text select-none\"\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\tCreate remote {pathStatus.matchingRule.provider} repository\n\t\t\t\t\t\t\t\t</label>\n\t\t\t\t\t\t\t</div>\n\n\t\t\t\t\t\t\t{#if createRemoteRepo}\n\t\t\t\t\t\t\t\t<div\n\t\t\t\t\t\t\t\t\tclass=\"flex items-center gap-4 pl-6 text-xs text-brand-text-muted\"\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t<span>Visibility:</span>\n\t\t\t\t\t\t\t\t\t<label\n\t\t\t\t\t\t\t\t\t\tclass=\"flex cursor-pointer items-center gap-1.5 transition-colors select-none hover:text-brand-text\"\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t<input\n\t\t\t\t\t\t\t\t\t\t\ttype=\"radio\"\n\t\t\t\t\t\t\t\t\t\t\tname=\"modal-visibility\"\n\t\t\t\t\t\t\t\t\t\t\tvalue=\"private\"\n\t\t\t\t\t\t\t\t\t\t\tbind:group={repoVisibility}\n\t\t\t\t\t\t\t\t\t\t\tclass=\"border-brand-border bg-brand-surface-3 text-brand-blue focus:ring-brand-blue\"\n\t\t\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t\t\t\tPrivate\n\t\t\t\t\t\t\t\t\t</label>\n\t\t\t\t\t\t\t\t\t<label\n\t\t\t\t\t\t\t\t\t\tclass=\"flex cursor-pointer items-center gap-1.5 transition-colors select-none hover:text-brand-text\"\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t<input\n\t\t\t\t\t\t\t\t\t\t\ttype=\"radio\"\n\t\t\t\t\t\t\t\t\t\t\tname=\"modal-visibility\"\n\t\t\t\t\t\t\t\t\t\t\tvalue=\"public\"\n\t\t\t\t\t\t\t\t\t\t\tbind:group={repoVisibility}\n\t\t\t\t\t\t\t\t\t\t\tclass=\"border-brand-border bg-brand-surface-3 text-brand-blue focus:ring-brand-blue\"\n\t\t\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t\t\t\tPublic\n\t\t\t\t\t\t\t\t\t</label>\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t</div>\n\t\t\t\t\t{/if}\n\t\t\t\t</div>\n\n\t\t\t\t<div class=\"flex justify-end gap-2.5\">\n\t\t\t\t\t<button\n\t\t\t\t\t\ttype=\"button\"\n\t\t\t\t\t\tonclick={() => (showGitInitConfirmModal = false)}\n\t\t\t\t\t\tclass=\"rounded bg-brand-surface-3 px-3.5 py-1.5 text-xs font-semibold text-brand-text transition-colors hover:bg-brand-surface-2\"\n\t\t\t\t\t>\n\t\t\t\t\t\tCancel\n\t\t\t\t\t</button>\n\t\t\t\t\t<button\n\t\t\t\t\t\ttype=\"button\"\n\t\t\t\t\t\tonclick={() => {\n\t\t\t\t\t\t\tshowGitInitConfirmModal = false;\n\t\t\t\t\t\t\tcreateSession(\n\t\t\t\t\t\t\t\tnewFolderCwd.trim(),\n\t\t\t\t\t\t\t\tnewFolderModel || undefined,\n\t\t\t\t\t\t\t\tnewFolderGitInit,\n\t\t\t\t\t\t\t\tpathStatus.matchingRule ? createRemoteRepo : undefined,\n\t\t\t\t\t\t\t\tpathStatus.matchingRule ? repoVisibility : undefined,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}}\n\t\t\t\t\t\tclass=\"rounded bg-gradient-to-r from-brand-cyan to-brand-blue px-3.5 py-1.5 text-xs font-semibold text-brand-text transition-all hover:opacity-90\"\n\t\t\t\t\t>\n\t\t\t\t\t\tConfirm & Create\n\t\t\t\t\t</button>\n\t\t\t\t</div>\n\t\t\t</div>\n\t\t</div>\n\t{/if}\n\n\t<!-- Clone Existing Remote Repository -->\n\t{#if showCloneConfirmModal}\n\t\t<div\n\t\t\tclass=\"fixed inset-0 z-50 flex items-center justify-center bg-brand-dark/65 p-4\"\n\t\t\trole=\"dialog\"\n\t\t\taria-modal=\"true\"\n\t\t>\n\t\t\t<div\n\t\t\t\tclass=\"w-full max-w-sm rounded-lg border border-brand-border bg-brand-surface-2 p-6 text-brand-text\"\n\t\t\t>\n\t\t\t\t<h3 class=\"mb-2 text-base font-bold text-brand-text\">\n\t\t\t\t\tRemote Repository Already Exists\n\t\t\t\t</h3>\n\t\t\t\t<p class=\"mb-3 text-sm text-brand-text-muted\">\n\t\t\t\t\tA {cloneRemoteInfo?.provider ?? 'remote'} repository matching\n\t\t\t\t\t<span class=\"font-mono text-xs text-brand-text\">{newFolderCwd}</span>\n\t\t\t\t\talready exists. Do you want to clone it instead of creating a new one?\n\t\t\t\t</p>\n\t\t\t\t{#if cloneRemoteInfo?.sshUrl}\n\t\t\t\t\t<p\n\t\t\t\t\t\tclass=\"mb-4 rounded bg-brand-surface-3 px-2.5 py-1.5 font-mono text-xs break-all text-brand-text-muted\"\n\t\t\t\t\t>\n\t\t\t\t\t\t{cloneRemoteInfo.sshUrl}\n\t\t\t\t\t</p>\n\t\t\t\t{/if}\n\n\t\t\t\t<div class=\"flex justify-end gap-2.5\">\n\t\t\t\t\t<button\n\t\t\t\t\t\ttype=\"button\"\n\t\t\t\t\t\tonclick={() => {\n\t\t\t\t\t\t\tshowCloneConfirmModal = false;\n\t\t\t\t\t\t\tcloneRemoteInfo = null;\n\t\t\t\t\t\t\tsubmitCreateSession(false);\n\t\t\t\t\t\t}}\n\t\t\t\t\t\tclass=\"rounded bg-brand-surface-3 px-3.5 py-1.5 text-xs font-semibold text-brand-text transition-colors hover:bg-brand-surface-2\"\n\t\t\t\t\t>\n\t\t\t\t\t\tCreate New Instead\n\t\t\t\t\t</button>\n\t\t\t\t\t<button\n\t\t\t\t\t\ttype=\"button\"\n\t\t\t\t\t\tonclick={() => {\n\t\t\t\t\t\t\tshowCloneConfirmModal = false;\n\t\t\t\t\t\t\tcloneRemoteInfo = null;\n\t\t\t\t\t\t\tsubmitCreateSession(true);\n\t\t\t\t\t\t}}\n\t\t\t\t\t\tclass=\"rounded bg-gradient-to-r from-brand-cyan to-brand-blue px-3.5 py-1.5 text-xs font-semibold text-brand-text transition-all hover:opacity-90\"\n\t\t\t\t\t>\n\t\t\t\t\t\tClone Repository\n\t\t\t\t\t</button>\n\t\t\t\t</div>\n\t\t\t</div>\n\t\t</div>\n\t{/if}\n</div>\n","// Pure decision helper for what a composer submit should DO, extracted from\n// ChatInput.svelte so the behaviour is deterministically unit-testable (the\n// component itself is not exercised by the node-env vitest run).\n//\n// This encodes the pi-CLI default: a submit made WHILE the agent is streaming\n// STEERS immediately (the server turns a mid-stream `message` into a `steer`,\n// injected at the next tool/step boundary before the next LLM call). There is\n// NO local \"wait for the turn to finish\" queue and no isStreaming-driven\n// auto-drain: an explicit user submit is sent right away, exactly like pressing\n// Enter in the pi CLI (interactive-mode.ts calls\n// `session.prompt(text, { streamingBehavior: \"steer\" })`).\n//\n// `deliverAs` is carried on the `send` outcome so an explicit opt-in follow-up\n// (pi's Alt+Enter \"wait until the agent finishes\") can be added later WITHOUT\n// reworking this seam: the default submit is always `steer`.\n\nexport interface ComposeSendInput {\n\t/** The agent is mid-turn (a stream is active) on the server. */\n\tstreaming: boolean;\n\t/** There is a live relay connection (real socket, not a stale flag). */\n\tconnected: boolean;\n\t/** The session transcript is loaded but its live agent is still building. */\n\tagentPending: boolean;\n\t/** The session is observe-only; sending is not allowed. */\n\treadOnly: boolean;\n\t/** An active session is open to send into. */\n\thasSession: boolean;\n}\n\nexport type ComposeSendResult =\n\t| {\n\t\t\t/** Send now. `deliverAs` tells the intent for a mid-stream send. */\n\t\t\taction: 'send';\n\t\t\tdeliverAs: 'steer' | 'followUp';\n\t }\n\t| {\n\t\t\t/** Do not send; the composer should stay put and surface `reason`. */\n\t\t\taction: 'blocked';\n\t\t\treason: 'no-session' | 'read-only' | 'disconnected' | 'agent-pending';\n\t };\n\n/**\n * Decide the outcome of a composer submit.\n *\n * Key property (the whole point of this change): when the agent is streaming on\n * a live connection, the result is `{action:'send', deliverAs:'steer'}` -- an\n * IMMEDIATE send. It is never a \"queue and wait\" outcome. The only non-send\n * results are genuine block conditions (no session / read-only / disconnected /\n * agent still building), which keep the user's text intact instead of silently\n * swallowing it.\n *\n * @param opts.followUp opt-in to pi's \"wait until the agent finishes\"\n * (Alt+Enter) behaviour for THIS submit; defaults to steer.\n */\nexport function decideComposeSend(\n\tinput: ComposeSendInput,\n\topts?: {followUp?: boolean},\n): ComposeSendResult {\n\tif (!input.hasSession) return {action: 'blocked', reason: 'no-session'};\n\tif (input.readOnly) return {action: 'blocked', reason: 'read-only'};\n\tif (!input.connected) return {action: 'blocked', reason: 'disconnected'};\n\tif (input.agentPending) return {action: 'blocked', reason: 'agent-pending'};\n\n\t// Streaming or not, an explicit submit sends now. When streaming, the server\n\t// delivers it as steer (or followUp if the caller opted in); when idle, the\n\t// deliverAs field is irrelevant (the server sends it as a normal prompt).\n\treturn {\n\t\taction: 'send',\n\t\tdeliverAs: opts?.followUp ? 'followUp' : 'steer',\n\t};\n}\n","/**\n * What a composer attachment chip shows for its upload.\n *\n * The chip's ONLY source of upload state is the `onProgress({acked, size,\n * state, error?})` callback of `uploadFile()` (`web/src/lib/wherever.ts`):\n * the composer never sees an `uploadId`, and POST uploads never enter the\n * client's `uploadsStore`, so the callback is the one feed that covers every\n * path. This module turns that state into a view, plus the two decisions the\n * composer needs (does this attachment block Send, may it be retried), as pure\n * functions so they are unit-tested without a DOM.\n *\n * Decisions (also listed in the task's done record):\n * - `pre-start` is a LOCAL state, not a client one: `handleFileChange` uploads\n * the picked files one at a time, so later files of a multi-pick wait before\n * `uploadFile` is even called. They show a bare spinner (no \"waiting\" label,\n * since nothing is waiting for the connection yet) and block Send. It is a\n * separate name rather than a reuse of `queued`, because `queued` is the\n * client's \"held: no socket / rejoin pending / capabilities unknown\" and\n * renders \"Paused, waiting for connection\".\n * - `queued` and `paused` render the SAME \"waiting for connection\" label: to\n * the user both mean \"it will continue once the connection is back\". This\n * replaces the old label derived from `!connected || resyncing`.\n * - Sending with nothing acked yet is INDETERMINATE, not 0%: the legacy WS\n * frame only ever reports acked 0 (POST too, until its first\n * `upload.onprogress`), and a bar stuck at 0% would read\n * as a hung upload, which is what story 1 is about.\n * - The percentage rounds DOWN, so 100% only shows once every byte is acked.\n * - `done` blocks Send until the resolved `savedPath` is on the attachment:\n * the `done` callback fires just before `uploadFile` resolves, and the path\n * (which is what the message carries) only arrives with the resolution.\n * - \"Pick it again\" is decided from `error.code === 'not_readable'`, never\n * from the message text.\n */\nimport type {UploadError, UploadState} from '@wherever-dev/client';\n\n/** The composer's local state for a picked file not yet handed to `uploadFile`. */\nexport const PRE_START = 'pre-start';\n\nexport type ChipUploadState = typeof PRE_START | UploadState;\n\n/** The `onProgress` payload, widened with the local pre-start state. */\nexport interface ChipUpload {\n\tstate: ChipUploadState;\n\tacked: number;\n\tsize: number;\n\terror?: UploadError;\n}\n\nexport type ChipView =\n\t/** Not handed to `uploadFile` yet: spinner, no label. */\n\t| {kind: 'pending'}\n\t/** `queued` or `paused`: \"Paused, waiting for connection\". */\n\t| {kind: 'waiting'}\n\t/** `sending` with nothing acked yet: spinner, no percentage. */\n\t| {kind: 'indeterminate'}\n\t/** `sending` with acked bytes: bar + percentage. */\n\t| {kind: 'progress'; percent: number}\n\t/** Every byte acked, completion pending: full bar + spinner. */\n\t| {kind: 'finishing'; percent: 100}\n\t| {kind: 'done'}\n\t/**\n\t * The reason, and either Retry (the composer kept the `File`) or a\n\t * \"pick the file again\" hint (the OS invalidated it).\n\t */\n\t| {kind: 'failed'; message: string; retry: boolean; pickAgain: boolean}\n\t/** Cancelled: the chip goes away, with no error and no Retry. */\n\t| {kind: 'removed'};\n\nconst GENERIC_FAILURE = 'Failed to upload';\n\nexport function preStartUpload(size: number): ChipUpload {\n\treturn {state: PRE_START, acked: 0, size};\n}\n\n/** Acked share of the size as a whole percentage, rounded down, 0..100. */\nexport function uploadPercent(acked: number, size: number): number {\n\tif (!(size > 0)) return 0;\n\tconst pct = Math.floor((acked / size) * 100);\n\treturn Math.min(100, Math.max(0, pct));\n}\n\n/** Whether a failure may be retried from the same `File`. */\nexport function canRetryUpload(error: UploadError | undefined): boolean {\n\treturn error?.code !== 'not_readable';\n}\n\nexport function chipView(upload: ChipUpload): ChipView {\n\tswitch (upload.state) {\n\t\tcase PRE_START:\n\t\t\treturn {kind: 'pending'};\n\t\tcase 'queued':\n\t\tcase 'paused':\n\t\t\treturn {kind: 'waiting'};\n\t\tcase 'sending':\n\t\t\treturn upload.acked > 0\n\t\t\t\t? {kind: 'progress', percent: uploadPercent(upload.acked, upload.size)}\n\t\t\t\t: {kind: 'indeterminate'};\n\t\tcase 'finishing':\n\t\t\treturn {kind: 'finishing', percent: 100};\n\t\tcase 'done':\n\t\t\treturn {kind: 'done'};\n\t\tcase 'aborted':\n\t\t\treturn {kind: 'removed'};\n\t\tcase 'failed': {\n\t\t\tconst retry = canRetryUpload(upload.error);\n\t\t\treturn {\n\t\t\t\tkind: 'failed',\n\t\t\t\tmessage: upload.error?.message || GENERIC_FAILURE,\n\t\t\t\tretry,\n\t\t\t\tpickAgain: !retry,\n\t\t\t};\n\t\t}\n\t}\n}\n\n/** Pre-start, queued, sending, paused or finishing: Cancel applies. */\nexport function isUploadInFlight(state: ChipUploadState): boolean {\n\treturn (\n\t\tstate === PRE_START ||\n\t\tstate === 'queued' ||\n\t\tstate === 'sending' ||\n\t\tstate === 'paused' ||\n\t\tstate === 'finishing'\n\t);\n}\n\n/**\n * Whether this attachment keeps Send disabled. A failed chip does not (the\n * user may send without it); a search-held file has no `upload` and does not.\n */\nexport function attachmentBlocksSend(attachment: {\n\tupload?: ChipUpload;\n\tpath?: string;\n}): boolean {\n\tconst upload = attachment.upload;\n\tif (!upload) return false;\n\tif (isUploadInFlight(upload.state)) return true;\n\treturn upload.state === 'done' && !attachment.path;\n}\n\n/**\n * The `UploadError` for a thrown failure (the promise rejection of\n * `uploadFile`, or a failure before it ran such as \"No active session\").\n * Only the `not_readable` code is carried over.\n */\nexport function uploadErrorFrom(err: unknown): UploadError {\n\tconst e = err as {message?: unknown; code?: unknown} | null | undefined;\n\tconst message =\n\t\ttypeof e?.message === 'string' && e.message ? e.message : GENERIC_FAILURE;\n\treturn e?.code === 'not_readable'\n\t\t? {message, code: 'not_readable'}\n\t\t: {message};\n}\n","// The hands-free loop (`micReopensAfterReply` knob) lets the user carry on a\n// spoken conversation without tapping: after the agent settles (the isStreaming\n// true->false edge the waiting-for-human beep already uses) AND any in-flight\n// TTS has finished, the mic is re-opened for another turn.\n//\n// This module is the pure decision seam the settle-edge driver in\n// ChatInput.svelte consumes (mirror of core/collapse-reply.ts and\n// core/compose-send.ts): given whether the knob is active, WHAT should happen\n// when a reply settles, and (for the cloud engine) WHEN an auto-opened\n// recording should stop again. The gating of the knob itself (conversation mode\n// ON and micReopensAfterReply ON) lives upstream in core/conversation-mode.ts's\n// isKnobActive and is folded into `active` here; the wait-for-TTS-to-finish\n// coordination lives in core/speak.ts's TTS-settle signal. Keeping the decisions\n// pure makes them unit-testable without standing up jsdom + svelte the repo\n// deliberately omits.\n\n/** The speech engine SpeechButton is currently using. */\nexport type SpeechEngine = 'browser' | 'cloud';\n\n/**\n * What the settle-edge driver should do when a reply settles.\n *\n * - `reopen-mic`: start recording again, as a manual tap would.\n * - `none`: do nothing (knob inactive).\n */\nexport type MicReopenAction = 'reopen-mic' | 'none';\n\n/**\n * Decide what to do when the agent's reply settles.\n *\n * BOTH engines auto-record. An earlier revision re-opened the mic only on the\n * BROWSER engine and merely re-focused the composer on the CLOUD engine, on the\n * grounds that auto-recording without a gesture would surprise the user. That\n * had it backwards: THE CONFIRMATION IS IN THE CONFIG, NOT IN THE CONVERSATION.\n * A user who turned `micReopensAfterReply` on has already said \"re-open my mic\n * after each reply\"; silently refusing to do it on one engine makes the knob\n * lie, and leaves a phone user (who is the most likely to be on the cloud\n * engine) tapping the mic every single turn, which is exactly the hands-free\n * loop this knob exists to remove.\n *\n * What the cloud engine genuinely needs is not consent but a STOP condition: it\n * records until told to stop, with no endpointing of its own (the browser engine\n * ends its own utterance). That is what createAutoStopDetector below provides,\n * so an auto-opened cloud recording ends on silence and can never run away.\n *\n * @param active whether the `micReopensAfterReply` knob is active (already folds\n * in the conversation-mode master gate; see isKnobActive).\n * @param engine the speech engine currently selected in SpeechButton, kept for\n * call-site clarity and future per-engine rules.\n */\nexport function decideMicReopen(opts: {\n\tactive: boolean;\n\tengine: SpeechEngine;\n}): MicReopenAction {\n\treturn opts.active ? 'reopen-mic' : 'none';\n}\n\n/** What an auto-opened recording should do after the latest audio frame. */\nexport type AutoStopDecision = 'keep-recording' | 'stop-silence' | 'stop-max';\n\nexport interface AutoStopDetector {\n\t/**\n\t * Feed one audio frame.\n\t *\n\t * @param level the frame's loudness (RMS amplitude, 0..1)\n\t * @param frameMs how much audio time that frame represents\n\t */\n\tpush(level: number, frameMs: number): AutoStopDecision;\n}\n\n/** Defaults tuned for \"the human finished their sentence\", not for hard silence. */\nexport const AUTO_STOP_DEFAULTS = {\n\t/** Above this RMS a frame counts as speech (a quiet room sits well below). */\n\tspeechLevel: 0.015,\n\t/** Stop after this much continuous silence FOLLOWING some speech. */\n\tsilenceMs: 2000,\n\t/** Stop after this much silence when the user never said anything at all. */\n\tleadingSilenceMs: 6000,\n\t/** Hard ceiling on one auto-opened recording, whatever the audio does. */\n\tmaxMs: 60_000,\n};\n\n/**\n * A stop-condition for a recording the HANDS-FREE loop opened (never for one the\n * user opened by tapping: there, the user's next tap is the stop, and taking\n * that away would be the surprising behaviour).\n *\n * Three ways to end, in priority order:\n * - `stop-max`: the hard ceiling, so a hot mic in a noisy room cannot record\n * (and upload, and pay for) forever;\n * - `stop-silence` after speech: the user said something and has stopped, which\n * is the normal end of a hands-free turn;\n * - `stop-silence` before any speech: the mic re-opened, nobody spoke, so the\n * loop gives up rather than sending a recording of the room.\n *\n * Pure and stateful-but-local: no timers, no browser APIs. The caller feeds it\n * frames it already has (SpeechButton's ScriptProcessor hands over PCM anyway),\n * which also means the detector is driven by real captured audio rather than by\n * a wall clock that keeps running when the tab is throttled.\n */\nexport function createAutoStopDetector(\n\topts: Partial<typeof AUTO_STOP_DEFAULTS> = {},\n): AutoStopDetector {\n\tconst {speechLevel, silenceMs, leadingSilenceMs, maxMs} = {\n\t\t...AUTO_STOP_DEFAULTS,\n\t\t...opts,\n\t};\n\tlet elapsedMs = 0;\n\tlet silentMs = 0;\n\tlet heardSpeech = false;\n\t// Once it has decided to stop, the decision STICKS: audio frames can still\n\t// arrive after the caller asks to stop (the processor is torn down\n\t// asynchronously), and a detector that flipped back to 'keep-recording' would\n\t// read as \"carry on\" to anything inspecting it later.\n\tlet stopped: AutoStopDecision | null = null;\n\n\treturn {\n\t\tpush(level: number, frameMs: number): AutoStopDecision {\n\t\t\tif (stopped) return stopped;\n\t\t\telapsedMs += frameMs;\n\n\t\t\tif (level >= speechLevel) {\n\t\t\t\theardSpeech = true;\n\t\t\t\tsilentMs = 0;\n\t\t\t} else {\n\t\t\t\tsilentMs += frameMs;\n\t\t\t}\n\n\t\t\tif (elapsedMs >= maxMs) {\n\t\t\t\tstopped = 'stop-max';\n\t\t\t\treturn stopped;\n\t\t\t}\n\t\t\tconst limit = heardSpeech ? silenceMs : leadingSilenceMs;\n\t\t\tif (silentMs >= limit) {\n\t\t\t\tstopped = 'stop-silence';\n\t\t\t\treturn stopped;\n\t\t\t}\n\t\t\treturn 'keep-recording';\n\t\t},\n\t};\n}\n\n/** RMS amplitude (0..1) of a frame of mono float samples. */\nexport function frameLevel(samples: ArrayLike<number>): number {\n\tconst length = samples.length;\n\tif (!length) return 0;\n\tlet sum = 0;\n\tfor (let i = 0; i < length; i++) {\n\t\tconst sample = samples[i];\n\t\tsum += sample * sample;\n\t}\n\treturn Math.sqrt(sum / length);\n}\n","<script lang=\"ts\">\n\timport {onMount} from 'svelte';\n\timport {autoSendOnSpeechEnd, setAutoSendOnSpeechEnd} from '$lib/wherever';\n\timport {unlockTts} from '$lib/core/speak';\n\timport {\n\t\tcreateAutoStopDetector,\n\t\tframeLevel,\n\t\ttype AutoStopDetector,\n\t} from '$lib/core/hands-free';\n\n\tlet {\n\t\ttext = $bindable(),\n\t\tdisabled,\n\t\tonSend,\n\t\tactiveEngine = $bindable('browser'),\n\t}: {\n\t\ttext: string;\n\t\tdisabled: boolean;\n\t\tonSend?: () => void;\n\t\t// The speech engine currently in use, mirrored out to the parent so the\n\t\t// hands-free mic-reopen loop can see it (both engines auto-record; the cloud\n\t\t// one additionally auto-STOPS, see autoStopDetector below). Bindable so a\n\t\t// parent can read it reactively; SpeechButton owns the value (the settings\n\t\t// popover sets it), the parent only observes.\n\t\tactiveEngine?: 'browser' | 'cloud';\n\t} = $props();\n\n\t// Check for Web Speech API support\n\tconst SpeechRecognition =\n\t\ttypeof window !== 'undefined'\n\t\t\t? (window as any).SpeechRecognition ||\n\t\t\t\t(window as any).webkitSpeechRecognition\n\t\t\t: null;\n\tconst isBrowserSupported = !!SpeechRecognition;\n\n\t// State\n\tlet isRecording = $state(false);\n\tlet isProcessing = $state(false);\n\tlet isHolding = $state(false);\n\tlet showSettings = $state(false);\n\tlet directSend = $state(false);\n\tlet locale = $state('en-US');\n\tlet engine = $state<'browser' | 'cloud'>('browser');\n\tlet speechError = $state<string | null>(null);\n\n\t// Keep the bindable `activeEngine` prop in lockstep with the internal engine\n\t// choice so the parent (the hands-free loop) always sees the live engine.\n\t$effect(() => {\n\t\tactiveEngine = engine;\n\t});\n\n\t// Gesture & API Tracking\n\tlet pressTimer = $state<any>(null);\n\tlet recognitionInstance: any = null;\n\n\t// Direct WAV / Web Audio PCM Recording State\n\tlet audioContext: AudioContext | null = null;\n\tlet micSource: MediaStreamAudioSourceNode | null = null;\n\tlet scriptProcessor: any = null;\n\tlet audioStream: MediaStream | null = null;\n\tlet pcmChunks: Float32Array[] = [];\n\t// Set ONLY for a recording the hands-free loop opened on the CLOUD engine.\n\t// That engine has no endpointing of its own (it records until told to stop), so\n\t// an auto-opened recording needs an auto-stop: silence after speech ends the\n\t// turn, and a hard ceiling means a hot mic can never run away. A recording the\n\t// user opened by TAPPING is left alone -- their next tap is the stop, and\n\t// taking that away would be the surprising behaviour.\n\tlet autoStopDetector: AutoStopDetector | null = null;\n\n\tlet baseText = '';\n\tlet textModified = false;\n\n\tconst locales = [\n\t\t{code: 'en-US', label: 'English (US)'},\n\t\t{code: 'en-GB', label: 'English (UK)'},\n\t\t{code: 'en-IN', label: 'English (India)'},\n\t\t{code: 'en-AU', label: 'English (Australia)'},\n\t\t{code: 'en-CA', label: 'English (Canada)'},\n\t\t{code: 'en-ZA', label: 'English (South Africa)'},\n\t];\n\n\t// directSend IS the conversation-mode `autoSendOnSpeechEnd` knob: it shares the\n\t// single `wherever-speech-direct-send` home via the autoSendOnSpeechEnd store\n\t// (see wherever.ts), so a change here or in the settings UI is reflected in the\n\t// other without a forked second flag.\n\tconst unsubscribeDirectSend = autoSendOnSpeechEnd.subscribe((v) => {\n\t\tdirectSend = v;\n\t});\n\n\tonMount(() => {\n\t\t// Load preferences (directSend is loaded via the autoSendOnSpeechEnd store).\n\t\tconst storedLocale = localStorage.getItem('wherever-speech-locale');\n\t\tif (storedLocale !== null) {\n\t\t\tlocale = storedLocale;\n\t\t}\n\t\tconst storedEngine = localStorage.getItem('wherever-speech-engine');\n\t\tif (storedEngine !== null) {\n\t\t\tengine = storedEngine as 'browser' | 'cloud';\n\t\t} else if (!isBrowserSupported) {\n\t\t\tengine = 'cloud'; // Default to cloud if browser doesn't support Web Speech API\n\t\t}\n\n\t\t// Cleanup on destroy\n\t\treturn () => {\n\t\t\tunsubscribeDirectSend();\n\t\t\tif (recognitionInstance) {\n\t\t\t\ttry {\n\t\t\t\t\trecognitionInstance.abort();\n\t\t\t\t} catch (e) {}\n\t\t\t}\n\t\t\tif (scriptProcessor) {\n\t\t\t\ttry {\n\t\t\t\t\tscriptProcessor.disconnect();\n\t\t\t\t} catch {}\n\t\t\t}\n\t\t\tif (micSource) {\n\t\t\t\ttry {\n\t\t\t\t\tmicSource.disconnect();\n\t\t\t\t} catch {}\n\t\t\t}\n\t\t\tif (audioStream) {\n\t\t\t\ttry {\n\t\t\t\t\taudioStream.getTracks().forEach((track) => track.stop());\n\t\t\t\t} catch {}\n\t\t\t}\n\t\t\tif (audioContext) {\n\t\t\t\ttry {\n\t\t\t\t\taudioContext.close();\n\t\t\t\t} catch {}\n\t\t\t}\n\t\t\tif (pressTimer) clearTimeout(pressTimer);\n\t\t};\n\t});\n\n\tfunction savePreferences() {\n\t\t// directSend persists via its shared store (single canonical home) so the\n\t\t// conversation-mode autoSendOnSpeechEnd knob and this toggle stay in sync.\n\t\tsetAutoSendOnSpeechEnd(directSend);\n\t\tlocalStorage.setItem('wherever-speech-locale', locale);\n\t\tlocalStorage.setItem('wherever-speech-engine', engine);\n\t}\n\n\tfunction getBaseUrl(): string {\n\t\tconst config = localStorage.getItem('wherever-config');\n\t\tconst parsed = config ? JSON.parse(config) : null;\n\t\t// host/port are checked before being dereferenced because the stored config\n\t\t// is not guaranteed to carry them: a token adopted from a `#token=` link on\n\t\t// a browser that never opened Connection Settings writes the token field\n\t\t// alone. Fall back to this page's own origin, as the final return does.\n\t\tif (parsed && parsed.host && parsed.port) {\n\t\t\tconst protocol =\n\t\t\t\twindow.location.protocol === 'https:' ? 'https:' : 'http:';\n\t\t\tconst host = parsed.host.startsWith('http')\n\t\t\t\t? parsed.host.replace(/^wss?:\\/\\//, '')\n\t\t\t\t: parsed.host;\n\t\t\treturn `${protocol}//${host}:${parsed.port}`;\n\t\t}\n\t\treturn `${window.location.protocol}//${window.location.host}`;\n\t}\n\n\tfunction getToken(): string {\n\t\ttry {\n\t\t\tconst config = localStorage.getItem('wherever-config');\n\t\t\tif (config) {\n\t\t\t\tconst parsed = JSON.parse(config);\n\t\t\t\treturn parsed.token || '';\n\t\t\t}\n\t\t} catch {}\n\t\treturn '';\n\t}\n\n\t// Synthesize a brief audible beep to indicate recording start\n\tfunction playBeep() {\n\t\ttry {\n\t\t\tconst AudioContextClass =\n\t\t\t\twindow.AudioContext || (window as any).webkitAudioContext;\n\t\t\tif (!AudioContextClass) return;\n\t\t\tconst ctx = new AudioContextClass();\n\t\t\tconst osc = ctx.createOscillator();\n\t\t\tconst gain = ctx.createGain();\n\n\t\t\tosc.type = 'sine';\n\t\t\tosc.frequency.setValueAtTime(400, ctx.currentTime); // 400 Hz tone\n\n\t\t\tgain.gain.setValueAtTime(0.08, ctx.currentTime);\n\t\t\tgain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 0.12); // smooth fade out\n\n\t\t\tosc.connect(gain);\n\t\t\tgain.connect(ctx.destination);\n\n\t\t\tosc.start();\n\t\t\tosc.stop(ctx.currentTime + 0.12);\n\t\t} catch (e) {\n\t\t\tconsole.warn('Could not play audio beep feedback:', e);\n\t\t}\n\t}\n\n\t// Downsamples audio buffers to target sample rate (e.g. 16kHz)\n\tfunction downsampleBuffer(\n\t\tbuffer: Float32Array,\n\t\tinputSampleRate: number,\n\t\toutputSampleRate: number,\n\t): Float32Array {\n\t\tif (inputSampleRate === outputSampleRate) {\n\t\t\treturn buffer;\n\t\t}\n\t\tconst sampleRateRatio = inputSampleRate / outputSampleRate;\n\t\tconst newLength = Math.round(buffer.length / sampleRateRatio);\n\t\tconst result = new Float32Array(newLength);\n\t\tlet offsetResult = 0;\n\t\tlet offsetBuffer = 0;\n\t\twhile (offsetResult < result.length) {\n\t\t\tconst nextOffsetBuffer = Math.round((offsetResult + 1) * sampleRateRatio);\n\t\t\tlet accum = 0;\n\t\t\tlet count = 0;\n\t\t\tfor (\n\t\t\t\tlet i = offsetBuffer;\n\t\t\t\ti < nextOffsetBuffer && i < buffer.length;\n\t\t\t\ti++\n\t\t\t) {\n\t\t\t\taccum += buffer[i];\n\t\t\t\tcount++;\n\t\t\t}\n\t\t\tresult[offsetResult] = count > 0 ? accum / count : 0;\n\t\t\toffsetResult++;\n\t\t\toffsetBuffer = nextOffsetBuffer;\n\t\t}\n\t\treturn result;\n\t}\n\n\t// ==========================================\n\t// NATIVE BROWSER SPEECH RECOGNITION (STREAMING)\n\t// ==========================================\n\tfunction startBrowserRecording() {\n\t\tif (!isBrowserSupported) return;\n\t\ttry {\n\t\t\trecognitionInstance = new SpeechRecognition();\n\t\t\trecognitionInstance.continuous = true;\n\t\t\trecognitionInstance.interimResults = true;\n\t\t\trecognitionInstance.lang = locale;\n\n\t\t\trecognitionInstance.onstart = () => {\n\t\t\t\tisRecording = true;\n\t\t\t\tisProcessing = false;\n\t\t\t\tplayBeep();\n\t\t\t};\n\n\t\t\trecognitionInstance.onresult = (event: any) => {\n\t\t\t\tlet finalSessionText = '';\n\t\t\t\tlet interimSessionText = '';\n\n\t\t\t\tfor (let i = event.resultIndex; i < event.results.length; ++i) {\n\t\t\t\t\tconst result = event.results[i];\n\t\t\t\t\tif (result.isFinal) {\n\t\t\t\t\t\tfinalSessionText += result[0].transcript;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tinterimSessionText += result[0].transcript;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst sessionText = (finalSessionText + interimSessionText).trim();\n\t\t\t\tif (sessionText) {\n\t\t\t\t\ttextModified = true;\n\t\t\t\t\ttext = baseText + (baseText ? ' ' : '') + sessionText;\n\t\t\t\t}\n\t\t\t};\n\n\t\t\trecognitionInstance.onerror = (event: any) => {\n\t\t\t\tconsole.error('Browser speech recognition error:', event.error);\n\t\t\t\tif (event.error !== 'no-speech') {\n\t\t\t\t\tspeechError = `Error: ${event.error}`;\n\t\t\t\t}\n\t\t\t\tstopBrowserRecording();\n\t\t\t};\n\n\t\t\trecognitionInstance.onend = () => {\n\t\t\t\tisRecording = false;\n\t\t\t\tif (directSend && textModified && onSend) {\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tif (text.trim()) {\n\t\t\t\t\t\t\tonSend();\n\t\t\t\t\t\t}\n\t\t\t\t\t}, 50);\n\t\t\t\t}\n\t\t\t};\n\n\t\t\trecognitionInstance.start();\n\t\t\tif (navigator.vibrate) {\n\t\t\t\tnavigator.vibrate(40);\n\t\t\t}\n\t\t} catch (e: any) {\n\t\t\tconsole.error('Failed to start browser speech recognition:', e);\n\t\t\tspeechError = 'Failed to start browser recording';\n\t\t\tisRecording = false;\n\t\t}\n\t}\n\n\tfunction stopBrowserRecording() {\n\t\tif (recognitionInstance) {\n\t\t\ttry {\n\t\t\t\trecognitionInstance.stop();\n\t\t\t} catch (e) {}\n\t\t}\n\t\tisRecording = false;\n\t}\n\n\t// ==========================================\n\t// CLOUD SERVER-ASSISTED SPEECH TRANSCRIPTION\n\t// ==========================================\n\tasync function startCloudRecording() {\n\t\ttry {\n\t\t\tconst stream = await navigator.mediaDevices.getUserMedia({audio: true});\n\t\t\taudioStream = stream;\n\t\t\tpcmChunks = [];\n\n\t\t\tconst AudioContextClass =\n\t\t\t\twindow.AudioContext || (window as any).webkitAudioContext;\n\t\t\taudioContext = new AudioContextClass();\n\n\t\t\tmicSource = audioContext.createMediaStreamSource(stream);\n\n\t\t\t// ScriptProcessor is widely supported and simpler than module-registered AudioWorklet\n\t\t\tscriptProcessor = audioContext.createScriptProcessor(4096, 1, 1);\n\t\t\tscriptProcessor.onaudioprocess = (event: any) => {\n\t\t\t\tconst inputBuffer = event.inputBuffer.getChannelData(0);\n\t\t\t\t// Push a snapshot/copy of Float32 audio samples\n\t\t\t\tpcmChunks.push(new Float32Array(inputBuffer));\n\t\t\t\t// Hands-free auto-stop, driven by the audio we are already capturing (a\n\t\t\t\t// wall-clock timer would keep running while a backgrounded tab is\n\t\t\t\t// throttled and the mic is not actually delivering frames).\n\t\t\t\tif (!autoStopDetector) return;\n\t\t\t\tconst sampleRate = event.inputBuffer.sampleRate || 44100;\n\t\t\t\tconst frameMs = (inputBuffer.length / sampleRate) * 1000;\n\t\t\t\tif (\n\t\t\t\t\tautoStopDetector.push(frameLevel(inputBuffer), frameMs) !==\n\t\t\t\t\t'keep-recording'\n\t\t\t\t) {\n\t\t\t\t\tautoStopDetector = null;\n\t\t\t\t\tstopRecording();\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tmicSource.connect(scriptProcessor);\n\t\t\tscriptProcessor.connect(audioContext.destination);\n\n\t\t\tisRecording = true;\n\t\t\tisProcessing = false;\n\t\t\tplayBeep();\n\n\t\t\tif (navigator.vibrate) {\n\t\t\t\tnavigator.vibrate(40);\n\t\t\t}\n\t\t} catch (err: any) {\n\t\t\tconsole.error('Failed to start cloud audio recording:', err);\n\t\t\tspeechError = err.message || 'Microphone access denied';\n\t\t\tisRecording = false;\n\t\t\tisProcessing = false;\n\t\t\tautoStopDetector = null;\n\t\t}\n\t}\n\n\tfunction stopCloudRecording() {\n\t\tif (isRecording) {\n\t\t\tisRecording = false;\n\t\t\tisProcessing = true;\n\n\t\t\tif (scriptProcessor) {\n\t\t\t\ttry {\n\t\t\t\t\tscriptProcessor.disconnect();\n\t\t\t\t} catch {}\n\t\t\t\tscriptProcessor.onaudioprocess = null;\n\t\t\t}\n\t\t\tif (micSource) {\n\t\t\t\ttry {\n\t\t\t\t\tmicSource.disconnect();\n\t\t\t\t} catch {}\n\t\t\t}\n\t\t\tif (audioStream) {\n\t\t\t\ttry {\n\t\t\t\t\taudioStream.getTracks().forEach((track) => track.stop());\n\t\t\t\t} catch {}\n\t\t\t}\n\n\t\t\t// Decouple processing asynchronously to prevent UI freezing\n\t\t\tprocessCloudTranscription();\n\t\t}\n\t}\n\n\tasync function processCloudTranscription() {\n\t\ttry {\n\t\t\tif (pcmChunks.length === 0) {\n\t\t\t\tisProcessing = false;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tspeechError = null;\n\n\t\t\t// Concatenate Float32 chunks\n\t\t\tlet totalLength = 0;\n\t\t\tfor (const chunk of pcmChunks) {\n\t\t\t\ttotalLength += chunk.length;\n\t\t\t}\n\n\t\t\tconst flatBuffer = new Float32Array(totalLength);\n\t\t\tlet offset = 0;\n\t\t\tfor (const chunk of pcmChunks) {\n\t\t\t\tflatBuffer.set(chunk, offset);\n\t\t\t\toffset += chunk.length;\n\t\t\t}\n\n\t\t\t// Downsample to 16kHz (Server transcriber standard)\n\t\t\tconst originalSampleRate = audioContext ? audioContext.sampleRate : 48000;\n\t\t\tconst targetSampleRate = 16000;\n\t\t\tconst downsampledBuffer = downsampleBuffer(\n\t\t\t\tflatBuffer,\n\t\t\t\toriginalSampleRate,\n\t\t\t\ttargetSampleRate,\n\t\t\t);\n\n\t\t\t// Encode directly to mono 16-bit PCM WAV buffer\n\t\t\tconst wavBuffer = createWav(\n\t\t\t\tdownsampledBuffer,\n\t\t\t\t1,\n\t\t\t\ttargetSampleRate,\n\t\t\t\t1,\n\t\t\t\t16,\n\t\t\t);\n\t\t\tconst wavBlob = new Blob([wavBuffer], {type: 'audio/wav'});\n\n\t\t\tconst baseUrl = getBaseUrl();\n\t\t\tconst token = getToken();\n\t\t\tconst url = `${baseUrl}/session/transcribe${token ? `?token=${encodeURIComponent(token)}` : ''}`;\n\n\t\t\tconst res = await fetch(url, {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody: wavBlob,\n\t\t\t\theaders: {\n\t\t\t\t\t'Content-Type': 'application/octet-stream',\n\t\t\t\t},\n\t\t\t});\n\n\t\t\tconst data = await res.json();\n\t\t\tif (!res.ok) {\n\t\t\t\tthrow new Error(data.error || `HTTP ${res.status}`);\n\t\t\t}\n\n\t\t\tif (data.text && data.text.trim()) {\n\t\t\t\ttextModified = true;\n\t\t\t\ttext = baseText + (baseText ? ' ' : '') + data.text.trim();\n\n\t\t\t\t// Auto dispatch if enabled\n\t\t\t\tif (directSend && onSend) {\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tif (text.trim()) {\n\t\t\t\t\t\t\tonSend();\n\t\t\t\t\t\t}\n\t\t\t\t\t}, 50);\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (err: any) {\n\t\t\tconsole.error('Cloud transcription request failed:', err);\n\t\t\tspeechError = err.message || 'Cloud API failed';\n\t\t} finally {\n\t\t\tisProcessing = false;\n\t\t\tif (audioContext) {\n\t\t\t\ttry {\n\t\t\t\t\taudioContext.close();\n\t\t\t\t} catch {}\n\t\t\t\taudioContext = null;\n\t\t\t}\n\t\t}\n\t}\n\n\t// ==========================================\n\t// GESTURE & INTERACTION DISPATCHERS\n\t// ==========================================\n\t// `autoStop` is set ONLY by the hands-free loop (see\n\t// startRecordingProgrammatically). A manual tap always clears the detector, so a\n\t// user-opened recording is never ended for them.\n\tfunction startRecording(autoStop = false) {\n\t\tif (disabled || isRecording || isProcessing) return;\n\t\tspeechError = null;\n\t\ttextModified = false;\n\t\tbaseText = text;\n\t\tautoStopDetector =\n\t\t\tautoStop && engine === 'cloud' ? createAutoStopDetector() : null;\n\n\t\tif (engine === 'cloud') {\n\t\t\tstartCloudRecording();\n\t\t} else {\n\t\t\tstartBrowserRecording();\n\t\t}\n\t}\n\n\t// Public: programmatically start recording, for the hands-free mic-reopen loop\n\t// (BOTH engines: the user's consent lives in the micReopensAfterReply config\n\t// knob, not in a per-conversation gesture; see core/hands-free.ts). Exposed via\n\t// bind:this so the settle-edge driver in ChatInput can re-open the mic after a\n\t// reply settles, exactly as a manual tap would. Guarded by the same\n\t// disabled/recording checks as a user gesture.\n\t//\n\t// The cloud engine additionally gets an auto-STOP for this recording, since it\n\t// would otherwise record until a tap -- the very tap the hands-free loop exists\n\t// to remove.\n\texport function startRecordingProgrammatically() {\n\t\tstartRecording(true);\n\t}\n\n\tfunction stopRecording() {\n\t\tautoStopDetector = null;\n\t\tif (engine === 'cloud') {\n\t\t\tstopCloudRecording();\n\t\t} else {\n\t\t\tstopBrowserRecording();\n\t\t}\n\t}\n\n\tfunction handlePointerDown(e: PointerEvent) {\n\t\tif (e.button !== 0) return; // Only left click / main touch\n\t\tif (disabled) return;\n\n\t\t// Second TTS gesture-unlock point (the first is the Conversation Mode\n\t\t// toggle). Tapping the mic is the other unmistakable \"I want a spoken\n\t\t// exchange\" gesture, and it is the one that covers a RETURNING user whose\n\t\t// conversation mode was already persisted ON: they never tap the toggle, so\n\t\t// without this the gesture-less `say` utterance would still be dropped on\n\t\t// mobile. Silent, idempotent and a no-op where speechSynthesis is absent (see\n\t\t// core/speak.ts), so it costs nothing when the user only wants dictation.\n\t\t// Note the gesture-less startRecordingProgrammatically() path deliberately\n\t\t// does NOT unlock -- there is no user activation there to consume.\n\t\tunlockTts();\n\n\t\te.preventDefault();\n\t\tif (isRecording) {\n\t\t\tstopRecording();\n\t\t\treturn;\n\t\t}\n\n\t\tisHolding = false;\n\t\tpressTimer = setTimeout(() => {\n\t\t\tisHolding = true;\n\t\t\tstartRecording();\n\t\t}, 350);\n\t}\n\n\tfunction handlePointerUp(e: PointerEvent) {\n\t\tif (pressTimer) {\n\t\t\tclearTimeout(pressTimer);\n\t\t\tpressTimer = null;\n\t\t}\n\n\t\tif (isHolding) {\n\t\t\tisHolding = false;\n\t\t\tstopRecording();\n\t\t} else if (!isRecording) {\n\t\t\tstartRecording();\n\t\t}\n\t}\n\n\tfunction handlePointerCancel() {\n\t\tif (pressTimer) {\n\t\t\tclearTimeout(pressTimer);\n\t\t\tpressTimer = null;\n\t\t}\n\t\tif (isHolding) {\n\t\t\tisHolding = false;\n\t\t\tstopRecording();\n\t\t}\n\t}\n\n\t// ==========================================\n\t// CLIENT-SIDE WAV ENCODER\n\t// ==========================================\n\tfunction audioBufferToWav(buffer: AudioBuffer): ArrayBuffer {\n\t\tconst numOfChan = buffer.numberOfChannels;\n\t\tconst sampleRate = buffer.sampleRate;\n\t\tconst format = 1; // Raw PCM\n\t\tconst bitDepth = 16;\n\n\t\tlet result;\n\t\tif (numOfChan === 2) {\n\t\t\tresult = interleave(buffer.getChannelData(0), buffer.getChannelData(1));\n\t\t} else {\n\t\t\tresult = buffer.getChannelData(0);\n\t\t}\n\n\t\treturn createWav(result, numOfChan, sampleRate, format, bitDepth);\n\t}\n\n\tfunction interleave(\n\t\tinputL: Float32Array,\n\t\tinputR: Float32Array,\n\t): Float32Array {\n\t\tconst length = inputL.length + inputR.length;\n\t\tconst result = new Float32Array(length);\n\t\tlet index = 0;\n\t\tlet inputIndex = 0;\n\n\t\twhile (index < length) {\n\t\t\tresult[index++] = inputL[inputIndex];\n\t\t\tresult[index++] = inputR[inputIndex];\n\t\t\tinputIndex++;\n\t\t}\n\t\treturn result;\n\t}\n\n\tfunction createWav(\n\t\tsamples: Float32Array,\n\t\tnumOfChan: number,\n\t\tsampleRate: number,\n\t\tformat: number,\n\t\tbitDepth: number,\n\t): ArrayBuffer {\n\t\tconst buffer = new ArrayBuffer(44 + samples.length * 2);\n\t\tconst view = new DataView(buffer);\n\n\t\t/* RIFF identifier */\n\t\twriteString(view, 0, 'RIFF');\n\t\t/* file length */\n\t\tview.setUint32(4, 36 + samples.length * 2, true);\n\t\t/* RIFF type */\n\t\twriteString(view, 8, 'WAVE');\n\t\t/* format chunk identifier */\n\t\twriteString(view, 12, 'fmt ');\n\t\t/* format chunk length */\n\t\tview.setUint32(16, 16, true);\n\t\t/* sample format (raw PCM) */\n\t\tview.setUint16(20, format, true);\n\t\t/* channel count */\n\t\tview.setUint16(22, numOfChan, true);\n\t\t/* sample rate */\n\t\tview.setUint32(24, sampleRate, true);\n\t\t/* byte rate (sample rate * block align) */\n\t\tview.setUint32(28, sampleRate * numOfChan * (bitDepth / 8), true);\n\t\t/* block align (channel count * bytes per sample) */\n\t\tview.setUint16(32, numOfChan * (bitDepth / 8), true);\n\t\t/* bits per sample */\n\t\tview.setUint16(34, bitDepth, true);\n\t\t/* data chunk identifier */\n\t\twriteString(view, 36, 'data');\n\t\t/* data chunk length */\n\t\tview.setUint32(40, samples.length * 2, true);\n\n\t\tfloatTo16BitPCM(view, 44, samples);\n\n\t\treturn buffer;\n\t}\n\n\tfunction floatTo16BitPCM(\n\t\toutput: DataView,\n\t\toffset: number,\n\t\tinput: Float32Array,\n\t) {\n\t\tfor (let i = 0; i < input.length; i++, offset += 2) {\n\t\t\tlet s = Math.max(-1, Math.min(1, input[i]));\n\t\t\toutput.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7fff, true);\n\t\t}\n\t}\n\n\tfunction writeString(view: DataView, offset: number, string: string) {\n\t\tfor (let i = 0; i < string.length; i++) {\n\t\t\tview.setUint8(offset + i, string.charCodeAt(i));\n\t\t}\n\t}\n</script>\n\n<div class=\"relative flex shrink-0 items-center gap-1 select-none\">\n\t<!-- Mic Button -->\n\t<button\n\t\ttype=\"button\"\n\t\tdisabled={(disabled && !isRecording && !isProcessing) || isProcessing}\n\t\tonpointerdown={handlePointerDown}\n\t\tonpointerup={handlePointerUp}\n\t\tonpointercancel={handlePointerCancel}\n\t\tclass=\"flex h-[48px] w-[48px] items-center justify-center rounded-lg border transition-all duration-150 disabled:cursor-not-allowed disabled:opacity-40\n\t\t\t{isRecording\n\t\t\t? 'animate-pulse border-red-500 bg-red-600 text-white'\n\t\t\t: isProcessing\n\t\t\t\t? 'cursor-wait border-amber-500 bg-amber-600 text-white'\n\t\t\t\t: 'border-gray-600 bg-gray-800 text-gray-400 hover:bg-gray-700 hover:text-white'}\"\n\t\ttitle={isRecording\n\t\t\t? 'Recording (release/tap to stop)...'\n\t\t\t: isProcessing\n\t\t\t\t? 'Processing speech...'\n\t\t\t\t: 'Hold to speak (walkie-talkie) or Tap to toggle recording'}\n\t>\n\t\t<svg\n\t\t\txmlns=\"http://www.w3.org/2000/svg\"\n\t\t\tviewBox=\"0 0 24 24\"\n\t\t\tfill=\"none\"\n\t\t\tstroke=\"currentColor\"\n\t\t\tstroke-width=\"2\"\n\t\t\tstroke-linecap=\"round\"\n\t\t\tstroke-linejoin=\"round\"\n\t\t\tclass=\"h-5 w-5\"\n\t\t>\n\t\t\t<path d=\"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z\" />\n\t\t\t<path d=\"M19 10v2a7 7 0 0 1-14 0v-2\" />\n\t\t\t<line x1=\"12\" x2=\"12\" y1=\"19\" y2=\"22\" />\n\t\t</svg>\n\t</button>\n\n\t<!-- Settings Cog Button -->\n\t<button\n\t\ttype=\"button\"\n\t\tonclick={() => (showSettings = !showSettings)}\n\t\tdisabled={(disabled && !isRecording && !isProcessing) || isProcessing}\n\t\tclass=\"flex h-[48px] w-[28px] items-center justify-center rounded-lg border border-gray-600 bg-gray-800 text-gray-400 hover:bg-gray-700 hover:text-white disabled:cursor-not-allowed disabled:opacity-40\"\n\t\ttitle=\"Speech Settings\"\n\t>\n\t\t<svg\n\t\t\txmlns=\"http://www.w3.org/2000/svg\"\n\t\t\tviewBox=\"0 0 24 24\"\n\t\t\tfill=\"none\"\n\t\t\tstroke=\"currentColor\"\n\t\t\tstroke-width=\"2\"\n\t\t\tstroke-linecap=\"round\"\n\t\t\tstroke-linejoin=\"round\"\n\t\t\tclass=\"h-4 w-4 transition-transform duration-200 {showSettings\n\t\t\t\t? 'rotate-45 text-white'\n\t\t\t\t: ''}\"\n\t\t>\n\t\t\t<circle cx=\"12\" cy=\"12\" r=\"3\" />\n\t\t\t<path\n\t\t\t\td=\"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z\"\n\t\t\t/>\n\t\t</svg>\n\t</button>\n\n\t<!-- Settings Popover -->\n\t{#if showSettings}\n\t\t<!-- Click Outside Backdrop -->\n\t\t<!-- svelte-ignore a11y_click_events_have_key_events -->\n\t\t<!-- svelte-ignore a11y_no_static_element_interactions -->\n\t\t<div\n\t\t\tclass=\"fixed inset-0 z-40\"\n\t\t\tonclick={() => (showSettings = false)}\n\t\t></div>\n\n\t\t<div\n\t\t\tclass=\"absolute right-0 bottom-14 z-50 w-64 rounded-lg border border-gray-600 bg-gray-800 p-4 text-xs text-white shadow-xl\"\n\t\t>\n\t\t\t<h4\n\t\t\t\tclass=\"mb-3 border-b border-gray-700 pb-1.5 font-semibold text-gray-300\"\n\t\t\t>\n\t\t\t\tSpeech Settings\n\t\t\t</h4>\n\n\t\t\t<!-- Engine Selection -->\n\t\t\t<div class=\"mb-3.5\">\n\t\t\t\t<span class=\"mb-1 block font-medium text-gray-400\">\n\t\t\t\t\tSpeech-to-Text Engine\n\t\t\t\t</span>\n\t\t\t\t<div class=\"flex gap-2\">\n\t\t\t\t\t<button\n\t\t\t\t\t\ttype=\"button\"\n\t\t\t\t\t\tonclick={() => {\n\t\t\t\t\t\t\tengine = 'browser';\n\t\t\t\t\t\t\tsavePreferences();\n\t\t\t\t\t\t}}\n\t\t\t\t\t\tdisabled={!isBrowserSupported}\n\t\t\t\t\t\tclass=\"flex-1 rounded border px-2 py-1.5 text-center font-medium transition-colors disabled:opacity-40\n\t\t\t\t\t\t\t{engine === 'browser'\n\t\t\t\t\t\t\t? 'border-blue-500 bg-blue-600 text-white'\n\t\t\t\t\t\t\t: 'border-gray-600 bg-gray-950 text-gray-400 hover:text-white'}\"\n\t\t\t\t\t>\n\t\t\t\t\t\tOn-Device\n\t\t\t\t\t</button>\n\t\t\t\t\t<button\n\t\t\t\t\t\ttype=\"button\"\n\t\t\t\t\t\tonclick={() => {\n\t\t\t\t\t\t\tengine = 'cloud';\n\t\t\t\t\t\t\tsavePreferences();\n\t\t\t\t\t\t}}\n\t\t\t\t\t\tclass=\"flex-1 rounded border px-2 py-1.5 text-center font-medium transition-colors\n\t\t\t\t\t\t\t{engine === 'cloud'\n\t\t\t\t\t\t\t? 'border-blue-500 bg-blue-600 text-white'\n\t\t\t\t\t\t\t: 'border-gray-600 bg-gray-950 text-gray-400 hover:text-white'}\"\n\t\t\t\t\t>\n\t\t\t\t\t\tCloud AI\n\t\t\t\t\t</button>\n\t\t\t\t</div>\n\t\t\t\t<p class=\"mt-1 text-[10px] leading-relaxed text-gray-400\">\n\t\t\t\t\t{engine === 'browser'\n\t\t\t\t\t\t? 'Uses free built-in browser dictation. Streaming, zero-latency.'\n\t\t\t\t\t\t: 'Uses server-side Z.ai / Groq / OpenAI keys. High accent tolerance.'}\n\t\t\t\t</p>\n\t\t\t</div>\n\n\t\t\t<!-- Accent/Locale Selection (Only visible for Browser engine) -->\n\t\t\t{#if engine === 'browser'}\n\t\t\t\t<div class=\"mb-3.5\">\n\t\t\t\t\t<label\n\t\t\t\t\t\tfor=\"speech-locale\"\n\t\t\t\t\t\tclass=\"mb-1 block font-medium text-gray-400\"\n\t\t\t\t\t>\n\t\t\t\t\t\tAccent / Locale\n\t\t\t\t\t</label>\n\t\t\t\t\t<select\n\t\t\t\t\t\tid=\"speech-locale\"\n\t\t\t\t\t\tbind:value={locale}\n\t\t\t\t\t\tonchange={savePreferences}\n\t\t\t\t\t\tclass=\"w-full rounded border border-gray-600 bg-gray-950 px-2 py-1.5 text-white focus:border-blue-500 focus:outline-none\"\n\t\t\t\t\t>\n\t\t\t\t\t\t{#each locales as loc}\n\t\t\t\t\t\t\t<option value={loc.code}>{loc.label}</option>\n\t\t\t\t\t\t{/each}\n\t\t\t\t\t</select>\n\t\t\t\t</div>\n\t\t\t{/if}\n\n\t\t\t<!-- Direct Send Toggle -->\n\t\t\t<div class=\"mb-2\">\n\t\t\t\t<label class=\"flex cursor-pointer items-center gap-2 py-1\">\n\t\t\t\t\t<input\n\t\t\t\t\t\ttype=\"checkbox\"\n\t\t\t\t\t\tbind:checked={directSend}\n\t\t\t\t\t\tonchange={savePreferences}\n\t\t\t\t\t\tclass=\"rounded border-gray-600 bg-gray-950 text-blue-600 focus:ring-0 focus:ring-offset-0\"\n\t\t\t\t\t/>\n\t\t\t\t\t<span class=\"font-medium text-gray-300\"\n\t\t\t\t\t\t>Direct Send (Auto-dispatch)</span\n\t\t\t\t\t>\n\t\t\t\t</label>\n\t\t\t\t<p class=\"pl-6 text-[10px] leading-relaxed text-gray-400\">\n\t\t\t\t\tWhen enabled, releasing or stopping the microphone immediately sends\n\t\t\t\t\tthe message.\n\t\t\t\t</p>\n\t\t\t</div>\n\n\t\t\t{#if speechError}\n\t\t\t\t<div\n\t\t\t\t\tclass=\"mt-2 rounded border border-red-900/40 bg-red-950/40 p-2 leading-normal text-red-400\"\n\t\t\t\t>\n\t\t\t\t\t{speechError}\n\t\t\t\t</div>\n\t\t\t{/if}\n\t\t</div>\n\t{/if}\n</div>\n","<script lang=\"ts\">\n\timport {onDestroy, onMount, untrack} from 'svelte';\n\timport {\n\t\tsendMessage,\n\t\tpiState,\n\t\tisConnected,\n\t\tcreateSession,\n\t\tclearMessages,\n\t\tleaveSession,\n\t\tuploadFile,\n\t\tbeginFilePicker,\n\t\tendFilePicker,\n\t\tcomposerPrefill,\n\t\treloadResources,\n\t} from '$lib/wherever';\n\timport {isStreaming, isReadOnly, activeSessionInfo} from '$lib/wherever';\n\timport {getConversationKnobs} from '$lib/wherever';\n\timport {getBaseUrl, getToken} from '$lib/session-store';\n\timport {decideComposeSend} from '$lib/core/compose-send';\n\timport {buildAttachmentMessage} from '$lib/core/attachments';\n\timport {\n\t\tattachmentBlocksSend,\n\t\tcanRetryUpload,\n\t\tchipView,\n\t\tisUploadInFlight,\n\t\tpreStartUpload,\n\t\tuploadErrorFrom,\n\t\ttype ChipUpload,\n\t} from '$lib/core/upload-chip';\n\timport type {UploadProgress} from '@wherever-dev/client';\n\timport {isKnobActive} from '$lib/core/conversation-mode';\n\timport {decideMicReopen} from '$lib/core/hands-free';\n\timport {whenTtsIdle} from '$lib/core/speak';\n\timport {\n\t\tDRAFTS_CACHE_KEY,\n\t\tLEGACY_DRAFTS_KEY,\n\t\tapplyDraft,\n\t\tdecideDraftLoad,\n\t\tdraftOriginLabel,\n\t\tdraftPreview,\n\t\tdraftToConsumeOnSend,\n\t\tparseDrafts,\n\t\tserializeDrafts,\n\t\ttype Draft,\n\t\ttype DraftLoadMode,\n\t} from '$lib/core/drafts';\n\timport {fetchDrafts, saveDraftRemote, deleteDraftRemote} from '$lib/wherever';\n\timport SpeechButton from './speech/SpeechButton.svelte';\n\n\tlet {\n\t\tdisabled,\n\t\tsendDisabled = false,\n\t\tonSend,\n\t\tonSubmit,\n\t\tplaceholder,\n\t\tsubmitLabel,\n\t\tshowAttach = true,\n\t\tsearchMode = false,\n\t\tsearchConfigured = false,\n\t\tsearchModels = [],\n\t\tsearchModel = $bindable(''),\n\t}: {\n\t\t// Blocks EDITING (textarea, attach, mic): no session, read-only, ...\n\t\tdisabled: boolean;\n\t\t// Blocks only SENDING (the Send/Steer button, Enter-to-send, dictation\n\t\t// auto-send) while the box stays editable: a reconnect/resync, or a\n\t\t// still-building agent. Losing the socket must never stop the user from\n\t\t// reading, typing or attaching; it only stops the message going out.\n\t\tsendDisabled?: boolean;\n\t\tonSend?: () => void;\n\t\t// When provided (search mode), submit routes here instead of sendMessage.\n\t\t// Files are handed over UNUPLOADED: search has no session yet, so the\n\t\t// search flow uploads them once it has created one.\n\t\tonSubmit?: (text: string, files?: File[]) => void;\n\t\tplaceholder?: string;\n\t\tsubmitLabel?: string;\n\t\tshowAttach?: boolean;\n\t\tsearchMode?: boolean;\n\t\t// Whether a search folder is configured (gates enablement in search mode).\n\t\tsearchConfigured?: boolean;\n\t\t// Model list + bound selection for the search-mode model picker. Values are\n\t\t// \"provider:modelId\"; empty label list hides the picker.\n\t\tsearchModels?: {value: string; label: string}[];\n\t\tsearchModel?: string;\n\t} = $props();\n\n\tlet text = $state('');\n\tlet enterToSend = $state(true);\n\tlet isCollapsed = $state(false);\n\n\t// Hands-free mic-reopen loop (`micReopensAfterReply` knob). The SpeechButton\n\t// child owns the engine + the programmatic recording start; ChatInput owns the\n\t// composer focus and already subscribes to the isStreaming settle edge, so the\n\t// settle-edge driver lives here. These bindings surface the child's engine and\n\t// its instance (for startRecordingProgrammatically) to the driver below.\n\tlet speechEngine = $state<'browser' | 'cloud'>('browser');\n\tlet speechButton = $state<{startRecordingProgrammatically: () => void}>();\n\n\t// --- Slash-command (skill) autocomplete ---------------------------------\n\t// Mirrors the pi CLI: when the message STARTS with a `/` token (no space yet),\n\t// offer the session's `/skill:<name>` commands. Selecting one only INSERTS\n\t// `/skill:<name> ` (trailing space) so the user can keep typing an argument;\n\t// it never submits. Expansion happens server-side at send time. `/skill:` is\n\t// start-anchored, so a `/` mid-message is ignored, exactly like the CLI.\n\tlet skillMenuOpen = $state(false);\n\tlet skillMenuIndex = $state(0);\n\n\tlet fileInput = $state<HTMLInputElement>();\n\tlet nextAttachmentId = 0;\n\t// In-flight uploads by attachment id, so removing a chip cancels its upload\n\t// (a parked upload would otherwise still go out on reconnect and leave an\n\t// orphan file in the upload dir).\n\tconst uploadControllers = new Map<number, AbortController>();\n\t// Chat mode: an attachment carries its upload state (`upload`, fed only by\n\t// uploadFile's onProgress; see core/upload-chip.ts) and, once done, the saved\n\t// `path`. Search mode: a local File waiting for a session to upload it to\n\t// (`file` set). The two must stay apart: `file` is the search-mode marker\n\t// (the leave-search-mode effect drops attachments that have it, search submit\n\t// collects it), so a chat upload keeps the File it may retry from under\n\t// `retryFile` instead.\n\tlet attachments = $state<\n\t\t{\n\t\t\t// Stable identity: an upload resolves long after it starts (it may wait\n\t\t\t// out a reconnect), and the user can remove other chips meanwhile, so\n\t\t\t// results are matched by id, never by array index.\n\t\t\tid: number;\n\t\t\tname: string;\n\t\t\tpath?: string;\n\t\t\tupload?: ChipUpload;\n\t\t\t// The picked File, kept so Retry needs no re-pick. Dropped once done,\n\t\t\t// and on a `not_readable` failure (the OS invalidated it).\n\t\t\tretryFile?: File;\n\t\t\t// /health diagnostics link shown with a failure.\n\t\t\turl?: string;\n\t\t\tfile?: File;\n\t\t}[]\n\t>([]);\n\n\tlet streaming = $derived($isStreaming);\n\tlet readOnly = $derived($isReadOnly);\n\tlet sessionInfo = $derived($activeSessionInfo);\n\tlet connected = $derived($isConnected);\n\tlet appState = $derived($piState);\n\n\t// The `/` token currently being typed at the START of the message, or null\n\t// when the message doesn't begin a slash command (no leading `/`, or a space\n\t// has already been typed so the command name is committed). Only the leading\n\t// token triggers the menu, matching the CLI's start-of-line anchoring.\n\tlet slashPrefix = $derived.by(() => {\n\t\tif (searchMode) return null;\n\t\tconst m = text.match(/^\\/([^\\s]*)$/);\n\t\treturn m ? m[1] : null;\n\t});\n\n\t// Skill commands the composer can offer, fuzzily filtered by the typed token.\n\t// `s.name` is the full invocation without the slash (e.g. \"skill:setup\"), so\n\t// typing \"/setu\" surfaces \"skill:setup\" via substring match on the name.\n\tlet skillMatches = $derived.by(() => {\n\t\tif (slashPrefix === null) return [];\n\t\tconst all = appState.skills ?? [];\n\t\tif (all.length === 0) return [];\n\t\tconst q = slashPrefix.toLowerCase();\n\t\tconst matches = q\n\t\t\t? all.filter((s) => s.name.toLowerCase().includes(q))\n\t\t\t: all.slice();\n\t\t// Rank exact-prefix hits (\"skill:setup\" for \"skill:set\") above loose\n\t\t// substring hits so the most likely completion is highlighted first.\n\t\treturn matches.sort((a, b) => {\n\t\t\tconst ap = a.name.toLowerCase().startsWith(q) ? 0 : 1;\n\t\t\tconst bp = b.name.toLowerCase().startsWith(q) ? 0 : 1;\n\t\t\treturn ap - bp || a.name.localeCompare(b.name);\n\t\t});\n\t});\n\n\t// Open the menu whenever there are matches for the current slash token, and\n\t// keep the highlighted index in range as the list shrinks/grows. Closes when\n\t// the token is committed (space typed) or there are no matches.\n\t$effect(() => {\n\t\tconst count = skillMatches.length;\n\t\tif (count === 0) {\n\t\t\tif (untrack(() => skillMenuOpen)) skillMenuOpen = false;\n\t\t\treturn;\n\t\t}\n\t\tif (!untrack(() => skillMenuOpen)) skillMenuOpen = true;\n\t\tif (untrack(() => skillMenuIndex) >= count) skillMenuIndex = 0;\n\t});\n\n\t// Insert `/skill:<name> ` (trailing space), keeping focus and placing the\n\t// cursor after the space so the user can immediately type an argument. Never\n\t// submits: this only rewrites the composer, exactly like the pi CLI.\n\tfunction applySkill(name: string) {\n\t\ttext = `/${name} `;\n\t\tskillMenuOpen = false;\n\t\tskillMenuIndex = 0;\n\t\tqueueMicrotask(() => {\n\t\t\tif (!textarea) return;\n\t\t\ttextarea.focus();\n\t\t\tconst end = text.length;\n\t\t\ttextarea.setSelectionRange(end, end);\n\t\t});\n\t}\n\n\t// In search mode the composer must work with no active session: it requires\n\t// only a live connection and a configured search folder. In chat mode it\n\t// stays gated on an active session as before.\n\t// Note: streaming does NOT disable the composer. A mid-stream submit steers\n\t// the agent immediately (pi's default), so the box stays live while the agent\n\t// works and the primary button reads \"Steer\".\n\t//\n\t// Chat mode deliberately does NOT gate editing on `connected`: a dropped\n\t// socket (app switch, file picker, network blip) keeps the cached\n\t// conversation on screen, and the composer must stay usable too (type, attach;\n\t// attachments wait for the connection). Only sending is blocked, below.\n\tlet effectivelyDisabled = $derived(\n\t\tsearchMode\n\t\t\t? disabled || !connected || !searchConfigured\n\t\t\t: disabled || readOnly || !sessionInfo.sessionId,\n\t);\n\t// Editing allowed but sending is not (reconnecting / resyncing / agent still\n\t// building). Superset of effectivelyDisabled.\n\tlet sendBlocked = $derived(\n\t\teffectivelyDisabled || sendDisabled || (!searchMode && !connected),\n\t);\n\n\tlet isAnyUploading = $derived(attachments.some(attachmentBlocksSend));\n\tlet canSend = $derived(\n\t\t!sendBlocked &&\n\t\t\t!isAnyUploading &&\n\t\t\t(text.trim().length > 0 || attachments.length > 0),\n\t);\n\n\tlet textarea = $state<HTMLTextAreaElement>();\n\n\t// Persist the in-progress draft so it is never lost when this composer is\n\t// unmounted out from under the user (e.g. the parent swaps it for the\n\t// \"Reconnecting and syncing session...\" status line during a resync, or on a\n\t// transient disconnect). The draft is keyed per session so switching sessions\n\t// does not bleed text between them; search mode (no session) uses a shared\n\t// 'search' key. Cleared on a successful send.\n\t// A draft belongs to the active session when one is open, otherwise to the\n\t// (no-session) search composer. Keying on sessionId-or-search this way means:\n\t// a session keeps its own draft, and the search query is preserved under one\n\t// shared key so switching into a session and back to search (by closing the\n\t// session or hitting the search button) restores what was typed. This holds\n\t// whether or not a search folder is configured (no session == search mode).\n\tconst DRAFT_PREFIX = 'wherever-draft:';\n\tlet draftKey = $derived(DRAFT_PREFIX + (sessionInfo.sessionId ?? 'search'));\n\t// Tracks which key we have already hydrated so the restore effect fires only\n\t// when the key actually changes (mount, session switch, search<->chat), not on\n\t// every keystroke. The persist effect below removes the key whenever the\n\t// textarea goes empty, so a successful send (which clears `text`) also clears\n\t// the saved draft.\n\tlet hydratedKey = $state<string | null>(null);\n\n\tonMount(() => {\n\t\tconst stored = localStorage.getItem('wherever-enter-to-send');\n\t\tif (stored !== null) {\n\t\t\tenterToSend = stored === 'true';\n\t\t}\n\t\tdrafts = readCachedDrafts();\n\t});\n\n\t// --- Saved drafts (save instead of send) --------------------------------\n\t// A draft is an EXPLICIT, durable message the user chose to keep rather than\n\t// send, distinct from the per-session auto-draft above (invisible crash\n\t// protection for the one text in the box).\n\t//\n\t// The STORE IS THE SERVER (`/drafts` -> <config dir>/drafts.json): a draft\n\t// saved on a phone has to be there on the laptop, and must survive the browser\n\t// losing its storage. The server is the only writer and answers every mutation\n\t// with the whole list, which is adopted verbatim; localStorage holds a MIRROR\n\t// used only to render the panel while disconnected. Drafts are global, not per\n\t// session (a prompt written in one repo is often what you want to send in\n\t// another), so the origin session/cwd is display metadata only.\n\tlet drafts = $state<Draft[]>([]);\n\tlet draftsOpen = $state(false);\n\t// A draft the user asked to load while the box already held unsent text. It is\n\t// held here (not loaded) until they pick Replace / Append / Cancel, so loading\n\t// a draft can never silently destroy what they were typing.\n\tlet pendingDraft = $state<Draft | null>(null);\n\t// The draft currently sitting in the composer. Loading does NOT delete a draft\n\t// (one mistap would destroy it with no undo); SENDING it does, via\n\t// draftToConsumeOnSend. Cleared whenever the link cannot hold any more.\n\tlet draftSource = $state<{id: string; text: string} | null>(null);\n\tlet draftSavedFlash = $state(false);\n\tlet draftError = $state<string | null>(null);\n\tlet draftsLoading = $state(false);\n\t// Monotonic stamp for drafts responses. Several requests (an open-panel\n\t// refresh, a save, a delete) can be in flight at once and they do NOT complete\n\t// in order: without this, a slow GET landing after a fast DELETE would\n\t// resurrect the deleted draft in the list AND in the offline mirror.\n\tlet draftsRequestSeq = 0;\n\tlet draftsAdoptedSeq = 0;\n\tlet draftFlashTimer: ReturnType<typeof setTimeout> | undefined;\n\n\tfunction readCachedDrafts(): Draft[] {\n\t\tif (typeof localStorage === 'undefined') return [];\n\t\ttry {\n\t\t\treturn parseDrafts(localStorage.getItem(DRAFTS_CACHE_KEY));\n\t\t} catch {\n\t\t\treturn [];\n\t\t}\n\t}\n\n\t// Adopt a server list and mirror it locally, unless a NEWER response has already\n\t// been adopted (see draftsRequestSeq). A failed mirror write is NOT an error the\n\t// user needs to see: the drafts are safe on the server, the cache is only an\n\t// offline convenience.\n\tfunction adoptDrafts(next: Draft[], seq: number) {\n\t\tif (seq < draftsAdoptedSeq) return;\n\t\tdraftsAdoptedSeq = seq;\n\t\tdrafts = next;\n\t\tif (typeof localStorage === 'undefined') return;\n\t\ttry {\n\t\t\tlocalStorage.setItem(DRAFTS_CACHE_KEY, serializeDrafts(next));\n\t\t} catch {}\n\t}\n\n\t// One-shot migration from the first, browser-only version of this feature, so\n\t// a draft written against a pre-server build is not orphaned. The legacy key is\n\t// removed once its contents are on the server; the cache key is a different key\n\t// precisely so a mirrored list can never be re-uploaded after a delete.\n\tasync function migrateLegacyDrafts(): Promise<boolean> {\n\t\tif (typeof localStorage === 'undefined') return false;\n\t\tlet legacy: Draft[] = [];\n\t\ttry {\n\t\t\tlegacy = parseDrafts(localStorage.getItem(LEGACY_DRAFTS_KEY));\n\t\t} catch {}\n\t\tif (legacy.length === 0) {\n\t\t\ttry {\n\t\t\t\tlocalStorage.removeItem(LEGACY_DRAFTS_KEY);\n\t\t\t} catch {}\n\t\t\treturn false;\n\t\t}\n\t\ttry {\n\t\t\t// Oldest first, so the server's newest-first order comes out right.\n\t\t\tfor (const d of [...legacy].reverse()) {\n\t\t\t\tawait saveDraftRemote({\n\t\t\t\t\ttext: d.text,\n\t\t\t\t\tsessionId: d.sessionId,\n\t\t\t\t\tcwd: d.cwd,\n\t\t\t\t});\n\t\t\t}\n\t\t\tlocalStorage.removeItem(LEGACY_DRAFTS_KEY);\n\t\t\treturn true;\n\t\t} catch {\n\t\t\t// Leave the legacy key in place and try again on the next connection.\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tasync function refreshDrafts() {\n\t\tif (!connected) return;\n\t\tconst seq = ++draftsRequestSeq;\n\t\tdraftsLoading = true;\n\t\ttry {\n\t\t\tawait migrateLegacyDrafts();\n\t\t\tadoptDrafts(await fetchDrafts(), seq);\n\t\t\tdraftError = null;\n\t\t} catch (err) {\n\t\t\t// Keep whatever list is on screen (possibly the offline mirror): an\n\t\t\t// unreadable store must never be flattened into \"you have no drafts\".\n\t\t\tdraftError = (err as Error)?.message || 'Could not load drafts';\n\t\t} finally {\n\t\t\tdraftsLoading = false;\n\t\t}\n\t}\n\n\t// Pull the server list once the socket is up (and again after a reconnect), so\n\t// a draft saved from another device is already there when the panel is opened.\n\tlet draftsFetchedWhileConnected = false;\n\t$effect(() => {\n\t\tif (!connected) {\n\t\t\tdraftsFetchedWhileConnected = false;\n\t\t\treturn;\n\t\t}\n\t\tif (draftsFetchedWhileConnected) return;\n\t\tdraftsFetchedWhileConnected = true;\n\t\tvoid refreshDrafts();\n\t});\n\n\t// Save what is in the box and CLEAR it, exactly like a send would: \"save\n\t// instead of sending\" means the composer is done with that message. The text is\n\t// only cleared once the SERVER has it -- a failed save leaves the message in the\n\t// box with the error, never silently swallowed. Attachments are deliberately\n\t// left alone: an uploaded file lives on the server under a path and a draft is\n\t// text only, so dropping the chips would lose them for a message the user still\n\t// intends to send.\n\tasync function saveCurrentAsDraft() {\n\t\tconst trimmed = text.trim();\n\t\tif (trimmed.length === 0) return;\n\t\t// Snapshot what is being saved AND which composer it belongs to. The box is\n\t\t// cleared only if BOTH still hold when the server answers: over a slow link\n\t\t// the user can keep typing (clearing would delete everything typed since) or\n\t\t// switch session (clearing would wipe THAT session's draft instead, from the\n\t\t// box and from its auto-draft entry). Never clear text we did not save.\n\t\tconst keyAtRequest = draftKey;\n\t\tconst seq = ++draftsRequestSeq;\n\t\ttry {\n\t\t\tconst next = await saveDraftRemote({\n\t\t\t\ttext: trimmed,\n\t\t\t\tsessionId: sessionInfo.sessionId ?? undefined,\n\t\t\t\tcwd: sessionInfo.cwd ?? undefined,\n\t\t\t});\n\t\t\tadoptDrafts(next, seq);\n\t\t\tdraftError = null;\n\t\t\tif (draftKey === keyAtRequest && text.trim() === trimmed) {\n\t\t\t\ttext = '';\n\t\t\t\tdraftSource = null;\n\t\t\t}\n\t\t\tdraftSavedFlash = true;\n\t\t\tclearTimeout(draftFlashTimer);\n\t\t\tdraftFlashTimer = setTimeout(() => (draftSavedFlash = false), 1800);\n\t\t} catch (err) {\n\t\t\tdraftError = (err as Error)?.message || 'Could not save the draft';\n\t\t\tdraftsOpen = true;\n\t\t}\n\t}\n\n\tfunction requestLoadDraft(draft: Draft) {\n\t\tif (decideDraftLoad(text) === 'confirm') {\n\t\t\tpendingDraft = draft;\n\t\t\treturn;\n\t\t}\n\t\tloadDraft(draft, 'replace');\n\t}\n\n\tfunction loadDraft(draft: Draft, mode: DraftLoadMode) {\n\t\t// Make sure the current key counts as hydrated so the auto-draft effect\n\t\t// persists the loaded text instead of skipping it (same reason the fork\n\t\t// prefill does this).\n\t\thydratedKey = draftKey;\n\t\ttext = applyDraft(text, draft.text, mode);\n\t\tdraftSource = {id: draft.id, text: draft.text};\n\t\tpendingDraft = null;\n\t\tdraftsOpen = false;\n\t\tif (isCollapsed) isCollapsed = false;\n\t\tqueueMicrotask(() => {\n\t\t\tif (!textarea) return;\n\t\t\ttextarea.focus();\n\t\t\tconst end = text.length;\n\t\t\ttextarea.setSelectionRange(end, end);\n\t\t});\n\t}\n\n\t// Called after a message actually went out: a draft that has been SENT is not a\n\t// draft any more. Best-effort -- the message is already delivered, so a failed\n\t// delete must not look like a failed send; the stale draft simply survives.\n\tfunction consumeDraftOnSend(sentText: string) {\n\t\tconst id = draftToConsumeOnSend(draftSource, sentText);\n\t\tdraftSource = null;\n\t\tif (!id) return;\n\t\tconst seq = ++draftsRequestSeq;\n\t\tvoid deleteDraftRemote(id)\n\t\t\t.then((next) => adoptDrafts(next, seq))\n\t\t\t.catch(() => {});\n\t}\n\n\tasync function deleteDraft(id: string) {\n\t\tconst seq = ++draftsRequestSeq;\n\t\ttry {\n\t\t\tadoptDrafts(await deleteDraftRemote(id), seq);\n\t\t\tdraftError = null;\n\t\t} catch (err) {\n\t\t\tdraftError = (err as Error)?.message || 'Could not delete the draft';\n\t\t}\n\t\tif (pendingDraft?.id === id) pendingDraft = null;\n\t\tif (draftSource?.id === id) draftSource = null;\n\t}\n\n\tfunction toggleDrafts() {\n\t\tif (!draftsOpen) void refreshDrafts();\n\t\tdraftsOpen = !draftsOpen;\n\t\tpendingDraft = null;\n\t}\n\n\tfunction closeDrafts() {\n\t\tdraftsOpen = false;\n\t\tpendingDraft = null;\n\t}\n\n\tonDestroy(() => clearTimeout(draftFlashTimer));\n\n\t// Swap the textarea to the active draft key's saved draft whenever the key\n\t// changes (initial mount, session switch, search<->chat). This is an\n\t// unconditional swap: the previous session's draft must NOT linger in the box\n\t// after switching, but going back to a session restores its own saved draft.\n\t// The hydratedKey guard makes this fire ONLY on a real key change (not on\n\t// every keystroke), so it never clobbers text the user is actively typing\n\t// within the current session. The text read is untracked accordingly.\n\t$effect(() => {\n\t\tconst key = draftKey;\n\t\tif (key === hydratedKey) return;\n\t\tuntrack(() => {\n\t\t\tlet saved: string | null = null;\n\t\t\tif (typeof localStorage !== 'undefined') {\n\t\t\t\ttry {\n\t\t\t\t\tsaved = localStorage.getItem(key);\n\t\t\t\t} catch {}\n\t\t\t}\n\t\t\ttext = saved ?? '';\n\t\t\thydratedKey = key;\n\t\t\t// The box now holds a different session's text, so it is no longer the\n\t\t\t// draft that was loaded: sending it must not delete that draft.\n\t\t\tdraftSource = null;\n\t\t});\n\t});\n\n\t// Fork prefill: when the fork-at-user-message flow sets composerPrefill (a\n\t// bumped {text, bump}), drop that text into the box for the user to edit and\n\t// send, mirroring pi's `/fork`. Keyed on `bump` so re-applying the same text\n\t// works; guarded so bump:0 (the initial empty value) is ignored. Runs after a\n\t// session switch, so it deliberately wins over the (empty) hydrated draft.\n\tlet appliedPrefillBump = $state(0);\n\t$effect(() => {\n\t\tconst {text: prefillText, bump} = $composerPrefill;\n\t\tif (bump === 0 || bump === appliedPrefillBump) return;\n\t\tappliedPrefillBump = bump;\n\t\tuntrack(() => {\n\t\t\t// Ensure the current key is treated as hydrated so the persist effect\n\t\t\t// saves this prefilled draft rather than being skipped/overwritten.\n\t\t\thydratedKey = draftKey;\n\t\t\ttext = prefillText;\n\t\t\tif (isCollapsed) isCollapsed = false;\n\t\t\tqueueMicrotask(() => textarea?.focus());\n\t\t});\n\t});\n\n\t// Persist the draft on every text change. Removing the key when empty keeps\n\t// storage clean (and means a successful send, which clears text, clears it).\n\t// Only persists once the current key has been hydrated, so the restore above\n\t// is never overwritten by a stale empty value mid-switch.\n\t$effect(() => {\n\t\tconst value = text;\n\t\tconst key = draftKey;\n\t\tif (key !== hydratedKey || typeof localStorage === 'undefined') return;\n\t\ttry {\n\t\t\tif (value.trim().length > 0) {\n\t\t\t\tlocalStorage.setItem(key, value);\n\t\t\t} else {\n\t\t\t\tlocalStorage.removeItem(key);\n\t\t\t}\n\t\t} catch {}\n\t});\n\n\t// Files picked in search mode are held locally until the search creates its\n\t// session. If the composer leaves search mode first (the user opens a session\n\t// instead of searching), those files have no destination, so drop them rather\n\t// than let a stale chip ride along into a chat message.\n\t$effect(() => {\n\t\tif (searchMode) return;\n\t\tuntrack(() => {\n\t\t\tif (attachments.some((a) => a.file)) {\n\t\t\t\tattachments = attachments.filter((a) => !a.file);\n\t\t\t}\n\t\t});\n\t});\n\n\t// Exposed so a parent can focus the textarea SYNCHRONOUSLY inside a user\n\t// gesture (required to raise the mobile virtual keyboard, esp. iOS Safari).\n\texport function focusInput() {\n\t\tif (isCollapsed) isCollapsed = false;\n\t\ttextarea?.focus();\n\t}\n\n\t// --- Hands-free mic-reopen driver --------------------------------------\n\t// Mirror the waiting-for-human beep: watch the streaming flag and act on the\n\t// isStreaming true->false edge (the moment the agent settles and is waiting for\n\t// the human). When the `micReopensAfterReply` knob is active we wait for any\n\t// in-flight `say` TTS to finish (whenTtsIdle) so the spoken reply is not\n\t// captured as mic input, then re-open the mic. BOTH engines auto-record: the\n\t// user's consent lives in the config knob they turned on, not in a\n\t// per-conversation gesture, and the cloud engine's missing stop condition is\n\t// solved by its auto-stop detector rather than by refusing to start (see\n\t// core/hands-free.ts). When the knob is inactive (conversation mode off for this\n\t// conversation, or the knob off) nothing happens.\n\tlet prevStreamingForReopen = false;\n\t$effect(() => {\n\t\tconst nowStreaming = $isStreaming;\n\t\tconst settled = prevStreamingForReopen && !nowStreaming;\n\t\tprevStreamingForReopen = nowStreaming;\n\t\tif (!settled) return;\n\t\t// Snapshot the decision at the settle edge (engine + knob state now). The\n\t\t// TTS wait is async, so guard against acting after the composer is torn down.\n\t\tconst action = decideMicReopen({\n\t\t\tactive: isKnobActive('micReopensAfterReply', getConversationKnobs()),\n\t\t\tengine: speechEngine,\n\t\t});\n\t\tif (action === 'none') return;\n\t\tif (sendBlocked) return;\n\t\tvoid whenTtsIdle().then(() => {\n\t\t\t// Re-check: the user may have started streaming again, or the composer may\n\t\t\t// have been disabled, while TTS was finishing.\n\t\t\tif ($isStreaming || sendBlocked) return;\n\t\t\tspeechButton?.startRecordingProgrammatically();\n\t\t});\n\t});\n\n\tfunction toggleEnterToSend() {\n\t\tenterToSend = !enterToSend;\n\t\tlocalStorage.setItem('wherever-enter-to-send', String(enterToSend));\n\t}\n\n\t$effect(() => {\n\t\tif (textarea) {\n\t\t\t// Trigger reactive updates when text changes\n\t\t\ttext;\n\t\t\ttextarea.style.height = 'auto';\n\t\t\ttextarea.style.height = `${textarea.scrollHeight}px`;\n\t\t}\n\t});\n\n\t// Automatically focus/refocus the textarea whenever it becomes active/enabled\n\t$effect(() => {\n\t\tif (!effectivelyDisabled && textarea) {\n\t\t\ttextarea.focus();\n\t\t}\n\t});\n\n\tasync function handleFileChange(e: Event) {\n\t\t// The native picker is closed now that we have a change event; allow the\n\t\t// background suspend timer to resume its normal behaviour.\n\t\tendFilePicker();\n\t\tconst target = e.target as HTMLInputElement;\n\t\tif (!target.files) return;\n\t\tconst files = Array.from(target.files);\n\t\ttarget.value = '';\n\n\t\t// Search mode has no session to upload into yet (the session is created by\n\t\t// the search itself), so just hold the files; runSearch uploads them once\n\t\t// the session exists.\n\t\tif (searchMode) {\n\t\t\tattachments = [\n\t\t\t\t...attachments,\n\t\t\t\t...files.map((f) => ({\n\t\t\t\t\tid: nextAttachmentId++,\n\t\t\t\t\tname: f.name,\n\t\t\t\t\tfile: f,\n\t\t\t\t})),\n\t\t\t];\n\t\t\treturn;\n\t\t}\n\n\t\t// No early \"No active session\" / \"not connected\" failure: the session id\n\t\t// survives a socket drop (the cached session is kept), and uploadFile waits\n\t\t// for the connection to come back. A slow pick (camera, file browser)\n\t\t// commonly costs the socket on mobile; that must not cost the upload.\n\t\tconst sessionId = sessionInfo.sessionId;\n\t\tconst entries = files.map((f) => ({file: f, id: nextAttachmentId++}));\n\t\t// Later files of a multi-pick wait for earlier ones (one upload at a time),\n\t\t// so they start in the local pre-start state.\n\t\tattachments = [\n\t\t\t...attachments,\n\t\t\t...entries.map(({file, id}) => ({\n\t\t\t\tid,\n\t\t\t\tname: file.name,\n\t\t\t\tupload: preStartUpload(file.size),\n\t\t\t\tretryFile: file,\n\t\t\t})),\n\t\t];\n\n\t\tfor (const {file, id} of entries) {\n\t\t\tawait runUpload(id, file, sessionId);\n\t\t}\n\t}\n\n\tfunction updateAttachment(\n\t\tid: number,\n\t\tupdate: (a: (typeof attachments)[number]) => (typeof attachments)[number],\n\t) {\n\t\tattachments = attachments.map((a) => (a.id === id ? update(a) : a));\n\t}\n\n\tfunction dropAttachment(id: number) {\n\t\tattachments = attachments.filter((a) => a.id !== id);\n\t}\n\n\tfunction diagnosticsUrl(): string {\n\t\ttry {\n\t\t\tconst baseUrl = getBaseUrl();\n\t\t\tconst token = getToken();\n\t\t\treturn `${baseUrl}/health${token ? `?token=${encodeURIComponent(token)}` : ''}`;\n\t\t} catch {\n\t\t\treturn '';\n\t\t}\n\t}\n\n\t// Upload one attachment's File and drive its chip from onProgress. Each\n\t// attempt owns its AbortController; callbacks and results from an attempt that\n\t// is no longer the current one for this id (removed, or superseded by a\n\t// Retry) are ignored.\n\tasync function runUpload(\n\t\tid: number,\n\t\tfile: File,\n\t\tsessionId: string | null | undefined,\n\t) {\n\t\t// Removed by the user while earlier files were uploading: skip it.\n\t\tif (!attachments.some((a) => a.id === id)) return;\n\t\tconst controller = new AbortController();\n\t\tuploadControllers.set(id, controller);\n\t\tconst isCurrent = () => uploadControllers.get(id) === controller;\n\t\tconst onProgress = (p: UploadProgress) => {\n\t\t\tif (!isCurrent()) return;\n\t\t\tif (p.state === 'aborted') {\n\t\t\t\tdropAttachment(id);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tupdateAttachment(id, (a) => ({\n\t\t\t\t...a,\n\t\t\t\tupload: {...p},\n\t\t\t\t...(p.state === 'failed' && !canRetryUpload(p.error)\n\t\t\t\t\t? {retryFile: undefined}\n\t\t\t\t\t: {}),\n\t\t\t}));\n\t\t};\n\t\ttry {\n\t\t\tif (!sessionId) {\n\t\t\t\tthrow new Error('No active session');\n\t\t\t}\n\t\t\tconst res = await uploadFile(sessionId, file, {\n\t\t\t\tsignal: controller.signal,\n\t\t\t\tonProgress,\n\t\t\t});\n\t\t\tif (!isCurrent()) return;\n\t\t\tupdateAttachment(id, (a) => ({\n\t\t\t\tid,\n\t\t\t\tname: a.name,\n\t\t\t\tpath: res.savedPath,\n\t\t\t\tupload: {state: 'done', acked: file.size, size: file.size},\n\t\t\t}));\n\t\t} catch (err) {\n\t\t\tif (!isCurrent()) return;\n\t\t\tif (controller.signal.aborted) {\n\t\t\t\tdropAttachment(id);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconsole.error('File upload error details:', err);\n\t\t\tconst error = uploadErrorFrom(err);\n\t\t\tupdateAttachment(id, (a) => ({\n\t\t\t\tid,\n\t\t\t\tname: a.name,\n\t\t\t\tupload: {\n\t\t\t\t\tstate: 'failed',\n\t\t\t\t\tacked: a.upload?.acked ?? 0,\n\t\t\t\t\tsize: file.size,\n\t\t\t\t\terror,\n\t\t\t\t},\n\t\t\t\tretryFile: canRetryUpload(error) ? file : undefined,\n\t\t\t\turl: diagnosticsUrl(),\n\t\t\t}));\n\t\t} finally {\n\t\t\tif (isCurrent()) uploadControllers.delete(id);\n\t\t}\n\t}\n\n\t// Cancel an in-flight upload. The aborted upload reports `aborted`, which\n\t// removes its chip; a pre-start chip has no upload yet, so it goes directly.\n\tfunction cancelUpload(id: number) {\n\t\tconst controller = uploadControllers.get(id);\n\t\tif (controller) controller.abort();\n\t\telse dropAttachment(id);\n\t}\n\n\t// Restart a failed upload from the File picked originally (no re-pick),\n\t// into the session that is current NOW, not the one at pick time.\n\tfunction retryUpload(id: number) {\n\t\tconst attachment = attachments.find((a) => a.id === id);\n\t\tconst file = attachment?.retryFile;\n\t\tif (!file || uploadControllers.has(id)) return;\n\t\tupdateAttachment(id, (a) => ({\n\t\t\tid,\n\t\t\tname: a.name,\n\t\t\tupload: preStartUpload(file.size),\n\t\t\tretryFile: file,\n\t\t}));\n\t\tvoid runUpload(id, file, sessionInfo.sessionId);\n\t}\n\n\tfunction removeAttachment(id: number) {\n\t\tuploadControllers.get(id)?.abort();\n\t\tdropAttachment(id);\n\t}\n\n\tfunction handleSend() {\n\t\t// Every send path (button, Enter, dictation auto-send) funnels through\n\t\t// here, so this is the one gate for \"editable but not sendable\". The text\n\t\t// and attachments stay in the box for when the connection is back.\n\t\tif (sendBlocked || isAnyUploading) return;\n\t\tconst trimmed = text.trim();\n\n\t\t// Search mode: route to the injected handler with the (not yet uploaded)\n\t\t// files, skipping slash commands and the streaming/queue machinery entirely.\n\t\t// Files alone are a valid search: the query can be \"what is this?\" implied.\n\t\tif (searchMode) {\n\t\t\tconst files = attachments\n\t\t\t\t.map((a) => a.file)\n\t\t\t\t.filter((f): f is File => !!f);\n\t\t\tif ((!trimmed && files.length === 0) || effectivelyDisabled) return;\n\t\t\tonSubmit?.(trimmed, files);\n\t\t\tconsumeDraftOnSend(trimmed);\n\t\t\ttext = '';\n\t\t\tattachments = [];\n\t\t\tonSend?.();\n\t\t\treturn;\n\t\t}\n\n\t\tif (!trimmed && attachments.length === 0) return;\n\n\t\tconst uploadedPaths = attachments\n\t\t\t.map((a) => a.path)\n\t\t\t.filter((p): p is string => !!p);\n\t\tconst messageToSend = buildAttachmentMessage(trimmed, uploadedPaths);\n\n\t\t// Handle local slash commands to match terminal behavior\n\t\tif (trimmed.startsWith('/') && attachments.length === 0) {\n\t\t\tconst lower = trimmed.toLowerCase();\n\t\t\t// Each of these CLEARS the box without sending, so the loaded draft is no\n\t\t\t// longer in the composer: drop the link, or a later unrelated send could\n\t\t\t// be credited to (and delete) that draft.\n\t\t\tif (lower === '/new' || lower === '/reset') {\n\t\t\t\tif (sessionInfo.cwd) {\n\t\t\t\t\tcreateSession(sessionInfo.cwd, sessionInfo.model || undefined);\n\t\t\t\t\ttext = '';\n\t\t\t\t\tdraftSource = null;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t} else if (lower === '/clear') {\n\t\t\t\tclearMessages();\n\t\t\t\ttext = '';\n\t\t\t\tdraftSource = null;\n\t\t\t\treturn;\n\t\t\t} else if (lower === '/leave' || lower === '/exit') {\n\t\t\t\tleaveSession();\n\t\t\t\ttext = '';\n\t\t\t\tdraftSource = null;\n\t\t\t\treturn;\n\t\t\t} else if (lower === '/reload') {\n\t\t\t\t// pi's `/reload` is a TUI command, not something the agent can act on,\n\t\t\t\t// so it must never reach the model as chat text. The SERVER rebuilds the\n\t\t\t\t// agent and answers with session_reloading/session_ready, or a notice\n\t\t\t\t// when it refuses (agent busy, terminal-driven session, read-only).\n\t\t\t\t// Without a session or a connection, or while the agent is still being\n\t\t\t\t// built (a cold load or a reload in progress: the server may not have\n\t\t\t\t// attached us yet), fall through to the normal send path, whose\n\t\t\t\t// blocked-send feedback already explains why and keeps the text.\n\t\t\t\tif (sessionInfo.sessionId && connected && !appState.agentPending) {\n\t\t\t\t\treloadResources();\n\t\t\t\t\ttext = '';\n\t\t\t\t\tdraftSource = null;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// pi's default: an explicit submit sends NOW. When the agent is streaming,\n\t\t// the server turns this mid-stream `message` into a STEER (injected at the\n\t\t// next tool/step boundary, before the next LLM call) rather than parking it\n\t\t// in a local queue that waits for the whole turn to resolve. The decision\n\t\t// helper is a pure, unit-tested function so this behaviour is gated in tests.\n\t\tconst decision = decideComposeSend({\n\t\t\tstreaming,\n\t\t\tconnected,\n\t\t\tagentPending: appState.agentPending,\n\t\t\treadOnly,\n\t\t\thasSession: !!sessionInfo.sessionId,\n\t\t});\n\t\tif (decision.action !== 'send') {\n\t\t\t// A genuine block (no session / read-only / disconnected / agent still\n\t\t\t// building). Keep the user's text intact; the composer's disabled/status\n\t\t\t// affordances already explain the state, and sendMessage() would surface a\n\t\t\t// recoverable error anyway. Never silently swallow the message.\n\t\t\tif (\n\t\t\t\tdecision.reason === 'disconnected' ||\n\t\t\t\tdecision.reason === 'agent-pending'\n\t\t\t) {\n\t\t\t\t// Route through sendMessage so it sets the clear, recoverable session\n\t\t\t\t// error (\"Not connected...\" / \"Preparing the session agent...\"). It\n\t\t\t\t// returns false and leaves the text so the user can retry.\n\t\t\t\tsendMessage(messageToSend);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// Only clear the composer if the message actually went out. On a dropped\n\t\t// send (socket died in the race) sendMessage() returns false and surfaces an\n\t\t// error; keep the text so the user can retry once reconnected instead of\n\t\t// silently losing what they typed.\n\t\tconst sent = sendMessage(messageToSend);\n\t\tif (sent) {\n\t\t\tconsumeDraftOnSend(trimmed);\n\t\t\ttext = '';\n\t\t\tattachments = [];\n\t\t\tonSend?.();\n\t\t}\n\t}\n\n\tfunction handleKeydown(e: KeyboardEvent) {\n\t\t// Escape closes the drafts panel first (it floats over the composer), the\n\t\t// same affordance the skill menu below has.\n\t\tif (draftsOpen && e.key === 'Escape') {\n\t\t\te.preventDefault();\n\t\t\tcloseDrafts();\n\t\t\treturn;\n\t\t}\n\t\t// Skill autocomplete owns the navigation keys while the menu is open. The\n\t\t// first Enter/Tab ACCEPTS the highlighted command (inserting `/skill:<name> `)\n\t\t// and is swallowed, so a second Enter is needed to actually send, matching the\n\t\t// pi CLI's accept-then-send behaviour and giving the user room to type args.\n\t\tif (skillMenuOpen && skillMatches.length > 0) {\n\t\t\tif (e.key === 'ArrowDown') {\n\t\t\t\te.preventDefault();\n\t\t\t\tskillMenuIndex = (skillMenuIndex + 1) % skillMatches.length;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (e.key === 'ArrowUp') {\n\t\t\t\te.preventDefault();\n\t\t\t\tskillMenuIndex =\n\t\t\t\t\t(skillMenuIndex - 1 + skillMatches.length) % skillMatches.length;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (e.key === 'Enter' || e.key === 'Tab') {\n\t\t\t\te.preventDefault();\n\t\t\t\tconst chosen = skillMatches[skillMenuIndex] ?? skillMatches[0];\n\t\t\t\tif (chosen) applySkill(chosen.name);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (e.key === 'Escape') {\n\t\t\t\te.preventDefault();\n\t\t\t\tskillMenuOpen = false;\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tif (e.key === 'Enter') {\n\t\t\tif (enterToSend) {\n\t\t\t\t// Default mode: Enter to send, Shift+Enter for newline\n\t\t\t\tif (!e.shiftKey) {\n\t\t\t\t\te.preventDefault();\n\t\t\t\t\thandleSend();\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Enter for newline, Shift+Enter to send\n\t\t\t\tif (e.shiftKey) {\n\t\t\t\t\te.preventDefault();\n\t\t\t\t\thandleSend();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n</script>\n\n<div class=\"relative border-t border-brand-border p-4\">\n\t{#if draftsOpen}\n\t\t<!-- Saved drafts. Floats ABOVE the composer (like the skill menu) so opening\n\t\t it never resizes the textarea or pushes the transcript around. Loading a\n\t\t draft over a non-empty box routes through the warning below first. -->\n\t\t<div\n\t\t\tid=\"drafts-panel\"\n\t\t\trole=\"dialog\"\n\t\t\taria-label=\"Saved drafts\"\n\t\t\tclass=\"absolute right-4 bottom-full left-4 z-30 mb-2 overflow-hidden rounded-lg border border-brand-border bg-brand-surface-2 shadow-lg\"\n\t\t>\n\t\t\t<div\n\t\t\t\tclass=\"flex items-center justify-between border-b border-brand-border px-3 py-2\"\n\t\t\t>\n\t\t\t\t<span class=\"text-xs font-medium text-brand-text\">\n\t\t\t\t\tSaved drafts ({drafts.length})\n\t\t\t\t\t{#if draftsLoading}\n\t\t\t\t\t\t<span class=\"ml-1 text-brand-text-muted\">syncing…</span>\n\t\t\t\t\t{:else if !connected}\n\t\t\t\t\t\t<span\n\t\t\t\t\t\t\tclass=\"ml-1 text-brand-text-muted\"\n\t\t\t\t\t\t\ttitle=\"Showing the last list this device saw. Saving and deleting need the server.\"\n\t\t\t\t\t\t\t>offline copy</span\n\t\t\t\t\t\t>\n\t\t\t\t\t{/if}\n\t\t\t\t</span>\n\t\t\t\t<button\n\t\t\t\t\ttype=\"button\"\n\t\t\t\t\tonclick={closeDrafts}\n\t\t\t\t\tclass=\"text-xs text-brand-text-muted hover:text-brand-text\"\n\t\t\t\t\taria-label=\"Close drafts\">Close ×</button\n\t\t\t\t>\n\t\t\t</div>\n\n\t\t\t{#if pendingDraft}\n\t\t\t\t<!-- The warning the feature exists for: the box holds unsent text, so a\n\t\t\t\t load is offered as Replace (destructive, explicit) or Append (keeps\n\t\t\t\t both), never silently applied. -->\n\t\t\t\t<div\n\t\t\t\t\tclass=\"border-b border-amber-500/30 bg-amber-500/10 px-3 py-2 text-xs text-amber-300\"\n\t\t\t\t>\n\t\t\t\t\t<div class=\"mb-2\">\n\t\t\t\t\t\t⚠️ The message box is not empty. Loading this draft would replace\n\t\t\t\t\t\twhat you typed.\n\t\t\t\t\t</div>\n\t\t\t\t\t<div class=\"flex flex-wrap gap-2\">\n\t\t\t\t\t\t<button\n\t\t\t\t\t\t\ttype=\"button\"\n\t\t\t\t\t\t\tonclick={() => pendingDraft && loadDraft(pendingDraft, 'replace')}\n\t\t\t\t\t\t\tclass=\"rounded bg-amber-500/20 px-2 py-1 font-medium text-amber-200 hover:bg-amber-500/30\"\n\t\t\t\t\t\t\t>Replace</button\n\t\t\t\t\t\t>\n\t\t\t\t\t\t<button\n\t\t\t\t\t\t\ttype=\"button\"\n\t\t\t\t\t\t\tonclick={() => pendingDraft && loadDraft(pendingDraft, 'append')}\n\t\t\t\t\t\t\tclass=\"rounded bg-brand-surface-3 px-2 py-1 font-medium text-brand-text hover:opacity-90\"\n\t\t\t\t\t\t\t>Append below</button\n\t\t\t\t\t\t>\n\t\t\t\t\t\t<button\n\t\t\t\t\t\t\ttype=\"button\"\n\t\t\t\t\t\t\tonclick={() => (pendingDraft = null)}\n\t\t\t\t\t\t\tclass=\"rounded px-2 py-1 text-brand-text-muted hover:text-brand-text\"\n\t\t\t\t\t\t\t>Cancel</button\n\t\t\t\t\t\t>\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n\t\t\t{/if}\n\n\t\t\t{#if drafts.length === 0}\n\t\t\t\t<p class=\"px-3 py-4 text-center text-xs text-brand-text-muted\">\n\t\t\t\t\tNo saved drafts yet. Type a message and press “Save draft” to keep it\n\t\t\t\t\ton the server for later, from any device.\n\t\t\t\t</p>\n\t\t\t{:else}\n\t\t\t\t<ul class=\"max-h-64 overflow-y-auto\">\n\t\t\t\t\t{#each drafts as d (d.id)}\n\t\t\t\t\t\t<li\n\t\t\t\t\t\t\tclass=\"flex items-start gap-2 border-b border-brand-border/50 px-3 py-2 last:border-b-0 {pendingDraft?.id ===\n\t\t\t\t\t\t\td.id\n\t\t\t\t\t\t\t\t? 'bg-brand-surface-3/60'\n\t\t\t\t\t\t\t\t: ''}\"\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t<!-- Loading needs a live box to load INTO. With no session and no\n\t\t\t\t\t\t\t search folder the composer is disabled, and dropping text into\n\t\t\t\t\t\t\t it would silently go nowhere, so the row says so instead. -->\n\t\t\t\t\t\t\t<button\n\t\t\t\t\t\t\t\ttype=\"button\"\n\t\t\t\t\t\t\t\tonclick={() => requestLoadDraft(d)}\n\t\t\t\t\t\t\t\tdisabled={effectivelyDisabled}\n\t\t\t\t\t\t\t\tclass=\"min-w-0 flex-1 text-left disabled:cursor-not-allowed disabled:opacity-50\"\n\t\t\t\t\t\t\t\ttitle={effectivelyDisabled\n\t\t\t\t\t\t\t\t\t? 'Open a session first to load this draft'\n\t\t\t\t\t\t\t\t\t: d.text}\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t<span class=\"line-clamp-2 text-xs text-brand-text\"\n\t\t\t\t\t\t\t\t\t>{draftPreview(d.text)}</span\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t<span class=\"mt-0.5 block text-[10px] text-brand-text-muted\"\n\t\t\t\t\t\t\t\t\t>{new Date(d.updatedAt).toLocaleString()}{draftOriginLabel(d)\n\t\t\t\t\t\t\t\t\t\t? ` · ${draftOriginLabel(d)}`\n\t\t\t\t\t\t\t\t\t\t: ''}</span\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t</button>\n\t\t\t\t\t\t\t<button\n\t\t\t\t\t\t\t\ttype=\"button\"\n\t\t\t\t\t\t\t\tonclick={() => deleteDraft(d.id)}\n\t\t\t\t\t\t\t\tclass=\"shrink-0 rounded px-1.5 py-0.5 text-xs text-brand-text-muted hover:bg-rose-500/10 hover:text-rose-400\"\n\t\t\t\t\t\t\t\ttitle=\"Delete this draft\"\n\t\t\t\t\t\t\t\taria-label=\"Delete draft\">🗑</button\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t</li>\n\t\t\t\t\t{/each}\n\t\t\t\t</ul>\n\t\t\t{/if}\n\n\t\t\t{#if draftError}\n\t\t\t\t<p class=\"border-t border-brand-border px-3 py-2 text-xs text-rose-400\">\n\t\t\t\t\t⚠️ {draftError}\n\t\t\t\t</p>\n\t\t\t{/if}\n\t\t</div>\n\t{/if}\n\t{#if !connected || appState.connecting || appState.error}\n\t\t<div\n\t\t\tclass=\"mb-2.5 flex items-center gap-1.5 text-xs font-medium text-brand-text-muted select-none\"\n\t\t>\n\t\t\t{#if appState.connecting}\n\t\t\t\t<span\n\t\t\t\t\tclass=\"inline-block h-1.5 w-1.5 animate-ping rounded-full bg-amber-400\"\n\t\t\t\t></span>\n\t\t\t\t<span>Connecting to remote server...</span>\n\t\t\t{:else if appState.error}\n\t\t\t\t<span class=\"text-rose-400\">⚠️</span>\n\t\t\t\t<span class=\"text-rose-400/80\">{appState.error}</span>\n\t\t\t{:else if !connected}\n\t\t\t\t<span class=\"inline-block h-1.5 w-1.5 rounded-full bg-brand-surface-3\"\n\t\t\t\t></span>\n\t\t\t\t<span>Disconnected from remote server</span>\n\t\t\t{/if}\n\t\t</div>\n\t{/if}\n\t{#if isCollapsed}\n\t\t<div class=\"flex items-center\">\n\t\t\t<button\n\t\t\t\ttype=\"button\"\n\t\t\t\tonclick={() => {\n\t\t\t\t\tisCollapsed = false;\n\t\t\t\t\tsetTimeout(() => textarea?.focus(), 50);\n\t\t\t\t}}\n\t\t\t\tclass=\"flex w-full items-center justify-between rounded-lg border border-brand-border bg-brand-surface-2 px-4 py-2.5 text-sm text-brand-text-muted transition-all hover:bg-brand-surface-3 hover:text-brand-text\"\n\t\t\t>\n\t\t\t\t<span class=\"flex items-center gap-2\">\n\t\t\t\t\t<span>{searchMode ? '🔍' : '💬'}</span>\n\t\t\t\t\t<span>\n\t\t\t\t\t\t{#if searchMode}\n\t\t\t\t\t\t\t{placeholder ?? 'Search the web...'}\n\t\t\t\t\t\t{:else if streaming}\n\t\t\t\t\t\t\tAgent is working, tap to Steer...\n\t\t\t\t\t\t{:else if readOnly}\n\t\t\t\t\t\t\tRead-only mode\n\t\t\t\t\t\t{:else if !sessionInfo.sessionId}\n\t\t\t\t\t\t\tSelect a session first...\n\t\t\t\t\t\t{:else}\n\t\t\t\t\t\t\tTap to type a message...\n\t\t\t\t\t\t{/if}\n\t\t\t\t\t</span>\n\t\t\t\t</span>\n\t\t\t\t<span\n\t\t\t\t\tclass=\"rounded bg-brand-surface-3 px-2 py-1 text-xs font-medium text-brand-text transition-colors hover:bg-brand-surface-2\"\n\t\t\t\t\t>Expand ▲</span\n\t\t\t\t>\n\t\t\t</button>\n\t\t</div>\n\t{:else}\n\t\t{#if attachments.length > 0}\n\t\t\t<div class=\"mb-3 flex flex-wrap gap-2\">\n\t\t\t\t{#each attachments as attachment (attachment.id)}\n\t\t\t\t\t<!-- Chip state comes ONLY from uploadFile's onProgress, mapped by\n\t\t\t\t\t core/upload-chip.ts (chipView); a search-held file has no upload. -->\n\t\t\t\t\t{@const view = attachment.upload ? chipView(attachment.upload) : null}\n\t\t\t\t\t{@const inFlight = attachment.upload\n\t\t\t\t\t\t? isUploadInFlight(attachment.upload.state)\n\t\t\t\t\t\t: false}\n\t\t\t\t\t<div\n\t\t\t\t\t\tclass=\"flex items-center gap-2 rounded border bg-brand-surface-2 px-2.5 py-1.5 text-xs {inFlight\n\t\t\t\t\t\t\t? 'border-brand-blue'\n\t\t\t\t\t\t\t: 'border-brand-border'}\"\n\t\t\t\t\t>\n\t\t\t\t\t\t<span\n\t\t\t\t\t\t\tclass=\"max-w-[150px] truncate font-medium text-brand-text\"\n\t\t\t\t\t\t\ttitle={attachment.name}\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t{attachment.name}\n\t\t\t\t\t\t</span>\n\t\t\t\t\t\t{#if attachment.file}\n\t\t\t\t\t\t\t<!-- Search mode: held locally, uploaded when the search creates\n\t\t\t\t\t\t\t its session. -->\n\t\t\t\t\t\t\t<span\n\t\t\t\t\t\t\t\tclass=\"text-brand-text-muted\"\n\t\t\t\t\t\t\t\ttitle=\"Will be uploaded with the search\">📎</span\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t{:else if view?.kind === 'pending' || view?.kind === 'indeterminate'}\n\t\t\t\t\t\t\t<span\n\t\t\t\t\t\t\t\tclass=\"inline-block h-3 w-3 animate-spin rounded-full border-2 border-brand-blue border-t-transparent\"\n\t\t\t\t\t\t\t></span>\n\t\t\t\t\t\t{:else if view?.kind === 'waiting'}\n\t\t\t\t\t\t\t<!-- Queued or paused: the upload continues on its own once the\n\t\t\t\t\t\t\t socket is back and the session has rejoined (no re-attach). -->\n\t\t\t\t\t\t\t<span\n\t\t\t\t\t\t\t\tclass=\"inline-block h-3 w-3 animate-spin rounded-full border-2 border-brand-text-muted border-t-transparent\"\n\t\t\t\t\t\t\t></span>\n\t\t\t\t\t\t\t<span\n\t\t\t\t\t\t\t\tclass=\"text-[10px] text-brand-text-muted\"\n\t\t\t\t\t\t\t\ttitle=\"The upload continues once reconnected\"\n\t\t\t\t\t\t\t\t>Paused, waiting for connection</span\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t{:else if view?.kind === 'progress' || view?.kind === 'finishing'}\n\t\t\t\t\t\t\t<span\n\t\t\t\t\t\t\t\tclass=\"h-1.5 w-16 overflow-hidden rounded-full bg-brand-surface-3\"\n\t\t\t\t\t\t\t\trole=\"progressbar\"\n\t\t\t\t\t\t\t\taria-valuemin={0}\n\t\t\t\t\t\t\t\taria-valuemax={100}\n\t\t\t\t\t\t\t\taria-valuenow={view.percent}\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t<span\n\t\t\t\t\t\t\t\t\tclass=\"block h-full rounded-full bg-brand-blue transition-[width]\"\n\t\t\t\t\t\t\t\t\tstyle=\"width: {view.percent}%\"\n\t\t\t\t\t\t\t\t></span>\n\t\t\t\t\t\t\t</span>\n\t\t\t\t\t\t\t<span class=\"text-[10px] text-brand-text-muted tabular-nums\"\n\t\t\t\t\t\t\t\t>{view.percent}%</span\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t{#if view.kind === 'finishing'}\n\t\t\t\t\t\t\t\t<span\n\t\t\t\t\t\t\t\t\tclass=\"inline-block h-3 w-3 animate-spin rounded-full border-2 border-brand-blue border-t-transparent\"\n\t\t\t\t\t\t\t\t\ttitle=\"Finishing\"\n\t\t\t\t\t\t\t\t></span>\n\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t{:else if view?.kind === 'failed'}\n\t\t\t\t\t\t\t<span\n\t\t\t\t\t\t\t\tclass=\"flex items-center gap-1 text-[10px] font-medium text-rose-400\"\n\t\t\t\t\t\t\t\ttitle={view.message}\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t<span class=\"max-w-[120px] truncate\">⚠️ {view.message}</span>\n\t\t\t\t\t\t\t\t{#if view.pickAgain}\n\t\t\t\t\t\t\t\t\t<span class=\"shrink-0 text-brand-text-muted\"\n\t\t\t\t\t\t\t\t\t\t>Pick the file again</span\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t{:else if attachment.url}\n\t\t\t\t\t\t\t\t\t<a\n\t\t\t\t\t\t\t\t\t\thref={attachment.url}\n\t\t\t\t\t\t\t\t\t\ttarget=\"_blank\"\n\t\t\t\t\t\t\t\t\t\tclass=\"ml-1 shrink-0 font-semibold text-brand-blue underline hover:opacity-80\"\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t[Test Link]\n\t\t\t\t\t\t\t\t\t</a>\n\t\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t\t</span>\n\t\t\t\t\t\t\t{#if view.retry && attachment.retryFile}\n\t\t\t\t\t\t\t\t<button\n\t\t\t\t\t\t\t\t\ttype=\"button\"\n\t\t\t\t\t\t\t\t\tonclick={() => retryUpload(attachment.id)}\n\t\t\t\t\t\t\t\t\tclass=\"rounded bg-brand-surface-3 px-1.5 py-0.5 text-[10px] font-medium text-brand-text hover:bg-brand-surface-3/70\"\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\tRetry\n\t\t\t\t\t\t\t\t</button>\n\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t{:else}\n\t\t\t\t\t\t\t<span class=\"text-emerald-400\">✓</span>\n\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t{#if inFlight}\n\t\t\t\t\t\t\t<button\n\t\t\t\t\t\t\t\ttype=\"button\"\n\t\t\t\t\t\t\t\tonclick={() => cancelUpload(attachment.id)}\n\t\t\t\t\t\t\t\tclass=\"rounded bg-brand-surface-3 px-1.5 py-0.5 text-[10px] font-medium text-brand-text-muted hover:text-brand-text\"\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\tCancel\n\t\t\t\t\t\t\t</button>\n\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t<button\n\t\t\t\t\t\t\ttype=\"button\"\n\t\t\t\t\t\t\tonclick={() => removeAttachment(attachment.id)}\n\t\t\t\t\t\t\tclass=\"ml-1 font-bold text-brand-text-muted hover:text-brand-text\"\n\t\t\t\t\t\t\ttitle=\"Remove\"\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t×\n\t\t\t\t\t\t</button>\n\t\t\t\t\t</div>\n\t\t\t\t{/each}\n\t\t\t</div>\n\t\t{/if}\n\t\t{#if searchMode && searchModels.length > 0}\n\t\t\t<!-- Model picker for search mode. Lets the user override the search\n\t\t\t folder's default model before pressing Search. -->\n\t\t\t<div class=\"mb-2 flex items-center gap-2\">\n\t\t\t\t<label\n\t\t\t\t\tfor=\"search-model\"\n\t\t\t\t\tclass=\"text-xs font-medium text-brand-text-muted\">Model</label\n\t\t\t\t>\n\t\t\t\t<select\n\t\t\t\t\tid=\"search-model\"\n\t\t\t\t\tbind:value={searchModel}\n\t\t\t\t\tdisabled={effectivelyDisabled}\n\t\t\t\t\tclass=\"min-w-0 flex-1 rounded-lg border border-brand-border bg-brand-surface-2 px-2 py-1.5 text-xs text-brand-text focus:border-brand-blue focus:outline-none disabled:opacity-50\"\n\t\t\t\t>\n\t\t\t\t\t{#each searchModels as m}\n\t\t\t\t\t\t<option value={m.value}>{m.label}</option>\n\t\t\t\t\t{/each}\n\t\t\t\t</select>\n\t\t\t</div>\n\t\t{/if}\n\t\t<form\n\t\t\tonsubmit={(e) => {\n\t\t\t\te.preventDefault();\n\t\t\t\thandleSend();\n\t\t\t}}\n\t\t\tclass=\"flex items-stretch gap-3\"\n\t\t>\n\t\t\t<div class=\"relative min-w-0 flex-1\">\n\t\t\t\t{#if skillMenuOpen && skillMatches.length > 0}\n\t\t\t\t\t<!-- Skill-command autocomplete. Floats above the composer. Selecting an\n\t\t\t\t\t item only inserts `/skill:<name> ` (see applySkill); it never sends. -->\n\t\t\t\t\t<ul\n\t\t\t\t\t\tclass=\"absolute bottom-full left-0 z-20 mb-1 max-h-56 w-full overflow-y-auto rounded-lg border border-brand-border bg-brand-surface-2 py-1 shadow-lg\"\n\t\t\t\t\t\trole=\"listbox\"\n\t\t\t\t\t>\n\t\t\t\t\t\t{#each skillMatches as skill, i (skill.name)}\n\t\t\t\t\t\t\t<li>\n\t\t\t\t\t\t\t\t<button\n\t\t\t\t\t\t\t\t\ttype=\"button\"\n\t\t\t\t\t\t\t\t\trole=\"option\"\n\t\t\t\t\t\t\t\t\taria-selected={i === skillMenuIndex}\n\t\t\t\t\t\t\t\t\tonmousedown={(e) => {\n\t\t\t\t\t\t\t\t\t\t// mousedown (not click) so the textarea doesn't blur first and\n\t\t\t\t\t\t\t\t\t\t// tear the menu down before the selection lands.\n\t\t\t\t\t\t\t\t\t\te.preventDefault();\n\t\t\t\t\t\t\t\t\t\tapplySkill(skill.name);\n\t\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t\t\tonmouseenter={() => (skillMenuIndex = i)}\n\t\t\t\t\t\t\t\t\tclass=\"flex w-full flex-col items-start gap-0.5 px-3 py-1.5 text-left text-sm {i ===\n\t\t\t\t\t\t\t\t\tskillMenuIndex\n\t\t\t\t\t\t\t\t\t\t? 'bg-brand-surface-3 text-brand-text'\n\t\t\t\t\t\t\t\t\t\t: 'text-brand-text-muted hover:bg-brand-surface-3/60'}\"\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t<span class=\"font-mono text-brand-text\">/{skill.name}</span>\n\t\t\t\t\t\t\t\t\t{#if skill.description}\n\t\t\t\t\t\t\t\t\t\t<span class=\"line-clamp-1 text-[11px] text-brand-text-muted\"\n\t\t\t\t\t\t\t\t\t\t\t>{skill.description}</span\n\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t\t\t</button>\n\t\t\t\t\t\t\t</li>\n\t\t\t\t\t\t{/each}\n\t\t\t\t\t</ul>\n\t\t\t\t{/if}\n\t\t\t\t<textarea\n\t\t\t\t\tbind:this={textarea}\n\t\t\t\t\tbind:value={text}\n\t\t\t\t\tonkeydown={handleKeydown}\n\t\t\t\t\tdisabled={effectivelyDisabled}\n\t\t\t\t\trows={1}\n\t\t\t\t\tplaceholder={searchMode\n\t\t\t\t\t\t? (placeholder ?? 'Search the web...')\n\t\t\t\t\t\t: !connected\n\t\t\t\t\t\t\t? appState.connecting\n\t\t\t\t\t\t\t\t? 'Reconnecting... you can keep typing'\n\t\t\t\t\t\t\t\t: 'Disconnected - you can type, sending resumes once reconnected'\n\t\t\t\t\t\t\t: streaming\n\t\t\t\t\t\t\t\t? 'Agent is working, Steer to interrupt...'\n\t\t\t\t\t\t\t\t: readOnly\n\t\t\t\t\t\t\t\t\t? 'Read-only mode'\n\t\t\t\t\t\t\t\t\t: !sessionInfo.sessionId\n\t\t\t\t\t\t\t\t\t\t? 'Select a session first...'\n\t\t\t\t\t\t\t\t\t\t: 'Type a message...'}\n\t\t\t\t\tclass=\"h-full max-h-48 min-h-[120px] w-full resize-none overflow-y-auto rounded-lg border border-brand-border bg-brand-surface-2 px-4 py-3 leading-relaxed text-brand-text placeholder-brand-text-muted focus:border-brand-blue focus:outline-none disabled:opacity-50\"\n\t\t\t\t></textarea>\n\t\t\t</div>\n\n\t\t\t<div class=\"flex w-[80px] shrink-0 flex-col justify-end gap-2\">\n\t\t\t\t{#if showAttach}\n\t\t\t\t\t<button\n\t\t\t\t\t\ttype=\"button\"\n\t\t\t\t\t\tonclick={() => {\n\t\t\t\t\t\t\t// Mark the picker active before it opens so the page-hidden\n\t\t\t\t\t\t\t// suspend timer doesn't tear down the session while the user\n\t\t\t\t\t\t\t// takes a photo / browses files.\n\t\t\t\t\t\t\tbeginFilePicker();\n\t\t\t\t\t\t\tfileInput?.click();\n\t\t\t\t\t\t}}\n\t\t\t\t\t\tdisabled={effectivelyDisabled}\n\t\t\t\t\t\tclass=\"flex h-[40px] w-full items-center justify-center rounded-lg border border-brand-border bg-brand-surface-2 text-brand-text-muted transition-colors hover:bg-brand-surface-3 hover:text-brand-text disabled:cursor-not-allowed disabled:opacity-50\"\n\t\t\t\t\t\ttitle=\"Attach file (image or document)\"\n\t\t\t\t\t>\n\t\t\t\t\t\t📎\n\t\t\t\t\t</button>\n\t\t\t\t\t<input\n\t\t\t\t\t\tbind:this={fileInput}\n\t\t\t\t\t\ttype=\"file\"\n\t\t\t\t\t\tmultiple\n\t\t\t\t\t\tonchange={handleFileChange}\n\t\t\t\t\t\tclass=\"hidden\"\n\t\t\t\t\t/>\n\t\t\t\t{/if}\n\t\t\t\t<div class=\"flex w-full justify-center\">\n\t\t\t\t\t<SpeechButton\n\t\t\t\t\t\tbind:this={speechButton}\n\t\t\t\t\t\tbind:text\n\t\t\t\t\t\tbind:activeEngine={speechEngine}\n\t\t\t\t\t\tdisabled={effectivelyDisabled}\n\t\t\t\t\t\tonSend={handleSend}\n\t\t\t\t\t/>\n\t\t\t\t</div>\n\t\t\t\t<button\n\t\t\t\t\ttype=\"submit\"\n\t\t\t\t\tdisabled={!canSend}\n\t\t\t\t\ttitle={!searchMode && streaming\n\t\t\t\t\t\t? 'Steer the agent now (injected at the next step, before the next model call)'\n\t\t\t\t\t\t: undefined}\n\t\t\t\t\tclass=\"flex h-[40px] w-full items-center justify-center rounded-lg bg-gradient-to-r from-brand-cyan to-brand-blue text-xs font-medium text-brand-text transition-all hover:opacity-90 disabled:cursor-not-allowed disabled:bg-brand-surface-3 disabled:from-brand-surface-3 disabled:to-brand-surface-3 disabled:opacity-50\"\n\t\t\t\t>\n\t\t\t\t\t{#if searchMode}\n\t\t\t\t\t\t{submitLabel ?? 'Search'}\n\t\t\t\t\t{:else if streaming}\n\t\t\t\t\t\tSteer\n\t\t\t\t\t{:else}\n\t\t\t\t\t\tSend\n\t\t\t\t\t{/if}\n\t\t\t\t</button>\n\t\t\t</div>\n\t\t</form>\n\n\t\t<div\n\t\t\tclass=\"mt-2 flex flex-wrap items-center justify-between gap-y-1.5 px-1 text-[11px] text-brand-text-muted select-none\"\n\t\t>\n\t\t\t<label\n\t\t\t\tclass=\"flex cursor-pointer items-center gap-1.5 hover:text-brand-text\"\n\t\t\t>\n\t\t\t\t<input\n\t\t\t\t\ttype=\"checkbox\"\n\t\t\t\t\tchecked={enterToSend}\n\t\t\t\t\tonchange={toggleEnterToSend}\n\t\t\t\t\tclass=\"rounded border-brand-border bg-brand-surface-2 text-brand-blue focus:ring-0 focus:ring-offset-0\"\n\t\t\t\t/>\n\t\t\t\t<span>Press Enter to send</span>\n\t\t\t</label>\n\t\t\t<div class=\"flex items-center gap-3\">\n\t\t\t\t<!-- Drafts are available in EVERY composer mode, including the no-session\n\t\t\t\t home page: a draft carries no session dependency, and the home page is\n\t\t\t\t exactly where you want to pull up something written yesterday and fire\n\t\t\t\t it into a new session. Saving needs the server (it is the store), so\n\t\t\t\t the button is disabled while disconnected. -->\n\t\t\t\t<button\n\t\t\t\t\ttype=\"button\"\n\t\t\t\t\tonclick={saveCurrentAsDraft}\n\t\t\t\t\tdisabled={text.trim().length === 0 || !connected}\n\t\t\t\t\ttitle={connected\n\t\t\t\t\t\t? 'Save this message as a draft instead of sending it'\n\t\t\t\t\t\t: 'Drafts are stored on the server, which is not reachable right now'}\n\t\t\t\t\tclass=\"rounded bg-brand-surface-3/50 px-2 py-0.5 text-xs text-brand-text-muted transition-colors hover:bg-brand-surface-3 hover:text-brand-text disabled:cursor-not-allowed disabled:opacity-40\"\n\t\t\t\t>\n\t\t\t\t\t{draftSavedFlash ? '✓ Saved' : '💾 Save draft'}\n\t\t\t\t</button>\n\t\t\t\t<button\n\t\t\t\t\ttype=\"button\"\n\t\t\t\t\tonclick={toggleDrafts}\n\t\t\t\t\ttitle=\"Open saved drafts\"\n\t\t\t\t\taria-expanded={draftsOpen}\n\t\t\t\t\taria-controls=\"drafts-panel\"\n\t\t\t\t\tclass=\"rounded bg-brand-surface-3/50 px-2 py-0.5 text-xs text-brand-text-muted transition-colors hover:bg-brand-surface-3 hover:text-brand-text\"\n\t\t\t\t>\n\t\t\t\t\t🗂 Drafts{drafts.length > 0 ? ` (${drafts.length})` : ''}\n\t\t\t\t</button>\n\t\t\t\t<button\n\t\t\t\t\ttype=\"button\"\n\t\t\t\t\tonclick={() => (isCollapsed = true)}\n\t\t\t\t\tclass=\"rounded bg-brand-surface-3/50 px-2 py-0.5 text-xs text-brand-text-muted transition-colors hover:bg-brand-surface-3 hover:text-brand-text\"\n\t\t\t\t>\n\t\t\t\t\tCollapse ▽\n\t\t\t\t</button>\n\t\t\t\t{#if !enterToSend}\n\t\t\t\t\t<span class=\"hidden font-mono opacity-60 sm:inline\">\n\t\t\t\t\t\tShift+Enter to send\n\t\t\t\t\t</span>\n\t\t\t\t{/if}\n\t\t\t</div>\n\t\t</div>\n\t{/if}\n</div>\n","// Fork-hierarchy ordering for the session sidebar.\n//\n// Sessions in a folder arrive newest-first (server sorts by `modified`), but the\n// sidebar renders them as a TREE: a forked session nests under the session it\n// was forked from. Ordering the tree by each root's OWN `modified` buries an\n// actively-used fork under an old, long-idle parent, since only the fork gets\n// new messages. So a whole fork GROUP (a root plus its descendants) is ranked by\n// its most recent activity ACROSS the group, and siblings are ranked the same\n// way. The parent still renders above its children (the tree shape is the point);\n// what changes is where the group as a whole sits in the list.\n\n/** Minimal shape needed to build/order the tree; matches SessionInfo. */\nexport interface ForkTreeNodeInput {\n\tpath: string;\n\tmodified: string;\n\tparentSessionPath?: string;\n}\n\nexport interface ForkTreeRow<T extends ForkTreeNodeInput> {\n\tsession: T;\n\tdepth: number;\n}\n\n/**\n * Flatten sessions into a depth-first fork tree (mirrors pi's session selector).\n * A session whose `parentSessionPath` matches another session's `path` in this\n * list is nested under it; everything else is a root. Cross-folder parents (a\n * fork into a different cwd) surface as roots, since we only tree WITHIN a\n * folder.\n *\n * Roots and sibling children are ordered by the most recent `modified` in their\n * whole subtree (descending), so a group with an active fork floats to the top\n * even when its root is old. Cycle-safe via a visited set; any session dropped\n * by a cycle is appended at depth 0 so nothing vanishes.\n */\nexport function buildForkTree<T extends ForkTreeNodeInput>(\n\tsessions: readonly T[],\n): ForkTreeRow<T>[] {\n\tconst byPath = new Map<string, T>();\n\tfor (const s of sessions) byPath.set(s.path, s);\n\n\tconst childrenOf = new Map<string, T[]>();\n\tconst roots: T[] = [];\n\tfor (const s of sessions) {\n\t\tconst parent = s.parentSessionPath;\n\t\tif (parent && byPath.has(parent) && parent !== s.path) {\n\t\t\tif (!childrenOf.has(parent)) childrenOf.set(parent, []);\n\t\t\tchildrenOf.get(parent)!.push(s);\n\t\t} else {\n\t\t\troots.push(s);\n\t\t}\n\t}\n\n\t// Most recent `modified` across a session and all its descendants. Memoized,\n\t// and cycle-safe via an in-progress set (a cycle contributes nothing extra).\n\tconst recencyCache = new Map<string, string>();\n\tconst inProgress = new Set<string>();\n\tconst groupRecency = (s: T): string => {\n\t\tconst cached = recencyCache.get(s.path);\n\t\tif (cached !== undefined) return cached;\n\t\tif (inProgress.has(s.path)) return s.modified ?? '';\n\t\tinProgress.add(s.path);\n\t\tlet best = s.modified ?? '';\n\t\tfor (const child of childrenOf.get(s.path) ?? []) {\n\t\t\tconst childBest = groupRecency(child);\n\t\t\tif (childBest.localeCompare(best) > 0) best = childBest;\n\t\t}\n\t\tinProgress.delete(s.path);\n\t\trecencyCache.set(s.path, best);\n\t\treturn best;\n\t};\n\n\t// Newest group first; ties fall back to the session's own `modified` then path\n\t// so the order is stable and deterministic.\n\tconst byRecency = (a: T, b: T): number =>\n\t\tgroupRecency(b).localeCompare(groupRecency(a)) ||\n\t\t(b.modified ?? '').localeCompare(a.modified ?? '') ||\n\t\ta.path.localeCompare(b.path);\n\n\tconst out: ForkTreeRow<T>[] = [];\n\tconst visited = new Set<string>();\n\tconst walk = (s: T, depth: number) => {\n\t\tif (visited.has(s.path)) return;\n\t\tvisited.add(s.path);\n\t\tout.push({session: s, depth});\n\t\tfor (const child of [...(childrenOf.get(s.path) ?? [])].sort(byRecency))\n\t\t\twalk(child, depth + 1);\n\t};\n\tfor (const r of [...roots].sort(byRecency)) walk(r, 0);\n\t// Safety net: include any session dropped by a cycle so nothing vanishes.\n\tfor (const s of sessions)\n\t\tif (!visited.has(s.path)) out.push({session: s, depth: 0});\n\treturn out;\n}\n","<script lang=\"ts\">\n\timport {\n\t\tsessionFolders,\n\t\treadOnlySessionFolders,\n\t\tavailableModels,\n\t\tfetchSessions,\n\t\tfetchReadOnlySessions,\n\t\tfetchModels,\n\t\tfetchConfig,\n\t\tgitInitDefaultStore,\n\t\tcheckPath,\n\t\tautocompletePath,\n\t\tsetCurrentSession,\n\t\tsetSessionStarred,\n\t\ttype ModelInfo,\n\t\ttype FolderWithSessions,\n\t} from '$lib/session-store';\n\t// Fork-hierarchy flattening + recency ordering (unit-tested in core).\n\timport {buildForkTree} from '$lib/core/fork-tree.js';\n\n\t// When true, this browser shows the read-only sessions page: it sources from\n\t// the read-only folder list, hides the create form, and hides all delete\n\t// controls. Opening a session here is forced read-only by the server.\n\t// `onSearchAll` hands the typed filter text over to conversation search (which\n\t// searches message CONTENT server-side, not just the names/previews in this\n\t// list); the filter box itself is unchanged.\n\tlet {\n\t\treadOnly = false,\n\t\tonSearchAll,\n\t}: {readOnly?: boolean; onSearchAll?: (query: string) => void} = $props();\n\timport {\n\t\tjoinSession,\n\t\tswitchSession,\n\t\tcreateSession,\n\t\tleaveSession,\n\t\tactiveSessionInfo,\n\t\tisConnected,\n\t\tisLoadingSession,\n\t\tisResyncing,\n\t\tsessionError,\n\t\tdismissSessionError,\n\t\tdeleteSession,\n\t} from '$lib/wherever';\n\n\tlet folders = $derived(\n\t\treadOnly ? $readOnlySessionFolders.folders : $sessionFolders.folders,\n\t);\n\tlet loading = $derived(\n\t\treadOnly ? $readOnlySessionFolders.loading : $sessionFolders.loading,\n\t);\n\n\tfunction refresh() {\n\t\tif (readOnly) {\n\t\t\tfetchReadOnlySessions();\n\t\t} else {\n\t\t\tfetchSessions();\n\t\t}\n\t}\n\tlet currentSession = $derived($activeSessionInfo.sessionFile);\n\tlet connected = $derived($isConnected);\n\tlet loadingSession = $derived($isLoadingSession);\n\tlet resyncing = $derived($isResyncing);\n\tlet models = $derived($availableModels.models);\n\n\tlet expanded = $state<Record<string, boolean>>({});\n\tlet searchExpanded = $state<Record<string, boolean>>({});\n\tlet confirmingDelete = $state<string | null>(null);\n\tlet confirmingDeleteFolder = $state<string | null>(null);\n\tlet searchQuery = $state('');\n\tlet filteredFolders = $state<FolderWithSessions[]>([]);\n\n\t// Auto-fetch sessions on connect and periodically\n\t$effect(() => {\n\t\tif (connected) {\n\t\t\trefresh();\n\t\t\tif (!readOnly) {\n\t\t\t\tfetchModels();\n\t\t\t\tfetchConfig();\n\t\t\t}\n\t\t}\n\t});\n\n\tfunction matchesFilter(\n\t\tsession: (typeof folders)[number]['sessions'][number],\n\t\tfolderName: string,\n\t\tquery: string,\n\t): boolean {\n\t\tif (!query) return true;\n\t\tconst q = query.toLowerCase();\n\t\treturn (\n\t\t\t(session.name || '').toLowerCase().includes(q) ||\n\t\t\tsession.firstMessage.toLowerCase().includes(q) ||\n\t\t\tfolderName.toLowerCase().includes(q)\n\t\t);\n\t}\n\n\t$effect(() => {\n\t\tconst q = searchQuery;\n\t\tconst foldersArr = folders;\n\t\tif (!q) {\n\t\t\tfilteredFolders = foldersArr;\n\t\t\tsearchExpanded = {};\n\t\t} else {\n\t\t\tfilteredFolders = foldersArr\n\t\t\t\t.map((folder) => ({\n\t\t\t\t\t...folder,\n\t\t\t\t\tsessions: folder.sessions.filter(\n\t\t\t\t\t\t(s: (typeof folder)['sessions'][number]) =>\n\t\t\t\t\t\t\tmatchesFilter(s, folder.name, q),\n\t\t\t\t\t),\n\t\t\t\t}))\n\t\t\t\t.filter((folder) => folder.sessions.length > 0);\n\t\t}\n\t});\n\n\tfunction toggleStar(sessionPath: string, starred: boolean) {\n\t\t// Optimistic in the store; a refusal is rolled back there and logged.\n\t\tsetSessionStarred(sessionPath, starred).catch(() => {});\n\t}\n\n\tfunction isFolderExpanded(folderPath: string): boolean {\n\t\tif (searchQuery) {\n\t\t\tif (searchExpanded[folderPath] !== undefined) {\n\t\t\t\treturn searchExpanded[folderPath];\n\t\t\t}\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn !!expanded[folderPath];\n\t\t}\n\t}\n\n\tfunction toggleFolder(path: string) {\n\t\tif (searchQuery) {\n\t\t\tsearchExpanded[path] = !isFolderExpanded(path);\n\t\t} else {\n\t\t\texpanded[path] = !isFolderExpanded(path);\n\t\t}\n\t}\n\n\tasync function handleDeleteSession(sessionPath: string) {\n\t\ttry {\n\t\t\tif (currentSession === sessionPath) {\n\t\t\t\tif (typeof window !== 'undefined') {\n\t\t\t\t\twindow.location.hash = '';\n\t\t\t\t}\n\t\t\t\tleaveSession();\n\t\t\t}\n\t\t\tawait deleteSession(sessionPath);\n\t\t\tif (confirmingDelete === sessionPath) {\n\t\t\t\tconfirmingDelete = null;\n\t\t\t}\n\t\t\tfetchSessions();\n\t\t} catch (err) {\n\t\t\tconsole.error('Failed to delete session:', err);\n\t\t}\n\t}\n\n\tasync function handleDeleteAllFolderSessions(folder: FolderWithSessions) {\n\t\ttry {\n\t\t\tconst sessionPaths = folder.sessions.map((s) => s.path);\n\t\t\tif (currentSession && sessionPaths.includes(currentSession)) {\n\t\t\t\tif (typeof window !== 'undefined') {\n\t\t\t\t\twindow.location.hash = '';\n\t\t\t\t}\n\t\t\t\tleaveSession();\n\t\t\t}\n\t\t\tawait Promise.all(folder.sessions.map((s) => deleteSession(s.path)));\n\t\t\tif (confirmingDeleteFolder === folder.path) {\n\t\t\t\tconfirmingDeleteFolder = null;\n\t\t\t}\n\t\t\tfetchSessions();\n\t\t} catch (err) {\n\t\t\tconsole.error('Failed to delete all sessions of folder:', err);\n\t\t}\n\t}\n\n\tfunction handleSessionClick(sessionPath: string) {\n\t\t// Tapping the already-active session (and not currently loading) is a no-op.\n\t\tif (currentSession === sessionPath && !loadingSession && !resyncing) return;\n\t\tdismissSessionError();\n\t\t// One atomic switch: leave the current session (if any) and load the target.\n\t\t// switchSession supersedes any in-flight load and rearms the load watchdog, so\n\t\t// a stuck/hung load never blocks tapping a different session, and the latest\n\t\t// tap always wins (no fragile leave -> setTimeout -> join gap).\n\t\tswitchSession(sessionPath);\n\t}\n\n\t// Collapsible Sidebar form state\n\tlet createFormOpen = $state(false);\n\tlet sidebarCwd = $state('');\n\tlet sidebarCompletions = $state<string[]>([]);\n\tlet sidebarInputFocused = $state(false);\n\tlet sidebarInputEl = $state<HTMLInputElement | null>(null);\n\tlet sidebarContainerEl = $state<HTMLDivElement | null>(null);\n\tlet lastCheckedSidebarPath = '';\n\tlet sidebarModel = $state('');\n\tlet sidebarGitInit = $state(false);\n\tlet userManualSidebarGitInit = $state<boolean | null>(null);\n\tlet sidebarCreateRemote = $state(true);\n\tlet sidebarRepoVisibility = $state<'private' | 'public'>('private');\n\tlet showSidebarGitConfirmModal = $state(false);\n\n\tlet defaultGitInit = $derived($gitInitDefaultStore);\n\n\t// Sync git init default\n\t$effect(() => {\n\t\tif (userManualSidebarGitInit === null) {\n\t\t\tsidebarGitInit = defaultGitInit;\n\t\t}\n\t});\n\n\tlet sidebarPathStatus = $state<{\n\t\texists: boolean | null;\n\t\tisGit: boolean;\n\t\tresolvedPath: string;\n\t\tmatchingRule: {provider: string; visibility: string} | null;\n\t}>({\n\t\texists: null,\n\t\tisGit: false,\n\t\tresolvedPath: '',\n\t\tmatchingRule: null,\n\t});\n\n\tlet isSidebarRemoteRepoCreation = $derived(\n\t\tsidebarPathStatus.exists !== true &&\n\t\t\tsidebarPathStatus.matchingRule &&\n\t\t\tsidebarCreateRemote,\n\t);\n\n\tlet sidebarPathCheckTimeout: ReturnType<typeof setTimeout> | null = null;\n\n\tasync function triggerSidebarCheck(pathValue: string, immediate = false) {\n\t\tif (sidebarPathCheckTimeout) clearTimeout(sidebarPathCheckTimeout);\n\n\t\tif (pathValue === lastCheckedSidebarPath && !immediate) return;\n\t\tlastCheckedSidebarPath = pathValue;\n\n\t\tif (!pathValue.trim()) {\n\t\t\tsidebarPathStatus = {\n\t\t\t\texists: null,\n\t\t\t\tisGit: false,\n\t\t\t\tresolvedPath: '',\n\t\t\t\tmatchingRule: null,\n\t\t\t};\n\t\t\tconst fetchEmpty = async () => {\n\t\t\t\tconst list = await autocompletePath('');\n\t\t\t\tsidebarCompletions = list || [];\n\t\t\t};\n\t\t\tif (immediate) {\n\t\t\t\tawait fetchEmpty();\n\t\t\t} else {\n\t\t\t\tsidebarPathCheckTimeout = setTimeout(fetchEmpty, 300);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tconst fetchFn = async () => {\n\t\t\tconst [res, list] = await Promise.all([\n\t\t\t\tcheckPath(pathValue),\n\t\t\t\tautocompletePath(pathValue),\n\t\t\t]);\n\t\t\tsidebarCompletions = list || [];\n\t\t\tif (res) {\n\t\t\t\tsidebarPathStatus = {\n\t\t\t\t\texists: res.exists,\n\t\t\t\t\tisGit: res.isGit,\n\t\t\t\t\tresolvedPath: res.resolvedPath,\n\t\t\t\t\tmatchingRule: (res as any).matchingRule || null,\n\t\t\t\t};\n\t\t\t\tif (!res.exists) {\n\t\t\t\t\tsidebarGitInit =\n\t\t\t\t\t\tuserManualSidebarGitInit !== null\n\t\t\t\t\t\t\t? userManualSidebarGitInit\n\t\t\t\t\t\t\t: defaultGitInit;\n\t\t\t\t\tsidebarCreateRemote = true; // reset to true for non-existing folders\n\t\t\t\t\tif ((res as any).matchingRule) {\n\t\t\t\t\t\tsidebarRepoVisibility = (res as any).matchingRule.visibility as\n\t\t\t\t\t\t\t| 'private'\n\t\t\t\t\t\t\t| 'public';\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tsidebarPathStatus = {\n\t\t\t\t\texists: null,\n\t\t\t\t\tisGit: false,\n\t\t\t\t\tresolvedPath: '',\n\t\t\t\t\tmatchingRule: null,\n\t\t\t\t};\n\t\t\t}\n\t\t};\n\n\t\tif (immediate) {\n\t\t\tawait fetchFn();\n\t\t} else {\n\t\t\tsidebarPathCheckTimeout = setTimeout(fetchFn, 300);\n\t\t}\n\t}\n\n\t$effect(() => {\n\t\tconst pathValue = sidebarCwd;\n\t\ttriggerSidebarCheck(pathValue, false);\n\t});\n\n\t// Select default model if any\n\t$effect(() => {\n\t\tif (models.length > 0 && !sidebarModel) {\n\t\t\tconst defaultModel = models.find((m: ModelInfo) => m.isDefault);\n\t\t\tif (defaultModel) {\n\t\t\t\tsidebarModel = `${defaultModel.provider}:${defaultModel.modelId}`;\n\t\t\t} else {\n\t\t\t\tsidebarModel = `${models[0].provider}:${models[0].modelId}`;\n\t\t\t}\n\t\t}\n\t});\n\n\tfunction handleSidebarCreateSession() {\n\t\tif (!sidebarCwd.trim()) return;\n\t\tif (sidebarPathStatus.exists === true) {\n\t\t\tsidebarGitInit = false; // toggled off by default in modal\n\t\t\tsidebarCreateRemote = false; // toggled off by default in modal\n\t\t\tif (sidebarPathStatus.matchingRule) {\n\t\t\t\tsidebarRepoVisibility = sidebarPathStatus.matchingRule.visibility as\n\t\t\t\t\t| 'private'\n\t\t\t\t\t| 'public';\n\t\t\t}\n\t\t\tshowSidebarGitConfirmModal = true;\n\t\t} else {\n\t\t\tdismissSessionError();\n\t\t\tconst cwd = sidebarCwd.trim();\n\t\t\tconst model = sidebarModel || undefined;\n\t\t\tconst gitInit = sidebarGitInit;\n\t\t\tconst createRemote = sidebarPathStatus.matchingRule\n\t\t\t\t? sidebarCreateRemote\n\t\t\t\t: undefined;\n\t\t\tconst repoVisibility = sidebarPathStatus.matchingRule\n\t\t\t\t? sidebarRepoVisibility\n\t\t\t\t: undefined;\n\n\t\t\t// Reset state\n\t\t\tsidebarCwd = '';\n\t\t\tcreateFormOpen = false;\n\n\t\t\tif (currentSession) {\n\t\t\t\tleaveSession();\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tcreateSession(cwd, model, gitInit, createRemote, repoVisibility);\n\t\t\t\t}, 100);\n\t\t\t} else {\n\t\t\t\tcreateSession(cwd, model, gitInit, createRemote, repoVisibility);\n\t\t\t}\n\t\t}\n\t}\n\n\tfunction handleSidebarConfirmModalSubmit() {\n\t\tshowSidebarGitConfirmModal = false;\n\t\tdismissSessionError();\n\t\tconst cwd = sidebarCwd.trim();\n\t\tconst model = sidebarModel || undefined;\n\t\tconst gitInit = sidebarGitInit;\n\t\tconst createRemote = sidebarPathStatus.matchingRule\n\t\t\t? sidebarCreateRemote\n\t\t\t: undefined;\n\t\tconst repoVisibility = sidebarPathStatus.matchingRule\n\t\t\t? sidebarRepoVisibility\n\t\t\t: undefined;\n\n\t\t// Reset state\n\t\tsidebarCwd = '';\n\t\tcreateFormOpen = false;\n\n\t\tif (currentSession) {\n\t\t\tleaveSession();\n\t\t\tsetTimeout(() => {\n\t\t\t\tcreateSession(cwd, model, gitInit, createRemote, repoVisibility);\n\t\t\t}, 100);\n\t\t} else {\n\t\t\tcreateSession(cwd, model, gitInit, createRemote, repoVisibility);\n\t\t}\n\t}\n\n\t// New session picker state\n\tlet newSessionPicker = $state<{\n\t\topen: boolean;\n\t\tfolderPath: string;\n\t\tselected: string;\n\t}>({\n\t\topen: false,\n\t\tfolderPath: '',\n\t\tselected: '',\n\t});\n\n\tfunction openNewSessionPicker(folderPath: string) {\n\t\tconst defaultModel = models.find((m: ModelInfo) => m.isDefault);\n\t\tnewSessionPicker = {\n\t\t\topen: true,\n\t\t\tfolderPath,\n\t\t\tselected: defaultModel\n\t\t\t\t? `${defaultModel.provider}:${defaultModel.modelId}`\n\t\t\t\t: '',\n\t\t};\n\t}\n\n\tfunction closeNewSessionPicker() {\n\t\tnewSessionPicker.open = false;\n\t}\n\n\tfunction handleCreateSession() {\n\t\tif (!newSessionPicker.open) return;\n\t\tdismissSessionError();\n\t\tconst folderPath = newSessionPicker.folderPath;\n\t\tconst model = newSessionPicker.selected || undefined;\n\t\tcloseNewSessionPicker();\n\t\tif (currentSession) {\n\t\t\tleaveSession();\n\t\t\tsetTimeout(() => {\n\t\t\t\tcreateSession(folderPath, model);\n\t\t\t}, 100);\n\t\t} else {\n\t\t\tcreateSession(folderPath, model);\n\t\t}\n\t}\n\n\tfunction formatRelative(timeStr: string): string {\n\t\tconst diff = Date.now() - new Date(timeStr).getTime();\n\t\tconst mins = Math.floor(diff / 60000);\n\t\tif (mins < 1) return 'just now';\n\t\tif (mins < 60) return `${mins}m ago`;\n\t\tconst hours = Math.floor(mins / 60);\n\t\tif (hours < 24) return `${hours}h ago`;\n\t\tconst days = Math.floor(hours / 24);\n\t\treturn `${days}d ago`;\n\t}\n\n\tfunction truncate(text: string, max: number = 40): string {\n\t\treturn text.length > max ? text.slice(0, max) + '...' : text;\n\t}\n</script>\n\n<div class=\"flex h-full flex-col\">\n\t<div class=\"border-b border-brand-border/50 p-2\">\n\t\t<div class=\"flex gap-1.5\">\n\t\t\t<input\n\t\t\t\ttype=\"text\"\n\t\t\t\tplaceholder=\"Filter sessions...\"\n\t\t\t\tvalue={searchQuery}\n\t\t\t\toninput={(e) => (searchQuery = e.currentTarget.value)}\n\t\t\t\tclass=\"min-w-0 flex-1 rounded border border-brand-border bg-brand-surface-2 px-2 py-1.5 text-xs text-brand-text placeholder-brand-text-muted focus:border-brand-blue focus:outline-none\"\n\t\t\t/>\n\t\t\t<button\n\t\t\t\ttype=\"button\"\n\t\t\t\tonclick={() => refresh()}\n\t\t\t\tclass=\"flex shrink-0 items-center justify-center rounded border border-brand-border bg-brand-surface-2 px-1.5 py-1.5 text-brand-text-muted transition-colors hover:bg-brand-surface-3 hover:text-brand-text\"\n\t\t\t\ttitle=\"Refresh session list\"\n\t\t\t>\n\t\t\t\t<span class={loading ? 'animate-spin' : ''}>↻</span>\n\t\t\t</button>\n\t\t</div>\n\t\t{#if onSearchAll && searchQuery.trim().length >= 2}\n\t\t\t<!-- The box above only filters this list (names + first-message previews).\n\t\t\t This is the way over to full-text search across every message. -->\n\t\t\t<button\n\t\t\t\ttype=\"button\"\n\t\t\t\tonclick={() => onSearchAll?.(searchQuery.trim())}\n\t\t\t\tclass=\"mt-1.5 w-full truncate rounded px-1 py-0.5 text-left text-[10px] text-brand-blue hover:underline\"\n\t\t\t>\n\t\t\t\t🔎 Search all conversations for “{searchQuery.trim()}”\n\t\t\t</button>\n\t\t{/if}\n\t</div>\n\n\t<div class=\"flex-1 overflow-y-auto\">\n\t\t<!-- Collapsible Create New Session Section (hidden in read-only mode) -->\n\t\t{#if !readOnly}\n\t\t\t<div class=\"border-b border-brand-border/50 bg-brand-surface/10\">\n\t\t\t\t<button\n\t\t\t\t\tonclick={() => (createFormOpen = !createFormOpen)}\n\t\t\t\t\tclass=\"flex w-full items-center justify-between px-3 py-2 text-left text-xs font-semibold text-brand-blue transition-colors hover:bg-brand-surface-3/30\"\n\t\t\t\t>\n\t\t\t\t\t<span\n\t\t\t\t\t\t>{createFormOpen\n\t\t\t\t\t\t\t? '▼ Close Create Session'\n\t\t\t\t\t\t\t: '✚ Create New Session'}</span\n\t\t\t\t\t>\n\t\t\t\t</button>\n\n\t\t\t\t{#if createFormOpen}\n\t\t\t\t\t<form\n\t\t\t\t\t\tonsubmit={(e) => {\n\t\t\t\t\t\t\te.preventDefault();\n\t\t\t\t\t\t\thandleSidebarCreateSession();\n\t\t\t\t\t\t}}\n\t\t\t\t\t\tclass=\"space-y-2.5 border-t border-brand-border/30 bg-brand-surface/30 p-3\"\n\t\t\t\t\t>\n\t\t\t\t\t\t<div>\n\t\t\t\t\t\t\t<label\n\t\t\t\t\t\t\t\tclass=\"mb-1 block text-[10px] font-bold tracking-wider text-brand-text-muted uppercase\"\n\t\t\t\t\t\t\t\tfor=\"sidebar-folder\">Folder Path</label\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t<div class=\"relative\" bind:this={sidebarContainerEl}>\n\t\t\t\t\t\t\t\t<input\n\t\t\t\t\t\t\t\t\tbind:this={sidebarInputEl}\n\t\t\t\t\t\t\t\t\tid=\"sidebar-folder\"\n\t\t\t\t\t\t\t\t\ttype=\"text\"\n\t\t\t\t\t\t\t\t\tautocomplete=\"off\"\n\t\t\t\t\t\t\t\t\tspellcheck=\"false\"\n\t\t\t\t\t\t\t\t\tplaceholder=\"e.g. ~/projects/my-new-app\"\n\t\t\t\t\t\t\t\t\tbind:value={sidebarCwd}\n\t\t\t\t\t\t\t\t\tonfocus={() => {\n\t\t\t\t\t\t\t\t\t\tsidebarInputFocused = true;\n\t\t\t\t\t\t\t\t\t\ttriggerSidebarCheck(sidebarCwd, true);\n\t\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t\t\tonblur={(e) => {\n\t\t\t\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t\t\t\tsidebarContainerEl &&\n\t\t\t\t\t\t\t\t\t\t\tsidebarContainerEl.contains(e.relatedTarget as Node)\n\t\t\t\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\tsidebarInputFocused = false;\n\t\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t\t\tonkeydown={(e) => {\n\t\t\t\t\t\t\t\t\t\tif (e.key === 'Escape') {\n\t\t\t\t\t\t\t\t\t\t\tsidebarInputFocused = false;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t\t\tclass=\"w-full rounded border px-2 py-1 text-xs text-brand-text placeholder-brand-text-muted transition-all duration-200 focus:outline-none {isSidebarRemoteRepoCreation\n\t\t\t\t\t\t\t\t\t\t? 'border-emerald-500/80 bg-emerald-500/10 focus:border-emerald-400 focus:ring-1 focus:ring-emerald-400/30'\n\t\t\t\t\t\t\t\t\t\t: 'border-brand-border bg-brand-dark/60 focus:border-brand-blue'}\"\n\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t\t{#if sidebarInputFocused && sidebarCompletions.length > 0}\n\t\t\t\t\t\t\t\t\t<div\n\t\t\t\t\t\t\t\t\t\tclass=\"absolute right-0 left-0 z-50 mt-1 max-h-40 overflow-y-auto rounded border border-brand-border bg-brand-surface-2 py-1 shadow-xl\"\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t{#each sidebarCompletions as completion}\n\t\t\t\t\t\t\t\t\t\t\t<button\n\t\t\t\t\t\t\t\t\t\t\t\ttype=\"button\"\n\t\t\t\t\t\t\t\t\t\t\t\tonclick={() => {\n\t\t\t\t\t\t\t\t\t\t\t\t\tsidebarCwd = completion;\n\t\t\t\t\t\t\t\t\t\t\t\t\ttriggerSidebarCheck(completion, true);\n\t\t\t\t\t\t\t\t\t\t\t\t\tsidebarInputEl?.focus();\n\t\t\t\t\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t\t\t\t\t\tclass=\"block w-full px-2.5 py-1 text-left text-xs text-brand-text transition-colors hover:bg-brand-surface-3 hover:text-brand-text\"\n\t\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t\t{completion}\n\t\t\t\t\t\t\t\t\t\t\t</button>\n\t\t\t\t\t\t\t\t\t\t{/each}\n\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t{#if sidebarPathStatus.exists === true}\n\t\t\t\t\t\t\t\t<span\n\t\t\t\t\t\t\t\t\tclass=\"mt-1 block text-[10px] font-medium text-yellow-400\"\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t📁 Folder already exists.\n\t\t\t\t\t\t\t\t\t{#if sidebarPathStatus.isGit}\n\t\t\t\t\t\t\t\t\t\t<span class=\"ml-1 font-semibold text-emerald-400\"\n\t\t\t\t\t\t\t\t\t\t\t>(Git repo)</span\n\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t\t\t</span>\n\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t</div>\n\n\t\t\t\t\t\t<div>\n\t\t\t\t\t\t\t<label\n\t\t\t\t\t\t\t\tclass=\"mb-1 block text-[10px] font-bold tracking-wider text-brand-text-muted uppercase\"\n\t\t\t\t\t\t\t\tfor=\"sidebar-model\">Model</label\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t{#if models.length > 0}\n\t\t\t\t\t\t\t\t<select\n\t\t\t\t\t\t\t\t\tid=\"sidebar-model\"\n\t\t\t\t\t\t\t\t\tbind:value={sidebarModel}\n\t\t\t\t\t\t\t\t\tclass=\"w-full rounded border border-brand-border bg-brand-dark/60 px-2 py-1 text-xs text-brand-text focus:border-brand-blue focus:outline-none\"\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t{#each models as model}\n\t\t\t\t\t\t\t\t\t\t<option value={`${model.provider}:${model.modelId}`}>\n\t\t\t\t\t\t\t\t\t\t\t{model.label}{model.isDefault ? ' (default)' : ''}\n\t\t\t\t\t\t\t\t\t\t</option>\n\t\t\t\t\t\t\t\t\t{/each}\n\t\t\t\t\t\t\t\t</select>\n\t\t\t\t\t\t\t{:else}\n\t\t\t\t\t\t\t\t<input\n\t\t\t\t\t\t\t\t\tid=\"sidebar-model\"\n\t\t\t\t\t\t\t\t\ttype=\"text\"\n\t\t\t\t\t\t\t\t\tbind:value={sidebarModel}\n\t\t\t\t\t\t\t\t\tplaceholder=\"provider:model\"\n\t\t\t\t\t\t\t\t\tclass=\"w-full rounded border border-brand-border bg-brand-dark/60 px-2 py-1 text-xs text-brand-text placeholder-brand-text-muted focus:border-brand-blue focus:outline-none\"\n\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t</div>\n\n\t\t\t\t\t\t{#if sidebarPathStatus.exists !== true && sidebarPathStatus.matchingRule}\n\t\t\t\t\t\t\t<div class=\"space-y-1 py-0.5\">\n\t\t\t\t\t\t\t\t<div class=\"flex items-center gap-1.5\">\n\t\t\t\t\t\t\t\t\t<input\n\t\t\t\t\t\t\t\t\t\tid=\"sidebar-create-remote\"\n\t\t\t\t\t\t\t\t\t\ttype=\"checkbox\"\n\t\t\t\t\t\t\t\t\t\tbind:checked={sidebarCreateRemote}\n\t\t\t\t\t\t\t\t\t\tclass=\"h-3.5 w-3.5 rounded border-brand-border bg-brand-surface-2 text-brand-blue focus:ring-brand-blue focus:ring-offset-brand-surface\"\n\t\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t\t\t<label\n\t\t\t\t\t\t\t\t\t\tfor=\"sidebar-create-remote\"\n\t\t\t\t\t\t\t\t\t\tclass=\"cursor-pointer text-xs text-brand-text select-none\"\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\tCreate remote {sidebarPathStatus.matchingRule.provider} repository\n\t\t\t\t\t\t\t\t\t</label>\n\t\t\t\t\t\t\t\t</div>\n\n\t\t\t\t\t\t\t\t{#if sidebarCreateRemote}\n\t\t\t\t\t\t\t\t\t<div\n\t\t\t\t\t\t\t\t\t\tclass=\"flex items-center gap-3 pl-5 text-[10px] text-brand-text-muted\"\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t<span>Visibility:</span>\n\t\t\t\t\t\t\t\t\t\t<label\n\t\t\t\t\t\t\t\t\t\t\tclass=\"flex cursor-pointer items-center gap-1 transition-colors select-none hover:text-brand-text\"\n\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t<input\n\t\t\t\t\t\t\t\t\t\t\t\ttype=\"radio\"\n\t\t\t\t\t\t\t\t\t\t\t\tname=\"sidebar-visibility\"\n\t\t\t\t\t\t\t\t\t\t\t\tvalue=\"private\"\n\t\t\t\t\t\t\t\t\t\t\t\tbind:group={sidebarRepoVisibility}\n\t\t\t\t\t\t\t\t\t\t\t\tclass=\"border-brand-border bg-brand-surface-2 text-brand-blue focus:ring-brand-blue\"\n\t\t\t\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t\t\t\t\tPrivate\n\t\t\t\t\t\t\t\t\t\t</label>\n\t\t\t\t\t\t\t\t\t\t<label\n\t\t\t\t\t\t\t\t\t\t\tclass=\"flex cursor-pointer items-center gap-1 transition-colors select-none hover:text-brand-text\"\n\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t<input\n\t\t\t\t\t\t\t\t\t\t\t\ttype=\"radio\"\n\t\t\t\t\t\t\t\t\t\t\t\tname=\"sidebar-visibility\"\n\t\t\t\t\t\t\t\t\t\t\t\tvalue=\"public\"\n\t\t\t\t\t\t\t\t\t\t\t\tbind:group={sidebarRepoVisibility}\n\t\t\t\t\t\t\t\t\t\t\t\tclass=\"border-brand-border bg-brand-surface-2 text-brand-blue focus:ring-brand-blue\"\n\t\t\t\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t\t\t\t\tPublic\n\t\t\t\t\t\t\t\t\t\t</label>\n\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t{/if}\n\n\t\t\t\t\t\t{#if sidebarPathStatus.exists !== true && (!sidebarPathStatus.matchingRule || !sidebarCreateRemote)}\n\t\t\t\t\t\t\t<div class=\"flex items-center gap-1.5 py-0.5\">\n\t\t\t\t\t\t\t\t<input\n\t\t\t\t\t\t\t\t\tid=\"sidebar-git-init\"\n\t\t\t\t\t\t\t\t\ttype=\"checkbox\"\n\t\t\t\t\t\t\t\t\tbind:checked={sidebarGitInit}\n\t\t\t\t\t\t\t\t\tonchange={(e) => {\n\t\t\t\t\t\t\t\t\t\tuserManualSidebarGitInit = e.currentTarget.checked;\n\t\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t\t\tclass=\"h-3.5 w-3.5 rounded border-brand-border bg-brand-surface-2 text-brand-blue focus:ring-brand-blue focus:ring-offset-brand-surface\"\n\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t\t<label\n\t\t\t\t\t\t\t\t\tfor=\"sidebar-git-init\"\n\t\t\t\t\t\t\t\t\tclass=\"cursor-pointer text-xs text-brand-text select-none\"\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\tInitialize Git repository\n\t\t\t\t\t\t\t\t</label>\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t{/if}\n\n\t\t\t\t\t\t<button\n\t\t\t\t\t\t\ttype=\"submit\"\n\t\t\t\t\t\t\tdisabled={!sidebarCwd.trim()}\n\t\t\t\t\t\t\tclass=\"w-full rounded bg-gradient-to-r from-brand-cyan to-brand-blue py-1.5 text-xs font-semibold text-brand-text transition-all hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-50\"\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\tCreate Session\n\t\t\t\t\t\t</button>\n\t\t\t\t\t</form>\n\t\t\t\t{/if}\n\t\t\t</div>\n\t\t{/if}\n\n\t\t{#if loading && filteredFolders.length === 0}\n\t\t\t<div class=\"p-4 text-center text-brand-text-muted\">\n\t\t\t\t<div\n\t\t\t\t\tclass=\"inline-block h-4 w-4 animate-spin rounded-full border-2 border-brand-text-muted border-t-transparent\"\n\t\t\t\t></div>\n\t\t\t\t<span class=\"ml-2 text-sm\">Loading sessions...</span>\n\t\t\t</div>\n\t\t{:else if filteredFolders.length === 0}\n\t\t\t<div class=\"p-4 text-center text-sm text-brand-text-muted\">\n\t\t\t\t{searchQuery ? 'No sessions match your filter' : 'No sessions found'}\n\t\t\t</div>\n\t\t{:else}\n\t\t\t{#each filteredFolders as folder (folder.path)}\n\t\t\t\t<div class=\"border-b border-brand-border/50\">\n\t\t\t\t\t<button\n\t\t\t\t\t\tonclick={() => toggleFolder(folder.path)}\n\t\t\t\t\t\tclass=\"flex w-full items-center gap-2 px-3 py-2 text-left transition-colors hover:bg-brand-surface-3/50\"\n\t\t\t\t\t>\n\t\t\t\t\t\t<span\n\t\t\t\t\t\t\tclass=\"text-xs text-brand-text-muted transition-transform {isFolderExpanded(\n\t\t\t\t\t\t\t\tfolder.path,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t? 'rotate-90'\n\t\t\t\t\t\t\t\t: ''}\"\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t▶\n\t\t\t\t\t\t</span>\n\t\t\t\t\t\t<div class=\"min-w-0 flex-1\">\n\t\t\t\t\t\t\t<div class=\"flex items-center gap-1.5\">\n\t\t\t\t\t\t\t\t<div class=\"truncate text-sm font-medium text-brand-text\">\n\t\t\t\t\t\t\t\t\t{folder.name}\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t<!-- The folder is not on this machine (a synced transcript whose\n\t\t\t\t\t\t\t\t clone never travelled). Its own marker, deliberately NOT the\n\t\t\t\t\t\t\t\t read-only treatment: read-only is a CONFIGURED policy and\n\t\t\t\t\t\t\t\t lives as a whole separate page, while this is a fact about\n\t\t\t\t\t\t\t\t the disk and is curable by a restore. Both can be true of one\n\t\t\t\t\t\t\t\t folder, so they must never look like one thing. -->\n\t\t\t\t\t\t\t\t{#if folder.missing}\n\t\t\t\t\t\t\t\t\t<span\n\t\t\t\t\t\t\t\t\t\tclass=\"flex-shrink-0 rounded border border-brand-purple/50 bg-brand-purple/15 px-1.5 py-px text-[10px] font-semibold tracking-wide text-brand-purple uppercase\"\n\t\t\t\t\t\t\t\t\t\ttitle=\"This folder does not exist on this machine. Open a session in it to clone or create it.\"\n\t\t\t\t\t\t\t\t\t\t>Missing</span\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t<div class=\"truncate text-[10px] text-brand-text-muted\">\n\t\t\t\t\t\t\t\t{folder.path}\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t<span class=\"text-xs text-brand-text-muted\"\n\t\t\t\t\t\t\t>{folder.sessions.length}</span\n\t\t\t\t\t\t>\n\t\t\t\t\t</button>\n\n\t\t\t\t\t{#if isFolderExpanded(folder.path)}\n\t\t\t\t\t\t<div class=\"px-3 pb-2\">\n\t\t\t\t\t\t\t{#if !readOnly}\n\t\t\t\t\t\t\t\t<div class=\"mb-1.5 flex items-center justify-between\">\n\t\t\t\t\t\t\t\t\t<button\n\t\t\t\t\t\t\t\t\t\tonclick={() => openNewSessionPicker(folder.path)}\n\t\t\t\t\t\t\t\t\t\tclass=\"rounded px-2 py-1 text-left text-xs text-brand-blue transition-colors hover:bg-brand-surface-3/50 hover:opacity-90\"\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t+ New Session Here\n\t\t\t\t\t\t\t\t\t</button>\n\t\t\t\t\t\t\t\t\t<div class=\"flex-shrink-0\">\n\t\t\t\t\t\t\t\t\t\t{#if confirmingDeleteFolder === folder.path}\n\t\t\t\t\t\t\t\t\t\t\t<div\n\t\t\t\t\t\t\t\t\t\t\t\tclass=\"flex items-center gap-1 rounded border border-red-500/30 bg-brand-surface-2/80 px-1 py-0.5\"\n\t\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t\t<button\n\t\t\t\t\t\t\t\t\t\t\t\t\tonclick={(e) => {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\te.stopPropagation();\n\t\t\t\t\t\t\t\t\t\t\t\t\t\thandleDeleteAllFolderSessions(folder);\n\t\t\t\t\t\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t\t\t\t\t\t\tclass=\"px-1.5 text-xs font-bold text-rose-400 hover:text-rose-300 focus:outline-none\"\n\t\t\t\t\t\t\t\t\t\t\t\t\ttitle=\"Confirm Delete All\"\n\t\t\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t\t\tDelete All?\n\t\t\t\t\t\t\t\t\t\t\t\t</button>\n\t\t\t\t\t\t\t\t\t\t\t\t<button\n\t\t\t\t\t\t\t\t\t\t\t\t\tonclick={(e) => {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\te.stopPropagation();\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconfirmingDeleteFolder = null;\n\t\t\t\t\t\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t\t\t\t\t\t\tclass=\"px-1.5 text-[10px] text-brand-text-muted hover:text-brand-text focus:outline-none\"\n\t\t\t\t\t\t\t\t\t\t\t\t\ttitle=\"Cancel\"\n\t\t\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t\t\t✕\n\t\t\t\t\t\t\t\t\t\t\t\t</button>\n\t\t\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t\t{:else}\n\t\t\t\t\t\t\t\t\t\t\t<button\n\t\t\t\t\t\t\t\t\t\t\t\tonclick={(e) => {\n\t\t\t\t\t\t\t\t\t\t\t\t\te.stopPropagation();\n\t\t\t\t\t\t\t\t\t\t\t\t\tconfirmingDeleteFolder = folder.path;\n\t\t\t\t\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t\t\t\t\t\tclass=\"rounded px-2 py-1 text-xs text-brand-text-muted transition-colors hover:bg-brand-surface-3/50 hover:text-rose-400 focus:outline-none\"\n\t\t\t\t\t\t\t\t\t\t\t\ttitle=\"Delete all sessions in this folder\"\n\t\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t\tDelete All\n\t\t\t\t\t\t\t\t\t\t\t</button>\n\t\t\t\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t{/if}\n\n\t\t\t\t\t\t\t{#each buildForkTree(folder.sessions) as { session, depth } (session.path)}\n\t\t\t\t\t\t\t\t<div\n\t\t\t\t\t\t\t\t\tstyle={depth > 0 ? `margin-left: ${depth * 0.85}rem` : ''}\n\t\t\t\t\t\t\t\t\tclass=\"group flex w-full items-center gap-2 rounded px-2 py-1.5 text-left transition-colors hover:bg-brand-surface-3/30 {depth >\n\t\t\t\t\t\t\t\t\t0\n\t\t\t\t\t\t\t\t\t\t? 'border-l border-brand-border/60 pl-2'\n\t\t\t\t\t\t\t\t\t\t: ''} {currentSession === session.path\n\t\t\t\t\t\t\t\t\t\t? 'bg-brand-surface-3'\n\t\t\t\t\t\t\t\t\t\t: ''}\"\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t{#if depth > 0}\n\t\t\t\t\t\t\t\t\t\t<span\n\t\t\t\t\t\t\t\t\t\t\tclass=\"flex-shrink-0 text-brand-text-muted\"\n\t\t\t\t\t\t\t\t\t\t\ttitle=\"Forked from the session above\"\n\t\t\t\t\t\t\t\t\t\t\taria-label=\"Forked session\">↳</span\n\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t\t\t\t<a\n\t\t\t\t\t\t\t\t\t\thref=\"#{encodeURIComponent(session.id)}\"\n\t\t\t\t\t\t\t\t\t\tonclick={(e) => {\n\t\t\t\t\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t\t\t\t\te.button === 0 &&\n\t\t\t\t\t\t\t\t\t\t\t\t!e.ctrlKey &&\n\t\t\t\t\t\t\t\t\t\t\t\t!e.metaKey &&\n\t\t\t\t\t\t\t\t\t\t\t\t!e.altKey &&\n\t\t\t\t\t\t\t\t\t\t\t\t!e.shiftKey\n\t\t\t\t\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\t\t\t\t\te.preventDefault();\n\t\t\t\t\t\t\t\t\t\t\t\thandleSessionClick(session.path);\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t\t\t\tclass=\"flex min-w-0 flex-1 items-center gap-2 text-left no-underline\"\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t{#if session.isWorking}\n\t\t\t\t\t\t\t\t\t\t\t<span\n\t\t\t\t\t\t\t\t\t\t\t\tclass=\"h-2 w-2 flex-shrink-0 animate-pulse rounded-full bg-amber-400\"\n\t\t\t\t\t\t\t\t\t\t\t\trole=\"img\"\n\t\t\t\t\t\t\t\t\t\t\t\ttitle=\"Agent is working\"\n\t\t\t\t\t\t\t\t\t\t\t\taria-label=\"Agent is working\"\n\t\t\t\t\t\t\t\t\t\t\t></span>\n\t\t\t\t\t\t\t\t\t\t{:else if session.isActive}\n\t\t\t\t\t\t\t\t\t\t\t<span\n\t\t\t\t\t\t\t\t\t\t\t\tclass=\"h-2 w-2 flex-shrink-0 rounded-full bg-emerald-500\"\n\t\t\t\t\t\t\t\t\t\t\t></span>\n\t\t\t\t\t\t\t\t\t\t{:else}\n\t\t\t\t\t\t\t\t\t\t\t<span\n\t\t\t\t\t\t\t\t\t\t\t\tclass=\"h-2 w-2 flex-shrink-0 rounded-full bg-brand-surface-3\"\n\t\t\t\t\t\t\t\t\t\t\t></span>\n\t\t\t\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t\t\t\t\t<div class=\"min-w-0 flex-1\">\n\t\t\t\t\t\t\t\t\t\t\t<div class=\"truncate text-xs text-brand-text\">\n\t\t\t\t\t\t\t\t\t\t\t\t{session.name ||\n\t\t\t\t\t\t\t\t\t\t\t\t\ttruncate(session.firstMessage) ||\n\t\t\t\t\t\t\t\t\t\t\t\t\t'Empty session'}\n\t\t\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t\t\t<div class=\"text-xs text-brand-text-muted\">\n\t\t\t\t\t\t\t\t\t\t\t\t{formatRelative(session.modified)} · {session.messageCount}\n\t\t\t\t\t\t\t\t\t\t\t\tmsgs\n\t\t\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t\t{#if session.clientCount > 0}\n\t\t\t\t\t\t\t\t\t\t\t<span\n\t\t\t\t\t\t\t\t\t\t\t\tclass=\"rounded bg-brand-surface-3 px-1.5 py-0.5 text-xs text-brand-text\"\n\t\t\t\t\t\t\t\t\t\t\t\t>{session.clientCount}</span\n\t\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t\t\t\t</a>\n\n\t\t\t\t\t\t\t\t\t<!-- Star toggle: always visible once starred, on hover otherwise\n\t\t\t\t\t\t\t\t\t (always on touch screens, which have no hover). -->\n\t\t\t\t\t\t\t\t\t<button\n\t\t\t\t\t\t\t\t\t\tonclick={(e) => {\n\t\t\t\t\t\t\t\t\t\t\te.stopPropagation();\n\t\t\t\t\t\t\t\t\t\t\ttoggleStar(session.path, !session.starred);\n\t\t\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t\t\t\tclass=\"flex-shrink-0 p-1 text-sm focus:outline-none {session.starred\n\t\t\t\t\t\t\t\t\t\t\t? 'text-amber-400 hover:text-brand-text-muted'\n\t\t\t\t\t\t\t\t\t\t\t: 'text-brand-text-muted transition-opacity hover:text-amber-400 md:opacity-0 md:group-hover:opacity-100'}\"\n\t\t\t\t\t\t\t\t\t\ttitle={session.starred\n\t\t\t\t\t\t\t\t\t\t\t? 'Unstar'\n\t\t\t\t\t\t\t\t\t\t\t: 'Star to come back to it later'}\n\t\t\t\t\t\t\t\t\t\taria-label={session.starred\n\t\t\t\t\t\t\t\t\t\t\t? 'Unstar session'\n\t\t\t\t\t\t\t\t\t\t\t: 'Star session'}\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t{session.starred ? '★' : '☆'}\n\t\t\t\t\t\t\t\t\t</button>\n\n\t\t\t\t\t\t\t\t\t<!-- Delete button with confirm state (hidden in read-only mode) -->\n\t\t\t\t\t\t\t\t\t{#if !readOnly}\n\t\t\t\t\t\t\t\t\t\t<div class=\"flex-shrink-0\">\n\t\t\t\t\t\t\t\t\t\t\t{#if confirmingDelete === session.path}\n\t\t\t\t\t\t\t\t\t\t\t\t<div\n\t\t\t\t\t\t\t\t\t\t\t\t\tclass=\"flex items-center gap-1 rounded border border-red-500/30 bg-brand-surface-2/80 px-1 py-0.5\"\n\t\t\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t\t\t<button\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tonclick={(e) => {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\te.stopPropagation();\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\thandleDeleteSession(session.path);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tclass=\"px-1.5 text-xs font-bold text-rose-400 hover:text-rose-300 focus:outline-none\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\ttitle=\"Confirm Delete\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t❓\n\t\t\t\t\t\t\t\t\t\t\t\t\t</button>\n\t\t\t\t\t\t\t\t\t\t\t\t\t<button\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tonclick={(e) => {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\te.stopPropagation();\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconfirmingDelete = null;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tclass=\"px-1.5 text-[10px] text-brand-text-muted hover:text-brand-text focus:outline-none\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\ttitle=\"Cancel\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t✕\n\t\t\t\t\t\t\t\t\t\t\t\t\t</button>\n\t\t\t\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t\t\t{:else}\n\t\t\t\t\t\t\t\t\t\t\t\t<button\n\t\t\t\t\t\t\t\t\t\t\t\t\tonclick={(e) => {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\te.stopPropagation();\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconfirmingDelete = session.path;\n\t\t\t\t\t\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t\t\t\t\t\t\tclass=\"p-1 text-xs text-brand-text-muted transition-opacity hover:text-rose-400 focus:outline-none md:opacity-0 md:group-hover:opacity-100\"\n\t\t\t\t\t\t\t\t\t\t\t\t\ttitle=\"Delete session\"\n\t\t\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t\t\t✕\n\t\t\t\t\t\t\t\t\t\t\t\t</button>\n\t\t\t\t\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t{/each}\n\t\t\t\t\t\t</div>\n\t\t\t\t\t{/if}\n\t\t\t\t</div>\n\t\t\t{/each}\n\t\t{/if}\n\t</div>\n</div>\n\n<!-- New Session Picker Dialog -->\n{#if newSessionPicker.open}\n\t<!-- svelte-ignore a11y_click_events_have_key_events -->\n\t<div\n\t\tclass=\"fixed inset-0 z-50 flex items-center justify-center bg-brand-dark/60\"\n\t\trole=\"presentation\"\n\t\tonclick={closeNewSessionPicker}\n\t>\n\t\t<div\n\t\t\tclass=\"w-80 rounded-lg border border-brand-border bg-brand-surface-2 p-6\"\n\t\t\trole=\"dialog\"\n\t\t\ttabindex=\"-1\"\n\t\t\tonclick={(e) => e.stopPropagation()}\n\t\t>\n\t\t\t<h3 class=\"mb-4 text-sm font-bold text-brand-text\">New Session</h3>\n\t\t\t<div class=\"mb-4\">\n\t\t\t\t<span class=\"mb-1 block text-xs text-brand-text-muted\">Folder</span>\n\t\t\t\t<div\n\t\t\t\t\tclass=\"truncate rounded bg-brand-surface-3 px-2 py-1.5 text-xs text-brand-text\"\n\t\t\t\t>\n\t\t\t\t\t{newSessionPicker.folderPath}\n\t\t\t\t</div>\n\t\t\t</div>\n\t\t\t<div class=\"mb-4\">\n\t\t\t\t<label\n\t\t\t\t\tclass=\"mb-1 block text-xs text-brand-text-muted\"\n\t\t\t\t\tfor=\"model-select\">Model</label\n\t\t\t\t>\n\t\t\t\t{#if models.length > 0}\n\t\t\t\t\t<select\n\t\t\t\t\t\tid=\"model-select\"\n\t\t\t\t\t\tbind:value={newSessionPicker.selected}\n\t\t\t\t\t\tclass=\"w-full rounded border border-brand-border bg-brand-surface-3 px-2 py-1.5 text-xs text-brand-text\"\n\t\t\t\t\t>\n\t\t\t\t\t\t{#each models as model}\n\t\t\t\t\t\t\t<option value={`${model.provider}:${model.modelId}`}>\n\t\t\t\t\t\t\t\t{model.label}{model.isDefault ? ' (default)' : ''}\n\t\t\t\t\t\t\t</option>\n\t\t\t\t\t\t{/each}\n\t\t\t\t\t</select>\n\t\t\t\t{:else}\n\t\t\t\t\t<input\n\t\t\t\t\t\tid=\"model-select\"\n\t\t\t\t\t\ttype=\"text\"\n\t\t\t\t\t\tbind:value={newSessionPicker.selected}\n\t\t\t\t\t\tplaceholder=\"provider:model\"\n\t\t\t\t\t\tclass=\"w-full rounded border border-brand-border bg-brand-surface-3 px-2 py-1.5 text-xs text-brand-text placeholder-brand-text-muted\"\n\t\t\t\t\t/>\n\t\t\t\t{/if}\n\t\t\t</div>\n\t\t\t<div class=\"flex justify-end gap-2\">\n\t\t\t\t<button\n\t\t\t\t\tonclick={closeNewSessionPicker}\n\t\t\t\t\tclass=\"rounded bg-brand-surface-3 px-3 py-1.5 text-xs text-brand-text transition-colors hover:bg-brand-surface-2\"\n\t\t\t\t>\n\t\t\t\t\tCancel\n\t\t\t\t</button>\n\t\t\t\t<button\n\t\t\t\t\tonclick={handleCreateSession}\n\t\t\t\t\tclass=\"rounded bg-gradient-to-r from-brand-cyan to-brand-blue px-3 py-1.5 text-xs font-semibold text-brand-text transition-all hover:opacity-90\"\n\t\t\t\t>\n\t\t\t\t\tCreate\n\t\t\t\t</button>\n\t\t\t</div>\n\t\t</div>\n\t</div>\n{/if}\n\n<!-- Session Error -->\n{#if $sessionError}\n\t<div\n\t\tclass=\"absolute right-0 bottom-0 left-0 flex items-center justify-between border-t border-red-500/30 bg-red-500/10 px-3 py-2 text-xs text-rose-400\"\n\t>\n\t\t<span class=\"truncate\">{$sessionError}</span>\n\t\t<button\n\t\t\tonclick={() => dismissSessionError()}\n\t\t\tclass=\"ml-2 flex-shrink-0 text-rose-300 hover:text-rose-200\">✕</button\n\t\t>\n\t</div>\n{/if}\n\n<!-- Sidebar Git Init Confirm Dialog -->\n{#if showSidebarGitConfirmModal}\n\t<div\n\t\tclass=\"fixed inset-0 z-50 flex items-center justify-center bg-brand-dark/65 p-4\"\n\t\trole=\"dialog\"\n\t\taria-modal=\"true\"\n\t>\n\t\t<div\n\t\t\tclass=\"w-80 rounded-lg border border-brand-border bg-brand-surface-2 p-5 text-brand-text\"\n\t\t>\n\t\t\t<h3 class=\"mb-2 text-sm font-bold text-brand-text\">\n\t\t\t\tFolder Already Exists\n\t\t\t</h3>\n\t\t\t<p class=\"mb-3 text-xs text-brand-text-muted\">\n\t\t\t\tThe folder <span\n\t\t\t\t\tclass=\"selectable font-mono text-[11px] break-all text-brand-text\"\n\t\t\t\t\t>{sidebarCwd}</span\n\t\t\t\t> already exists. Do you want to initialize a Git repository in it?\n\t\t\t</p>\n\n\t\t\t<div class=\"mb-4 flex flex-col gap-3\">\n\t\t\t\t<div class=\"flex items-center gap-1.5\">\n\t\t\t\t\t<input\n\t\t\t\t\t\tid=\"sidebar-modal-git-init\"\n\t\t\t\t\t\ttype=\"checkbox\"\n\t\t\t\t\t\tbind:checked={sidebarGitInit}\n\t\t\t\t\t\tdisabled={sidebarPathStatus.isGit}\n\t\t\t\t\t\tclass=\"h-3.5 w-3.5 rounded border-brand-border bg-brand-surface-3 text-brand-blue focus:ring-brand-blue disabled:opacity-50\"\n\t\t\t\t\t/>\n\t\t\t\t\t<label\n\t\t\t\t\t\tfor=\"sidebar-modal-git-init\"\n\t\t\t\t\t\tclass=\"cursor-pointer text-xs text-brand-text select-none disabled:opacity-50\"\n\t\t\t\t\t>\n\t\t\t\t\t\tInitialize Git repository\n\t\t\t\t\t\t{#if sidebarPathStatus.isGit}\n\t\t\t\t\t\t\t<span class=\"ml-1 text-[10px] text-brand-text-muted\"\n\t\t\t\t\t\t\t\t>(already a Git repo)</span\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t{:else}\n\t\t\t\t\t\t\t<span class=\"ml-1 text-[10px] font-medium text-yellow-500\"\n\t\t\t\t\t\t\t\t>(folder not empty)</span\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t{/if}\n\t\t\t\t\t</label>\n\t\t\t\t</div>\n\n\t\t\t\t{#if sidebarPathStatus.matchingRule}\n\t\t\t\t\t<div class=\"space-y-1\">\n\t\t\t\t\t\t<div class=\"flex items-center gap-1.5\">\n\t\t\t\t\t\t\t<input\n\t\t\t\t\t\t\t\tid=\"sidebar-modal-create-remote\"\n\t\t\t\t\t\t\t\ttype=\"checkbox\"\n\t\t\t\t\t\t\t\tbind:checked={sidebarCreateRemote}\n\t\t\t\t\t\t\t\tclass=\"h-3.5 w-3.5 rounded border-brand-border bg-brand-surface-3 text-brand-blue focus:ring-brand-blue\"\n\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t<label\n\t\t\t\t\t\t\t\tfor=\"sidebar-modal-create-remote\"\n\t\t\t\t\t\t\t\tclass=\"cursor-pointer text-xs text-brand-text select-none\"\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\tCreate remote {sidebarPathStatus.matchingRule.provider} repository\n\t\t\t\t\t\t\t</label>\n\t\t\t\t\t\t</div>\n\n\t\t\t\t\t\t{#if sidebarCreateRemote}\n\t\t\t\t\t\t\t<div\n\t\t\t\t\t\t\t\tclass=\"flex items-center gap-3 pl-5 text-[10px] text-brand-text-muted\"\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t<span>Visibility:</span>\n\t\t\t\t\t\t\t\t<label\n\t\t\t\t\t\t\t\t\tclass=\"flex cursor-pointer items-center gap-1 transition-colors select-none hover:text-brand-text\"\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t<input\n\t\t\t\t\t\t\t\t\t\ttype=\"radio\"\n\t\t\t\t\t\t\t\t\t\tname=\"sidebar-modal-visibility\"\n\t\t\t\t\t\t\t\t\t\tvalue=\"private\"\n\t\t\t\t\t\t\t\t\t\tbind:group={sidebarRepoVisibility}\n\t\t\t\t\t\t\t\t\t\tclass=\"border-brand-border bg-brand-surface-3 text-brand-blue focus:ring-brand-blue\"\n\t\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t\t\tPrivate\n\t\t\t\t\t\t\t\t</label>\n\t\t\t\t\t\t\t\t<label\n\t\t\t\t\t\t\t\t\tclass=\"flex cursor-pointer items-center gap-1 transition-colors select-none hover:text-brand-text\"\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t<input\n\t\t\t\t\t\t\t\t\t\ttype=\"radio\"\n\t\t\t\t\t\t\t\t\t\tname=\"sidebar-modal-visibility\"\n\t\t\t\t\t\t\t\t\t\tvalue=\"public\"\n\t\t\t\t\t\t\t\t\t\tbind:group={sidebarRepoVisibility}\n\t\t\t\t\t\t\t\t\t\tclass=\"border-brand-border bg-brand-surface-3 text-brand-blue focus:ring-brand-blue\"\n\t\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t\t\tPublic\n\t\t\t\t\t\t\t\t</label>\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t{/if}\n\t\t\t\t\t</div>\n\t\t\t\t{/if}\n\t\t\t</div>\n\n\t\t\t<div class=\"flex justify-end gap-2\">\n\t\t\t\t<button\n\t\t\t\t\ttype=\"button\"\n\t\t\t\t\tonclick={() => (showSidebarGitConfirmModal = false)}\n\t\t\t\t\tclass=\"rounded bg-brand-surface-3 px-3 py-1.5 text-xs text-brand-text transition-colors hover:bg-brand-surface-2\"\n\t\t\t\t>\n\t\t\t\t\tCancel\n\t\t\t\t</button>\n\t\t\t\t<button\n\t\t\t\t\ttype=\"button\"\n\t\t\t\t\tonclick={handleSidebarConfirmModalSubmit}\n\t\t\t\t\tclass=\"rounded bg-gradient-to-r from-brand-cyan to-brand-blue px-3 py-1.5 text-xs font-semibold text-brand-text transition-all hover:opacity-90\"\n\t\t\t\t>\n\t\t\t\t\tConfirm & Create\n\t\t\t\t</button>\n\t\t\t</div>\n\t\t</div>\n\t</div>\n{/if}\n","/**\n * Conversation-search snippets, as a pure module.\n *\n * The server ships each snippet exactly as SQLite FTS5 produced it: matched\n * terms are wrapped in \\u0001 ... \\u0002 (memonaut's `snippet()` markers). Those\n * control characters are used instead of HTML so the server never has to know\n * about markup and the transport can never carry an injection: turning them into\n * highlight spans is a rendering decision, made here.\n *\n * The result is a list of {text, match} segments the component renders with a\n * plain `{#each}` (no `{@html}`, so nothing from a transcript is ever parsed as\n * markup).\n */\n\nexport const MATCH_START = '\\u0001';\nexport const MATCH_END = '\\u0002';\n\nexport interface SnippetSegment {\n\ttext: string;\n\t/** True when this segment is a matched term and should be highlighted. */\n\tmatch: boolean;\n}\n\n/**\n * Split an FTS5 snippet into plain/highlighted segments.\n *\n * Tolerates malformed input on purpose: an unterminated start marker highlights\n * to the end, a stray end marker is dropped, and text with no markers at all\n * comes back as a single plain segment. A snippet is display sugar, so it must\n * never be able to throw in the render path.\n */\nexport function snippetSegments(snippet: string): SnippetSegment[] {\n\tif (!snippet) return [];\n\tconst segments: SnippetSegment[] = [];\n\tlet rest = snippet;\n\n\twhile (rest.length > 0) {\n\t\tconst start = rest.indexOf(MATCH_START);\n\t\tif (start < 0) {\n\t\t\tpush(segments, rest.split(MATCH_END).join(''), false);\n\t\t\tbreak;\n\t\t}\n\t\tpush(segments, rest.slice(0, start).split(MATCH_END).join(''), false);\n\t\trest = rest.slice(start + 1);\n\t\tconst end = rest.indexOf(MATCH_END);\n\t\tif (end < 0) {\n\t\t\tpush(segments, rest, true);\n\t\t\tbreak;\n\t\t}\n\t\tpush(segments, rest.slice(0, end), true);\n\t\trest = rest.slice(end + 1);\n\t}\n\n\treturn segments;\n}\n\nfunction push(segments: SnippetSegment[], text: string, match: boolean): void {\n\tif (!text) return;\n\tsegments.push({text, match});\n}\n\n/** The snippet with every marker removed (titles, tooltips, a11y labels). */\nexport function snippetPlainText(snippet: string): string {\n\treturn snippetSegments(snippet)\n\t\t.map((s) => s.text)\n\t\t.join('');\n}\n\n/**\n * Short, human label for where a hit came from. `kind` is memonaut's chunk kind\n * (what the text IS) and is more informative than the raw role, which is why it\n * wins; the tool name is appended when the kind is a tool call.\n */\nexport function hitKindLabel(kind: string, tool?: string | null): string {\n\tswitch (kind) {\n\t\tcase 'user':\n\t\t\treturn 'you';\n\t\tcase 'assistant':\n\t\t\treturn 'agent';\n\t\tcase 'thinking':\n\t\t\treturn 'thinking';\n\t\tcase 'name':\n\t\t\treturn 'session name';\n\t\tcase 'summary':\n\t\t\treturn 'summary';\n\t\tcase 'bash':\n\t\t\treturn 'bash';\n\t\tcase 'toolCall':\n\t\t\treturn tool ? `tool: ${tool}` : 'tool call';\n\t\tcase 'toolResult':\n\t\t\treturn tool ? `output: ${tool}` : 'tool output';\n\t\tdefault:\n\t\t\treturn kind || 'entry';\n\t}\n}\n\n/** Compact relative age (\"3d ago\"), falling back to the raw string. */\nexport function relativeTime(iso: string | null, now = Date.now()): string {\n\tif (!iso) return '';\n\tconst t = Date.parse(iso);\n\tif (Number.isNaN(t)) return '';\n\tconst seconds = Math.max(0, Math.round((now - t) / 1000));\n\tif (seconds < 60) return 'just now';\n\tconst minutes = Math.round(seconds / 60);\n\tif (minutes < 60) return `${minutes}m ago`;\n\tconst hours = Math.round(minutes / 60);\n\tif (hours < 24) return `${hours}h ago`;\n\tconst days = Math.round(hours / 24);\n\tif (days < 30) return `${days}d ago`;\n\tconst months = Math.round(days / 30);\n\tif (months < 12) return `${months}mo ago`;\n\treturn `${Math.round(months / 12)}y ago`;\n}\n","<script lang=\"ts\">\n\t/**\n\t * Conversation search: full-text search over EVERY past session, backed by\n\t * the memonaut index server-side (`GET /search`).\n\t *\n\t * Two things this panel must get right:\n\t * - **Forks are not collapsed.** A match in history shared by a fork family\n\t * is carried by several sessions; the server returns all of them, newest\n\t * active first, with a `+N after` count that is the only thing telling\n\t * byte-identical siblings apart. Each is independently clickable, so this\n\t * lands you in the continuation you actually meant, the same way the\n\t * sidebar's fork tree does.\n\t * - **It obeys the dashboard's visibility rules.** Which sessions are\n\t * searchable at all is decided on the server (see\n\t * server/src/conversation-search.ts); this panel simply mirrors the two\n\t * views: the main list, and the read-only page.\n\t */\n\timport {untrack} from 'svelte';\n\timport {\n\t\tsearchConversations,\n\t\ttype SearchHitResult,\n\t\ttype SearchResponse,\n\t\ttype SearchThreadResult,\n\t} from '$lib/session-store';\n\timport {\n\t\tswitchSession,\n\t\tactiveSessionInfo,\n\t\tisLoadingSession,\n\t\tisResyncing,\n\t\tdismissSessionError,\n\t} from '$lib/wherever';\n\timport {\n\t\tsnippetSegments,\n\t\tsnippetPlainText,\n\t\thitKindLabel,\n\t\trelativeTime,\n\t} from '$lib/core/search-snippet.js';\n\n\tlet {\n\t\treadOnly = false,\n\t\tinitialQuery = '',\n\t\tonOpened,\n\t}: {\n\t\t/** Search the read-only page's folders instead of the main list. */\n\t\treadOnly?: boolean;\n\t\tinitialQuery?: string;\n\t\t/** Called after a result is opened (used to close the sidebar on mobile). */\n\t\tonOpened?: () => void;\n\t} = $props();\n\n\t// Seeded once from the prop (the panel can be opened with text already typed\n\t// in the sidebar's filter box); from then on the input owns it.\n\tlet query = $state(untrack(() => initialQuery));\n\tlet result = $state<SearchResponse | null>(null);\n\tlet loading = $state(false);\n\tlet inputEl = $state<HTMLInputElement | null>(null);\n\t// Threads beyond the first are folded away per hit until asked for, so one\n\t// heavily forked conversation cannot own the panel.\n\tlet expandedThreads = $state<Record<string, boolean>>({});\n\n\tlet currentSession = $derived($activeSessionInfo.sessionFile);\n\tlet loadingSession = $derived($isLoadingSession);\n\tlet resyncing = $derived($isResyncing);\n\n\tconst MIN_QUERY = 2;\n\tconst DEBOUNCE_MS = 250;\n\tlet debounceTimer: ReturnType<typeof setTimeout> | null = null;\n\n\t// Focus on open, and run a prefilled query straight away (the panel can be\n\t// opened from the sidebar's list filter with the text already typed).\n\tlet started = false;\n\t$effect(() => {\n\t\tinputEl?.focus();\n\t\tif (started) return;\n\t\tstarted = true;\n\t\tif (query.trim().length >= MIN_QUERY) {\n\t\t\tloading = true;\n\t\t\tvoid run(query);\n\t\t}\n\t});\n\n\tfunction scheduleSearch(next: string) {\n\t\tquery = next;\n\t\tif (debounceTimer) clearTimeout(debounceTimer);\n\t\tif (next.trim().length < MIN_QUERY) {\n\t\t\tloading = false;\n\t\t\tresult = null;\n\t\t\treturn;\n\t\t}\n\t\tloading = true;\n\t\tdebounceTimer = setTimeout(() => {\n\t\t\tdebounceTimer = null;\n\t\t\tvoid run(next);\n\t\t}, DEBOUNCE_MS);\n\t}\n\n\tasync function run(text: string) {\n\t\tconst response = await searchConversations(\n\t\t\ttext.trim(),\n\t\t\treadOnly ? 'readonly' : 'default',\n\t\t);\n\t\t// null = superseded by a newer query; keep what is on screen.\n\t\tif (response === null) return;\n\t\tresult = response;\n\t\tloading = false;\n\t\texpandedThreads = {};\n\t}\n\n\tfunction submit(e: Event) {\n\t\te.preventDefault();\n\t\tif (debounceTimer) clearTimeout(debounceTimer);\n\t\tif (query.trim().length < MIN_QUERY) return;\n\t\tloading = true;\n\t\tvoid run(query);\n\t}\n\n\tfunction open(thread: SearchThreadResult) {\n\t\tif (\n\t\t\tcurrentSession === thread.sessionPath &&\n\t\t\t!loadingSession &&\n\t\t\t!resyncing\n\t\t) {\n\t\t\tonOpened?.();\n\t\t\treturn;\n\t\t}\n\t\tdismissSessionError();\n\t\t// The server normalizes `sessionPath` exactly like the /sessions listing,\n\t\t// so this is the same call the sidebar makes for the same session.\n\t\tswitchSession(thread.sessionPath);\n\t\tonOpened?.();\n\t}\n\n\tfunction hitKey(hit: SearchHitResult, i: number): string {\n\t\treturn `${hit.entryKey}-${i}`;\n\t}\n\n\tfunction threadLabel(thread: SearchThreadResult): string {\n\t\treturn thread.name || `${thread.folderName} · ${thread.entryCount} entries`;\n\t}\n</script>\n\n<!-- One clickable session. The SAME row renders the primary thread and each\n sibling fork of a shared-history match: they are the same thing (a session\n carrying this entry), so they must look and behave alike. -->\n{#snippet threadRow(thread: SearchThreadResult, extraClass: string)}\n\t<button\n\t\tonclick={() => open(thread)}\n\t\tclass=\"flex w-full items-start gap-2 rounded px-1.5 py-1 text-left transition-colors hover:bg-brand-surface-3/40 {extraClass}\"\n\t\ttitle={thread.sessionPath}\n\t>\n\t\t<span class=\"mt-0.5 flex-shrink-0 text-brand-text-muted\"\n\t\t\t>{thread.isRoot ? '•' : '↳'}</span\n\t\t>\n\t\t<span class=\"min-w-0 flex-1\">\n\t\t\t<span class=\"block truncate text-xs text-brand-text\"\n\t\t\t\t>{threadLabel(thread)}</span\n\t\t\t>\n\t\t\t<span class=\"block text-[10px] text-brand-text-muted\">\n\t\t\t\t{thread.folderName} · {relativeTime(thread.lastActivity)} · +{thread.after}\n\t\t\t\tafter\n\t\t\t</span>\n\t\t</span>\n\t</button>\n{/snippet}\n\n<div class=\"flex h-full flex-col\">\n\t<div class=\"border-b border-brand-border/50 p-2\">\n\t\t<form onsubmit={submit} class=\"flex gap-1.5\">\n\t\t\t<input\n\t\t\t\tbind:this={inputEl}\n\t\t\t\ttype=\"search\"\n\t\t\t\tplaceholder={readOnly\n\t\t\t\t\t? 'Search read-only conversations...'\n\t\t\t\t\t: 'Search all conversations...'}\n\t\t\t\tvalue={query}\n\t\t\t\toninput={(e) => scheduleSearch(e.currentTarget.value)}\n\t\t\t\tclass=\"min-w-0 flex-1 rounded border border-brand-border bg-brand-surface-2 px-2 py-1.5 text-xs text-brand-text placeholder-brand-text-muted focus:border-brand-blue focus:outline-none\"\n\t\t\t/>\n\t\t\t<button\n\t\t\t\ttype=\"submit\"\n\t\t\t\tclass=\"flex shrink-0 items-center justify-center rounded border border-brand-border bg-brand-surface-2 px-2 py-1.5 text-brand-text-muted transition-colors hover:bg-brand-surface-3 hover:text-brand-text\"\n\t\t\t\ttitle=\"Search\"\n\t\t\t>\n\t\t\t\t<span class={loading ? 'animate-pulse' : ''}>🔎</span>\n\t\t\t</button>\n\t\t</form>\n\t\t<div class=\"mt-1 px-0.5 text-[10px] text-brand-text-muted\">\n\t\t\tWords are ANDed; use \"quoted phrases\", OR, NOT, or a trailing * for\n\t\t\tprefixes.\n\t\t</div>\n\t</div>\n\n\t<div class=\"flex-1 overflow-y-auto\">\n\t\t{#if query.trim().length < MIN_QUERY}\n\t\t\t<div class=\"p-3 text-xs text-brand-text-muted\">\n\t\t\t\tType at least {MIN_QUERY} characters to search everything ever said in any\n\t\t\t\tsession.\n\t\t\t</div>\n\t\t{:else if loading && !result}\n\t\t\t<div class=\"p-3 text-xs text-brand-text-muted\">Searching…</div>\n\t\t{:else if result?.status === 'not-indexed'}\n\t\t\t<div class=\"space-y-2 p-3 text-xs text-brand-text-muted\">\n\t\t\t\t<div class=\"font-semibold text-brand-text\">\n\t\t\t\t\tNo conversation index yet\n\t\t\t\t</div>\n\t\t\t\t<p>\n\t\t\t\t\tSearch is backed by the <code class=\"text-brand-blue\">memonaut</code> index,\n\t\t\t\t\twhich has not been built on this machine. Building it takes about a minute\n\t\t\t\t\tand is deliberately never done from here, because it would freeze the server\n\t\t\t\t\twhile it ran.\n\t\t\t\t</p>\n\t\t\t\t<p>Run this on the server, then search again:</p>\n\t\t\t\t<pre\n\t\t\t\t\tclass=\"overflow-x-auto rounded bg-brand-surface-2 p-2 text-brand-text\">recall index</pre>\n\t\t\t\t{#if result.index?.path}\n\t\t\t\t\t<div class=\"break-all opacity-70\">\n\t\t\t\t\t\tExpected at {result.index.path}\n\t\t\t\t\t</div>\n\t\t\t\t{/if}\n\t\t\t</div>\n\t\t{:else if result?.status === 'unavailable' || result?.status === 'error'}\n\t\t\t<div class=\"p-3 text-xs text-rose-400\">\n\t\t\t\t{result.message || 'Search is unavailable.'}\n\t\t\t</div>\n\t\t{:else if result && result.hits.length === 0}\n\t\t\t<div class=\"p-3 text-xs text-brand-text-muted\">\n\t\t\t\tNo matches for “{result.query}”.\n\t\t\t\t{#if result.hiddenHits}\n\t\t\t\t\t<div class=\"mt-1 opacity-70\">\n\t\t\t\t\t\t{result.hiddenHits} match{result.hiddenHits === 1 ? '' : 'es'} were in\n\t\t\t\t\t\tsessions not shown here.\n\t\t\t\t\t</div>\n\t\t\t\t{/if}\n\t\t\t</div>\n\t\t{:else if result}\n\t\t\t<div\n\t\t\t\tclass=\"flex items-center justify-between border-b border-brand-border/30 px-3 py-1.5 text-[10px] text-brand-text-muted\"\n\t\t\t>\n\t\t\t\t<span>\n\t\t\t\t\t{result.hits.length} result{result.hits.length === 1 ? '' : 's'}\n\t\t\t\t\t{#if result.hiddenHits}· {result.hiddenHits} hidden{/if}\n\t\t\t\t</span>\n\t\t\t\t{#if result.index}\n\t\t\t\t\t<span title={result.index.path}>\n\t\t\t\t\t\t{result.index.files.toLocaleString()} sessions indexed\n\t\t\t\t\t</span>\n\t\t\t\t{/if}\n\t\t\t</div>\n\n\t\t\t{#each result.hits as hit, i (hitKey(hit, i))}\n\t\t\t\t{@const key = hitKey(hit, i)}\n\t\t\t\t{@const primary = hit.threads[0]}\n\t\t\t\t{@const rest = hit.threads.slice(1)}\n\t\t\t\t<div class=\"border-b border-brand-border/30 px-3 py-2\">\n\t\t\t\t\t<div\n\t\t\t\t\t\tclass=\"flex items-center gap-2 text-[10px] tracking-wide text-brand-text-muted uppercase\"\n\t\t\t\t\t>\n\t\t\t\t\t\t<span class=\"rounded bg-brand-surface-2 px-1.5 py-0.5\"\n\t\t\t\t\t\t\t>{hitKindLabel(hit.kind, hit.tool)}</span\n\t\t\t\t\t\t>\n\t\t\t\t\t\t<span>{relativeTime(hit.ts)}</span>\n\t\t\t\t\t\t{#if primary?.readOnly}\n\t\t\t\t\t\t\t<span class=\"text-amber-400\" title=\"Read-only session\">👁️</span>\n\t\t\t\t\t\t{/if}\n\t\t\t\t\t</div>\n\n\t\t\t\t\t<p class=\"mt-1 text-xs leading-relaxed text-brand-text\">\n\t\t\t\t\t\t{#each snippetSegments(hit.snippet) as segment}\n\t\t\t\t\t\t\t{#if segment.match}\n\t\t\t\t\t\t\t\t<mark class=\"rounded bg-brand-blue/30 px-0.5 text-brand-text\"\n\t\t\t\t\t\t\t\t\t>{segment.text}</mark\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t{:else}{segment.text}{/if}\n\t\t\t\t\t\t{/each}\n\t\t\t\t\t</p>\n\n\t\t\t\t\t{#if primary}\n\t\t\t\t\t\t{@render threadRow(primary, 'mt-1.5')}\n\t\t\t\t\t{/if}\n\n\t\t\t\t\t{#if rest.length > 0}\n\t\t\t\t\t\t<!-- Shared history: the SAME entry lives in every fork that\n\t\t\t\t\t\t inherited it, so every one of them is offered. -->\n\t\t\t\t\t\t<button\n\t\t\t\t\t\t\tonclick={() => (expandedThreads[key] = !expandedThreads[key])}\n\t\t\t\t\t\t\tclass=\"mt-1 px-1.5 text-[10px] text-brand-blue hover:underline\"\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\tmatched in shared history · carried by {hit.threadTotal} sessions\n\t\t\t\t\t\t\t{expandedThreads[key] ? '▲' : '▼'}\n\t\t\t\t\t\t</button>\n\t\t\t\t\t\t{#if expandedThreads[key]}\n\t\t\t\t\t\t\t<div class=\"mt-0.5 border-l border-brand-border/40 pl-2\">\n\t\t\t\t\t\t\t\t{#each rest as thread (thread.sessionPath)}\n\t\t\t\t\t\t\t\t\t{@render threadRow(thread, '')}\n\t\t\t\t\t\t\t\t{/each}\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t{/if}\n\t\t\t\t\t{/if}\n\n\t\t\t\t\t{#if hit.otherHits > 0}\n\t\t\t\t\t\t<div\n\t\t\t\t\t\t\tclass=\"px-1.5 pt-0.5 text-[10px] text-brand-text-muted\"\n\t\t\t\t\t\t\ttitle={snippetPlainText(hit.snippet)}\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t+{hit.otherHits} more match{hit.otherHits === 1 ? '' : 'es'} in this\n\t\t\t\t\t\t\tconversation\n\t\t\t\t\t\t</div>\n\t\t\t\t\t{/if}\n\t\t\t\t</div>\n\t\t\t{/each}\n\t\t{/if}\n\t</div>\n</div>\n","<script lang=\"ts\">\n\timport {sudoPrompt, sendSudoPassword, cancelSudoPrompt} from '$lib/wherever';\n\n\tlet prompt = $derived($sudoPrompt);\n\n\t// Local, transient password buffer. It lives only in this component for as\n\t// long as the dialog is open, is handed straight to the socket on submit, and\n\t// is wiped immediately after. It is never written to the store or persisted.\n\tlet password = $state('');\n\tlet inputEl = $state<HTMLInputElement | null>(null);\n\n\t// Autofocus the field and clear any stale buffer each time a new prompt\n\t// appears. Keyed on promptId so a fresh prompt (new command) always resets.\n\tlet lastPromptId = $state<string | null>(null);\n\t$effect(() => {\n\t\tconst id = prompt?.promptId ?? null;\n\t\tif (id !== lastPromptId) {\n\t\t\tlastPromptId = id;\n\t\t\tpassword = '';\n\t\t\tif (id) {\n\t\t\t\t// Defer so the input is mounted before focusing.\n\t\t\t\tqueueMicrotask(() => inputEl?.focus());\n\t\t\t}\n\t\t}\n\t});\n\n\tfunction submit() {\n\t\tif (!prompt) return;\n\t\tsendSudoPassword(password);\n\t\tpassword = '';\n\t}\n\n\tfunction cancel() {\n\t\tcancelSudoPrompt();\n\t\tpassword = '';\n\t}\n\n\tfunction onKeydown(e: KeyboardEvent) {\n\t\tif (e.key === 'Enter') {\n\t\t\te.preventDefault();\n\t\t\tsubmit();\n\t\t} else if (e.key === 'Escape') {\n\t\t\te.preventDefault();\n\t\t\tcancel();\n\t\t}\n\t}\n</script>\n\n{#if prompt}\n\t<div\n\t\tclass=\"fixed inset-0 z-50 flex items-center justify-center bg-brand-dark/60\"\n\t>\n\t\t<div\n\t\t\tclass=\"mx-4 w-full max-w-md rounded-xl border border-brand-border bg-brand-surface-2 p-6 shadow-xl\"\n\t\t>\n\t\t\t<h2 class=\"mb-2 text-lg font-bold text-brand-text\">Sudo password</h2>\n\t\t\t<p class=\"mb-3 text-sm text-brand-text-muted\">\n\t\t\t\tThis command needs your sudo password to run. It is used once and never\n\t\t\t\tstored.\n\t\t\t</p>\n\t\t\t<pre\n\t\t\t\tclass=\"mb-4 overflow-x-auto rounded-lg bg-brand-surface-3 px-3 py-2 font-mono text-xs text-brand-text\">{prompt.command}</pre>\n\n\t\t\t<!-- svelte-ignore a11y_autofocus -->\n\t\t\t<input\n\t\t\t\tbind:this={inputEl}\n\t\t\t\tbind:value={password}\n\t\t\t\tonkeydown={onKeydown}\n\t\t\t\ttype=\"password\"\n\t\t\t\tautocomplete=\"off\"\n\t\t\t\tautocapitalize=\"off\"\n\t\t\t\tautocorrect=\"off\"\n\t\t\t\tspellcheck=\"false\"\n\t\t\t\tplaceholder=\"Password\"\n\t\t\t\tclass=\"mb-4 w-full rounded-lg border border-brand-border bg-brand-surface-3 px-3 py-2.5 text-sm text-brand-text outline-none focus:border-brand-blue\"\n\t\t\t/>\n\n\t\t\t<div class=\"flex gap-3\">\n\t\t\t\t<button\n\t\t\t\t\tonclick={cancel}\n\t\t\t\t\tclass=\"flex-1 rounded-lg bg-brand-surface-3 px-4 py-2.5 text-sm text-brand-text transition-colors hover:bg-brand-surface-2\"\n\t\t\t\t>\n\t\t\t\t\tCancel\n\t\t\t\t</button>\n\t\t\t\t<button\n\t\t\t\t\tonclick={submit}\n\t\t\t\t\tclass=\"flex-1 rounded-lg bg-brand-blue px-4 py-2.5 text-sm text-brand-text transition-colors hover:opacity-90\"\n\t\t\t\t>\n\t\t\t\t\tRun\n\t\t\t\t</button>\n\t\t\t</div>\n\t\t</div>\n\t</div>\n{/if}\n","<script lang=\"ts\">\n\t// The PROGRESS DISPLAY of a restore job, shared by the two entry points that\n\t// have one: the RESTORE PANEL (a loaded session whose folder is missing) and\n\t// the NEW-SESSION clone (creating a session in a folder that has to be cloned\n\t// first). Both drive the same server-owned, path-keyed job, so both render it\n\t// the same way -- one display, so honesty is fixed in one place rather than\n\t// re-invented per entry point.\n\t//\n\t// Honest per story 8: the phase, the scope, and either a real percentage or an\n\t// EXPLICIT indeterminate state. Submodules report under their own scope,\n\t// counted separately, because git restarts counting for each one and nothing\n\t// knows how many objects the remaining ones hold. A single unified bar would\n\t// be a lie, and a lie that looks stuck is worse than a segmented truth that\n\t// moves.\n\timport type {RestoreJobInfo} from '@wherever-dev/client';\n\n\tlet {job}: {job: RestoreJobInfo | null} = $props();\n\n\t// A create has exactly one scope (there are no submodules to count), so the\n\t// scope label and the submodule note would be noise, not honesty.\n\tlet creating = $derived(job?.kind === 'create');\n\n\tconst PHASE_LABELS: Record<string, string> = {\n\t\tstarting: 'Starting',\n\t\tenumerating: 'Enumerating objects',\n\t\tcounting: 'Counting objects',\n\t\tcompressing: 'Compressing objects',\n\t\treceiving: 'Receiving objects',\n\t\tresolving: 'Resolving deltas',\n\t\t'checking-out': 'Checking out files',\n\t\tfiltering: 'Filtering content',\n\t\tcreating: 'Creating the folder',\n\t\tinitialising: 'Initialising a git repository',\n\t};\n\n\tfunction phaseLabel(phase: string): string {\n\t\treturn PHASE_LABELS[phase] ?? phase;\n\t}\n\n\t// 'repository' is the top-level clone; anything else is a submodule path\n\t// relative to the target, and is named as such so the separate counting is\n\t// visible rather than implied.\n\tfunction scopeLabel(scope: string): string {\n\t\treturn scope === 'repository' ? 'the repository' : `submodule ${scope}`;\n\t}\n</script>\n\n{#if job?.progress}\n\t{@const p = job.progress}\n\t<div class=\"mt-2 flex items-baseline justify-between gap-2 text-xs\">\n\t\t<span class=\"min-w-0 flex-1 break-words text-brand-text\">\n\t\t\t{phaseLabel(p.phase)}{creating ? '' : ` \\u00b7 ${scopeLabel(p.scope)}`}\n\t\t</span>\n\t\t<span class=\"flex-shrink-0 font-mono text-brand-text-muted\">\n\t\t\t{p.indeterminate ? 'no percentage' : `${p.percent}%`}\n\t\t</span>\n\t</div>\n\t<div class=\"mt-1 h-1.5 w-full overflow-hidden rounded bg-brand-surface-3\">\n\t\t{#if p.indeterminate}\n\t\t\t<!-- Explicitly indeterminate: git reports no percentage for this phase,\n\t\t\t so we animate rather than invent a number. -->\n\t\t\t<div class=\"h-full w-1/3 animate-pulse rounded bg-brand-blue/60\"></div>\n\t\t{:else}\n\t\t\t<div\n\t\t\t\tclass=\"h-full rounded bg-gradient-to-r from-brand-cyan to-brand-blue transition-all\"\n\t\t\t\tstyle={`width: ${Math.max(0, Math.min(100, p.percent ?? 0))}%`}\n\t\t\t></div>\n\t\t{/if}\n\t</div>\n\t<div class=\"mt-1 font-mono text-[11px] break-all text-brand-text-muted\">\n\t\t{p.text}\n\t</div>\n{:else}\n\t<div class=\"mt-2 text-xs text-brand-text-muted\">\n\t\t{creating\n\t\t\t? 'Starting...'\n\t\t\t: 'Starting the clone (git has not reported anything measurable yet)...'}\n\t</div>\n{/if}\n{#if !creating}\n\t<div class=\"mt-1 text-[11px] text-brand-text-muted\">\n\t\tEach submodule is counted separately and has its own progress above, so\n\t\tthere is no single overall percentage.\n\t</div>\n{/if}\n","<script lang=\"ts\">\n\t// The RESTORE PANEL: what a folder-missing session shows in place of the\n\t// composer. The session's working folder is not on this machine (the\n\t// transcript synced, the clone did not), so there is nothing to drive and\n\t// nothing to type into -- but there IS a remedy, and this is it: put the\n\t// folder back at that exact path, from the phone, and watch it happen.\n\t//\n\t// TWO remedies, ONE state machine. Cloning the repository back is the common\n\t// case and the primary action. Creating the folder is the RARE one (a scratch\n\t// directory, a folder whose contents only ever lived on the old machine): it\n\t// is deliberately kept visually secondary, behind a disclosure, because a tap\n\t// that lands on it by accident produces an EMPTY folder that then looks\n\t// restored -- the one outcome worse than the missing folder itself, since the\n\t// non-empty guard will refuse the clone that should have happened. Both drive\n\t// the same server job, the same frames and the same running / ready / failed\n\t// states below; only the request differs.\n\t//\n\t// Three things this panel is deliberately careful about:\n\t//\n\t// - The URL is a SUGGESTION, always editable. The server resolves candidates\n\t// on demand (a provider probe, then the folder-path convention); an empty\n\t// field is an honest answer and the user pastes their own.\n\t// - The job is SERVER-OWNED and keyed by the folder path, so this panel is a\n\t// view of it, never its owner. It repaints a clone started by another\n\t// device or by this phone's previous, dropped socket, and a second Clone\n\t// tap JOINS the running job rather than racing it -- in which case we say\n\t// which url is really in flight instead of pretending the edited one won.\n\t// - Progress is HONEST, and it is the SHARED display (`RestoreProgress`): the\n\t// new-session clone drives the same job and renders the very same thing, so\n\t// a phase, a scope and a real-or-explicitly-indeterminate percentage are\n\t// decided once rather than per entry point.\n\timport RestoreProgress from './RestoreProgress.svelte';\n\timport {\n\t\tfolderMissing,\n\t\trestoreState,\n\t\tstartRestore,\n\t\tcancelRestore,\n\t\treloadSession,\n\t} from '$lib/wherever';\n\timport {\n\t\tfetchConfig,\n\t\tfetchRemoteCandidates,\n\t\tgitInitDefaultStore,\n\t\ttype RemoteCandidate,\n\t} from '$lib/session-store';\n\n\tlet missing = $derived($folderMissing);\n\tlet restore = $derived($restoreState);\n\tlet job = $derived(restore?.job ?? null);\n\tlet running = $derived(job?.state === 'running');\n\tlet ready = $derived(job?.state === 'done');\n\tlet failure = $derived(job?.state === 'failed' ? job.failure : undefined);\n\tlet rejection = $derived(restore?.rejection ?? null);\n\t// A create request is out and unanswered. The clone side reads this off the\n\t// client's `requestedUrl`, which a create has none of, so it is tracked here.\n\t// It never needs clearing: the `!job && !rejection` conjunction below is what\n\t// actually opens and closes the window.\n\tlet createRequested = $state(false);\n\t// Our Clone or Create tap is out and the server has not answered yet (neither\n\t// a job nor a refusal). A tiny window on a fast link, a long one on a phone,\n\t// and the one where a second tap would fire a pointless duplicate request.\n\tlet awaitingAnswer = $derived(\n\t\t(!!restore?.requestedUrl || createRequested) && !job && !restore?.rejection,\n\t);\n\t// A clone of a DIFFERENT url is already running for this folder: our tap\n\t// joined it, so what lands here is that url, not the one in the field.\n\tlet joinedOtherUrl = $derived(\n\t\trestore?.joined &&\n\t\t\tjob?.url &&\n\t\t\trestore.requestedUrl &&\n\t\t\tjob.url !== restore.requestedUrl\n\t\t\t? job.url\n\t\t\t: null,\n\t);\n\t// Which remedy the running/finished job is: the two share every state below,\n\t// so the wording (and the submodule note, which is meaningless for a mkdir)\n\t// reads it rather than assuming a clone.\n\tlet creating = $derived(job?.kind === 'create');\n\n\tlet url = $state('');\n\tlet urlTouched = $state(false);\n\tlet candidates = $state<RemoteCandidate[]>([]);\n\tlet loadingCandidates = $state(false);\n\tlet showRawOutput = $state(false);\n\t// The second remedy, closed by default (see the header note on why it is\n\t// secondary).\n\tlet showCreate = $state(false);\n\tlet gitInit = $state(false);\n\t// null until the user touches the checkbox; while it is null the configured\n\t// default owns the value, exactly as the new-session dialog does it.\n\tlet gitInitChoice = $state<boolean | null>(null);\n\t// The path the field was last pre-filled for. A plain variable, not $state:\n\t// it guards the effect below and must not itself re-trigger it.\n\tlet prefilledFor = '';\n\n\t// Resolve the pre-fill ON DEMAND, when the panel opens for a folder. The\n\t// probe shells out to a provider CLI on the server, so this must never be a\n\t// per-keystroke or per-render call -- it is keyed on the missing path and\n\t// runs once per folder.\n\t$effect(() => {\n\t\tconst cwd = missing?.cwd;\n\t\tif (!cwd || cwd === prefilledFor) return;\n\t\tprefilledFor = cwd;\n\t\turl = '';\n\t\turlTouched = false;\n\t\tcandidates = [];\n\t\tshowCreate = false;\n\t\tgitInitChoice = null;\n\t\tcreateRequested = false;\n\t\t// Refresh the server's configured git-init default with the panel, so the\n\t\t// checkbox below reflects the CONFIG rather than whatever the store last\n\t\t// happened to hold (the session browser is what normally fetches it, and\n\t\t// the panel must not depend on that having happened). /config is a plain\n\t\t// read behind the same token gate as the candidates call beside it.\n\t\tfetchConfig();\n\t\tloadingCandidates = true;\n\t\tfetchRemoteCandidates(cwd)\n\t\t\t.then((list) => {\n\t\t\t\tcandidates = list;\n\t\t\t\t// Never overwrite something the user has already typed.\n\t\t\t\tif (!urlTouched && list.length > 0) url = list[0].url;\n\t\t\t})\n\t\t\t.finally(() => {\n\t\t\t\tloadingCandidates = false;\n\t\t\t});\n\t});\n\n\t// The git-init default is the CONFIGURED one (`gitInitDefault`, the same value\n\t// that decides whether a NEW session's folder is initialised), never a second\n\t// restore-only default: a user who turned it off must not get a surprise\n\t// repository here either. The user's own tick, once made, wins for this panel.\n\t$effect(() => {\n\t\tconst configured = $gitInitDefaultStore;\n\t\tgitInit = gitInitChoice === null ? configured : gitInitChoice;\n\t});\n\n\tfunction submitClone() {\n\t\tif (!url.trim()) return;\n\t\tshowRawOutput = false;\n\t\tcreateRequested = false;\n\t\tstartRestore('clone', url);\n\t}\n\n\tfunction submitCreate() {\n\t\tshowRawOutput = false;\n\t\tcreateRequested = true;\n\t\t// The checkbox travels EXPLICITLY, in both states, so the answer is the\n\t\t// one on screen rather than a default re-decided further down.\n\t\tstartRestore('create', undefined, gitInit);\n\t}\n</script>\n\n{#if missing}\n\t<div\n\t\tclass=\"border-t border-yellow-500/30 bg-yellow-500/10 px-4 py-3 text-sm text-yellow-400\"\n\t>\n\t\t<div class=\"font-medium\">\n\t\t\t📁 This session's folder is not on this machine\n\t\t</div>\n\t\t<div class=\"mt-1 font-mono text-xs break-all text-yellow-300\">\n\t\t\t{missing.cwd}\n\t\t</div>\n\n\t\t{#if ready}\n\t\t\t<!-- Restored. Whether a session has a live agent is a LOAD-TIME decision,\n\t\t\t and the load that found the folder missing built none, so a reload is\n\t\t\t the honest way to go live -- not a hint, the actual remedy. -->\n\t\t\t<div class=\"mt-2 text-xs text-brand-text-muted\">\n\t\t\t\t✅ The folder is ready. Reload the session to bring it back live.\n\t\t\t</div>\n\t\t\t<button\n\t\t\t\ttype=\"button\"\n\t\t\t\tonclick={() => reloadSession()}\n\t\t\t\tclass=\"mt-2 rounded bg-gradient-to-r from-brand-cyan to-brand-blue px-3.5 py-1.5 text-xs font-semibold text-brand-text transition-all hover:opacity-90\"\n\t\t\t>\n\t\t\t\tReload session\n\t\t\t</button>\n\t\t{:else if running}\n\t\t\t<!-- A job is running for this folder. It may not be ours: a second device,\n\t\t\t or this phone's own previous socket before the connection dropped. -->\n\t\t\t{#if creating}\n\t\t\t\t<div class=\"mt-2 text-xs text-brand-text-muted\">\n\t\t\t\t\tCreating the folder{job?.gitInit\n\t\t\t\t\t\t? ' and initialising a git repository in it'\n\t\t\t\t\t\t: ''}\n\t\t\t\t</div>\n\t\t\t{:else}\n\t\t\t\t<div class=\"mt-2 text-xs text-brand-text-muted\">\n\t\t\t\t\tCloning\n\t\t\t\t\t<span class=\"font-mono break-all text-brand-text\"\n\t\t\t\t\t\t>{job?.url ?? ''}</span\n\t\t\t\t\t>\n\t\t\t\t</div>\n\t\t\t{/if}\n\t\t\t{#if joinedOtherUrl}\n\t\t\t\t<div class=\"mt-1 text-xs text-yellow-300\">\n\t\t\t\t\tA clone of <span class=\"font-mono break-all\">{joinedOtherUrl}</span> was\n\t\t\t\t\talready running for this folder, so your Clone joined it. The URL you typed\n\t\t\t\t\twas NOT used; cancel it if you meant a different repository.\n\t\t\t\t</div>\n\t\t\t{/if}\n\n\t\t\t<RestoreProgress {job} />\n\n\t\t\t<button\n\t\t\t\ttype=\"button\"\n\t\t\t\tonclick={() => cancelRestore()}\n\t\t\t\tclass=\"mt-2 rounded bg-brand-surface-3 px-3.5 py-1.5 text-xs font-semibold text-brand-text transition-colors hover:bg-brand-surface-2\"\n\t\t\t>\n\t\t\t\tCancel\n\t\t\t</button>\n\t\t{:else}\n\t\t\t<!-- Offer to restore. Also the state a cancelled or failed job returns to. -->\n\t\t\t<div class=\"mt-1 text-xs text-brand-text-muted\">\n\t\t\t\tThe conversation is readable, but nothing can be run here until the\n\t\t\t\tfolder is restored. Clone the repository back into that path, then\n\t\t\t\treload the session.\n\t\t\t</div>\n\n\t\t\t{#if job?.state === 'cancelled'}\n\t\t\t\t<div class=\"mt-2 text-xs text-brand-text-muted\">\n\t\t\t\t\tThe {creating ? 'folder creation' : 'clone'} was cancelled and the folder\n\t\t\t\t\tit had created was removed.\n\t\t\t\t</div>\n\t\t\t{/if}\n\n\t\t\t{#if failure}\n\t\t\t\t<div\n\t\t\t\t\tclass=\"mt-2 rounded border border-red-500/30 bg-red-500/10 p-2 text-xs text-rose-300\"\n\t\t\t\t>\n\t\t\t\t\t<div class=\"break-words\">{failure.message}</div>\n\t\t\t\t\t{#if failure.stderr}\n\t\t\t\t\t\t<button\n\t\t\t\t\t\t\ttype=\"button\"\n\t\t\t\t\t\t\tonclick={() => (showRawOutput = !showRawOutput)}\n\t\t\t\t\t\t\tclass=\"mt-1 underline opacity-80 hover:opacity-100\"\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t{showRawOutput ? 'Hide' : 'Show'} git output\n\t\t\t\t\t\t</button>\n\t\t\t\t\t\t{#if showRawOutput}\n\t\t\t\t\t\t\t<pre\n\t\t\t\t\t\t\t\tclass=\"mt-1 max-h-32 overflow-auto rounded bg-brand-surface-3 p-2 font-mono text-[11px] whitespace-pre-wrap text-brand-text-muted\">{failure.stderr}</pre>\n\t\t\t\t\t\t{/if}\n\t\t\t\t\t{/if}\n\t\t\t\t</div>\n\t\t\t{/if}\n\n\t\t\t{#if rejection}\n\t\t\t\t<div\n\t\t\t\t\tclass=\"mt-2 rounded border border-red-500/30 bg-red-500/10 p-2 text-xs break-words text-rose-300\"\n\t\t\t\t>\n\t\t\t\t\t{rejection.message}\n\t\t\t\t</div>\n\t\t\t{/if}\n\n\t\t\t<label class=\"mt-2 block text-xs text-brand-text-muted\" for=\"restore-url\">\n\t\t\t\tRepository URL (SSH)\n\t\t\t</label>\n\t\t\t<input\n\t\t\t\tid=\"restore-url\"\n\t\t\t\ttype=\"text\"\n\t\t\t\tbind:value={url}\n\t\t\t\toninput={() => (urlTouched = true)}\n\t\t\t\tonkeydown={(e) => {\n\t\t\t\t\tif (e.key === 'Enter') submitClone();\n\t\t\t\t}}\n\t\t\t\tspellcheck=\"false\"\n\t\t\t\tautocapitalize=\"off\"\n\t\t\t\tautocorrect=\"off\"\n\t\t\t\tplaceholder={loadingCandidates\n\t\t\t\t\t? 'Looking for the repository...'\n\t\t\t\t\t: 'git@github.com:owner/repo.git'}\n\t\t\t\tclass=\"mt-1 w-full rounded border border-brand-border bg-brand-surface px-2.5 py-1.5 font-mono text-xs text-brand-text placeholder:text-brand-text-muted focus:border-brand-blue focus:outline-none\"\n\t\t\t/>\n\t\t\t{#if candidates.length > 1}\n\t\t\t\t<!-- More than one guess: the probe's and the path convention's. Offer\n\t\t\t\t them rather than silently picking, since only the user knows which\n\t\t\t\t repository this folder really was. -->\n\t\t\t\t<div class=\"mt-1 flex flex-wrap gap-1\">\n\t\t\t\t\t{#each candidates as candidate (candidate.url)}\n\t\t\t\t\t\t<button\n\t\t\t\t\t\t\ttype=\"button\"\n\t\t\t\t\t\t\tonclick={() => {\n\t\t\t\t\t\t\t\turl = candidate.url;\n\t\t\t\t\t\t\t\turlTouched = true;\n\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\tclass=\"rounded bg-brand-surface-3 px-2 py-1 font-mono text-[11px] break-all text-brand-text-muted hover:text-brand-text\"\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t{candidate.url}\n\t\t\t\t\t\t</button>\n\t\t\t\t\t{/each}\n\t\t\t\t</div>\n\t\t\t{:else if !loadingCandidates && candidates.length === 0}\n\t\t\t\t<div class=\"mt-1 text-[11px] text-brand-text-muted\">\n\t\t\t\t\tNo repository could be worked out for this folder. Paste the SSH URL\n\t\t\t\t\tto clone.\n\t\t\t\t</div>\n\t\t\t{/if}\n\n\t\t\t<button\n\t\t\t\ttype=\"button\"\n\t\t\t\tonclick={submitClone}\n\t\t\t\tdisabled={!url.trim() || awaitingAnswer}\n\t\t\t\tclass=\"mt-2 rounded bg-gradient-to-r from-brand-cyan to-brand-blue px-3.5 py-1.5 text-xs font-semibold text-brand-text transition-all hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-40\"\n\t\t\t>\n\t\t\t\t{awaitingAnswer ? 'Starting...' : 'Clone repository'}\n\t\t\t</button>\n\n\t\t\t<!-- The SECOND remedy: the folder was never a clone. Rare, so it is a\n\t\t\t disclosure rather than a button sitting beside Clone -- an accidental\n\t\t\t tap here makes an EMPTY folder that then looks restored, and the\n\t\t\t non-empty guard would refuse the clone that should have happened. -->\n\t\t\t<div class=\"mt-3 border-t border-yellow-500/20 pt-2\">\n\t\t\t\t{#if !showCreate}\n\t\t\t\t\t<button\n\t\t\t\t\t\ttype=\"button\"\n\t\t\t\t\t\tonclick={() => (showCreate = true)}\n\t\t\t\t\t\tclass=\"text-[11px] text-brand-text-muted underline opacity-80 hover:opacity-100\"\n\t\t\t\t\t>\n\t\t\t\t\t\tThis folder was never a clone? Create it instead\n\t\t\t\t\t</button>\n\t\t\t\t{:else}\n\t\t\t\t\t<div class=\"text-[11px] text-brand-text-muted\">\n\t\t\t\t\t\tMakes the folder and any missing parents. Nothing is downloaded, so\n\t\t\t\t\t\twhatever the folder used to hold is not coming back with it.\n\t\t\t\t\t</div>\n\t\t\t\t\t<div class=\"mt-1.5 flex items-center gap-2\">\n\t\t\t\t\t\t<input\n\t\t\t\t\t\t\tid=\"restore-git-init\"\n\t\t\t\t\t\t\ttype=\"checkbox\"\n\t\t\t\t\t\t\tchecked={gitInit}\n\t\t\t\t\t\t\tonchange={(e) => (gitInitChoice = e.currentTarget.checked)}\n\t\t\t\t\t\t\tclass=\"h-3.5 w-3.5 rounded border-brand-border bg-brand-surface-3 text-brand-blue focus:ring-brand-blue\"\n\t\t\t\t\t\t/>\n\t\t\t\t\t\t<label\n\t\t\t\t\t\t\tfor=\"restore-git-init\"\n\t\t\t\t\t\t\tclass=\"cursor-pointer text-xs text-brand-text-muted select-none\"\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\tInitialise a git repository\n\t\t\t\t\t\t</label>\n\t\t\t\t\t</div>\n\t\t\t\t\t<button\n\t\t\t\t\t\ttype=\"button\"\n\t\t\t\t\t\tonclick={submitCreate}\n\t\t\t\t\t\tdisabled={awaitingAnswer}\n\t\t\t\t\t\tclass=\"mt-2 rounded border border-brand-border bg-brand-surface-3 px-3 py-1 text-[11px] font-medium text-brand-text-muted transition-colors hover:bg-brand-surface-2 hover:text-brand-text disabled:cursor-not-allowed disabled:opacity-40\"\n\t\t\t\t\t>\n\t\t\t\t\t\t{awaitingAnswer ? 'Creating...' : 'Create folder'}\n\t\t\t\t\t</button>\n\t\t\t\t{/if}\n\t\t\t</div>\n\t\t{/if}\n\t</div>\n{/if}\n","<script lang=\"ts\">\n\timport Head from '$lib/Head.svelte';\n\timport ConnectionSettings from '$lib/components/ConnectionSettings.svelte';\n\timport AssistantPushSettings from '$lib/components/AssistantPushSettings.svelte';\n\timport AssistantTelegramSettings from '$lib/components/AssistantTelegramSettings.svelte';\n\timport {telegramSectionVisible} from '$lib/core/telegram-settings';\n\timport ChatMessageList from '$lib/components/ChatMessageList.svelte';\n\timport ChatInput from '$lib/components/ChatInput.svelte';\n\timport SessionBrowser from '$lib/components/SessionBrowser.svelte';\n\timport ConversationSearch from '$lib/components/ConversationSearch.svelte';\n\timport SudoPasswordDialog from '$lib/components/SudoPasswordDialog.svelte';\n\timport RestorePanel from '$lib/components/RestorePanel.svelte';\n\timport RestoreProgress from '$lib/components/RestoreProgress.svelte';\n\timport {\n\t\tpiState,\n\t\trestoreState,\n\t\tcancelRestore,\n\t\tisConnected,\n\t\tisInterrupted,\n\t\tsessionError,\n\t\tsessionNotice,\n\t\tfolderConflict,\n\t\tfolderMissing,\n\t\tcontinueFolderConflict,\n\t\tisReadOnly,\n\t\tactiveSessionInfo,\n\t\tconnect,\n\t\tdisconnect,\n\t\tsuspend,\n\t\tresume,\n\t\tnoteVisible,\n\t\tleaveSession,\n\t\tdismissSessionError,\n\t\tdismissNotice,\n\t\tchangeModel,\n\t\tjoinSession,\n\t\tswitchSession,\n\t\tisCreatingSession,\n\t\tisResyncing,\n\t\tisLoadingSession,\n\t\tisAgentPending,\n\t\thasSuspendedSession,\n\t\tisFilePickerActive,\n\t\tendFilePicker,\n\t\trunSearch,\n\t\thasActiveSession,\n\t\treadBootConversation,\n\t\thydrateFromCache,\n\t\tflushConversationCache,\n\t\tclearConversationCache,\n\t\topenAssistant,\n\t\tresetAssistant,\n\t} from '$lib/wherever';\n\timport {\n\t\tfetchSessions,\n\t\tfetchReadOnlySessions,\n\t\tavailableModels,\n\t\tsearchFolderStore,\n\t\tsearchDefaultModelStore,\n\t\tappearanceStore,\n\t\tsessionFolders,\n\t\treadOnlySessionFolders,\n\t\tsetSessionStarred,\n\t\tassistantStatusStore,\n\t\tisAssistantSession,\n\t} from '$lib/session-store';\n\timport {onMount} from 'svelte';\n\timport {version} from '$app/environment';\n\timport {url} from '$lib/core/utils/web/path';\n\timport {decideHashJoin, isSearchActive} from '$lib/core/view-mode';\n\timport {decideReturn, runBoot} from '$lib/core/instant-resume';\n\n\tlet sidebarOpen = $state(false);\n\t// Which session list the sidebar shows: the main dashboard, the separate\n\t// read-only page (sessions.readOnly folders) reached via the sidebar link, or\n\t// conversation search (full-text over every past session, GET /search).\n\t// The read-only page hides the create form, delete controls, and the composer.\n\tlet sessionView = $state<'main' | 'readonly' | 'search'>('main');\n\t// Search mirrors the two list views rather than spanning them: it is opened\n\t// from one of them and searches exactly that view's sessions, so the visibility\n\t// rule a user already understands from the list also holds for search.\n\tlet searchReadOnly = $state(false);\n\tlet searchInitialQuery = $state('');\n\n\tfunction openSearch(fromReadOnly: boolean, initial = '') {\n\t\tsearchReadOnly = fromReadOnly;\n\t\tsearchInitialQuery = initial;\n\t\tsessionView = 'search';\n\t}\n\tlet showSettings = $state(false);\n\tlet autoConnect = $state(true);\n\tlet interruptedTimeout: ReturnType<typeof setTimeout> | null = null;\n\tlet chatList: {forceScrollToBottom: () => void};\n\n\t// True until boot has ISSUED its own connect() (not until the socket opens,\n\t// or an offline cache miss would hold the handlers off forever). While set,\n\t// pageshow / visibilitychange do not connect: on a fresh load pageshow always\n\t// fires, and its plain connect() would reset a hydration in progress.\n\tlet booting = true;\n\n\tonMount(() => {\n\t\tif (autoConnect) {\n\t\t\t// Instant resume (docs/adr/0013): when the hash names a session, start\n\t\t\t// reading its cached copy now (capped at ~300 ms), alongside the existing\n\t\t\t// 200 ms boot delay. A hit is painted and connected with the store\n\t\t\t// preserved, so the conversation shows before the socket opens; a miss\n\t\t\t// boots exactly as before.\n\t\t\tconst cached = readBootConversation(readHashId());\n\t\t\tsetTimeout(() => {\n\t\t\t\tvoid runBoot({\n\t\t\t\t\tcached,\n\t\t\t\t\thydrate: hydrateFromCache,\n\t\t\t\t\tconnect: (opts) => {\n\t\t\t\t\t\tbooting = false;\n\t\t\t\t\t\tconnect(opts);\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}, 200);\n\t\t} else {\n\t\t\tbooting = false;\n\t\t}\n\n\t\tconst handleHashChange = () => {\n\t\t\t// A new hash is a new intent: forget any failed auto-join attempt.\n\t\t\thashJoinAttempt = null;\n\t\t\tif (connected) {\n\t\t\t\tconst hashId = window.location.hash\n\t\t\t\t\t? decodeURIComponent(window.location.hash.slice(1))\n\t\t\t\t\t: '';\n\t\t\t\tif (hashId && hashId !== currentSessionId) {\n\t\t\t\t\t// Record it as this hash's attempt, so a failed load is not re-joined\n\t\t\t\t\t// by the auto-join effect (a second failure per Back press).\n\t\t\t\t\thashJoinAttempt = hashId;\n\t\t\t\t\t// Atomic switch (no leave -> setTimeout -> join gap that could strand\n\t\t\t\t\t// the loading spinner). switchSession leaves the current session first\n\t\t\t\t\t// when there is one and loads the target either way.\n\t\t\t\t\tswitchSession(hashId);\n\t\t\t\t} else if (!hashId && currentSessionId) {\n\t\t\t\t\tleaveSession();\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\t\twindow.addEventListener('hashchange', handleHashChange);\n\n\t\t// --- Background/resume handling (esp. Firefox Android screen-lock) ---\n\t\t// While the page is backgrounded we close the WebSocket. An open WS makes\n\t\t// the page ineligible for the browser's back/forward cache, which on\n\t\t// mobile pushes the browser toward a full, slow reload on resume. Closing\n\t\t// it improves bfcache eligibility (instant restore) and, when a real\n\t\t// reload does happen, the active session is restored from the URL hash.\n\t\t// The disconnect is delayed so quick tab switches don't churn the\n\t\t// connection; reconnect is immediate on return.\n\t\tlet hiddenTimer: ReturnType<typeof setTimeout> | null = null;\n\t\tconst HIDE_DISCONNECT_DELAY = 8000;\n\n\t\tconst handleVisibility = () => {\n\t\t\tif (document.visibilityState === 'hidden') {\n\t\t\t\t// The OS may kill a hidden PWA without another event: save the\n\t\t\t\t// conversation now so a reload can paint it at once.\n\t\t\t\tflushConversationCache();\n\t\t\t\t// A native file picker / camera backgrounds the page. Don't schedule a\n\t\t\t\t// suspend in that window, or a slow file selection (e.g. taking a\n\t\t\t\t// photo) would tear down the session and make the upload fail with\n\t\t\t\t// \"No active session\" on return.\n\t\t\t\tif (isFilePickerActive()) return;\n\t\t\t\tif (hiddenTimer) clearTimeout(hiddenTimer);\n\t\t\t\thiddenTimer = setTimeout(() => {\n\t\t\t\t\thiddenTimer = null;\n\t\t\t\t\tif (document.visibilityState === 'hidden' && connected) {\n\t\t\t\t\t\t// Suspend (not disconnect): keep the cached session/messages so\n\t\t\t\t\t\t// returning resyncs in place instead of reloading from scratch.\n\t\t\t\t\t\tsuspend();\n\t\t\t\t\t}\n\t\t\t\t}, HIDE_DISCONNECT_DELAY);\n\t\t\t} else {\n\t\t\t\t// Back in the foreground: the picker (if any) is closed. Clear the\n\t\t\t\t// guard so a cancelled picker doesn't leave suspend disabled. The\n\t\t\t\t// upload's own session check already ran synchronously on the file\n\t\t\t\t// change, so the session is no longer needed to be pinned here.\n\t\t\t\tendFilePicker();\n\t\t\t\tif (hiddenTimer) {\n\t\t\t\t\tclearTimeout(hiddenTimer);\n\t\t\t\t\thiddenTimer = null;\n\t\t\t\t}\n\t\t\t\t// On EVERY return, probe a socket that is still open: timers fire\n\t\t\t\t// before the frames queued during the freeze, so the silence clock\n\t\t\t\t// alone would tear a healthy socket down (docs/adr/0011).\n\t\t\t\tnoteVisible();\n\t\t\t\t// Prefer the preserve-cache resume() path whenever we still hold an\n\t\t\t\t// active session -- from an explicit suspend OR an unsolicited drop that\n\t\t\t\t// happened while hidden (before the 8s suspend). resume() rejoins in\n\t\t\t\t// place and keeps the conversation visible; a plain connect() would wipe\n\t\t\t\t// the session and re-show the search / new-session empty-state. Only a\n\t\t\t\t// truly empty client (no session at all) falls back to connect(), where\n\t\t\t\t// the hash auto-join drives the load. Nothing while booting (see\n\t\t\t\t// `booting`): boot issues its own connect.\n\t\t\t\tconst action = decideReturn({\n\t\t\t\t\tbooting,\n\t\t\t\t\tconnected,\n\t\t\t\t\thasActiveSession: hasActiveSession(),\n\t\t\t\t});\n\t\t\t\tif (action === 'resume') resume();\n\t\t\t\telse if (action === 'connect') connect();\n\t\t\t}\n\t\t};\n\n\t\tconst handlePageShow = (e: PageTransitionEvent) => {\n\t\t\t// On bfcache restore (e.persisted) or any return to a visible page,\n\t\t\t// resume the suspended connection, rejoining the cached session in place.\n\t\t\tif (hiddenTimer) {\n\t\t\t\tclearTimeout(hiddenTimer);\n\t\t\t\thiddenTimer = null;\n\t\t\t}\n\t\t\tif (document.visibilityState === 'hidden') return;\n\t\t\t// Probe a still-open socket on every visible pageshow too (see\n\t\t\t// handleVisibility). Not on a hidden one: noteVisible() takes the fast\n\t\t\t// paths meant for a user who is looking at the page.\n\t\t\tnoteVisible();\n\t\t\tconst action = decideReturn({\n\t\t\t\tbooting,\n\t\t\t\tconnected,\n\t\t\t\thasActiveSession: hasActiveSession(),\n\t\t\t});\n\t\t\tif (action === 'resume') resume();\n\t\t\telse if (action === 'connect') connect();\n\t\t};\n\n\t\t// Last chance to save the conversation before the page goes away.\n\t\tconst handlePageHide = () => flushConversationCache();\n\n\t\tdocument.addEventListener('visibilitychange', handleVisibility);\n\t\twindow.addEventListener('pageshow', handlePageShow);\n\t\twindow.addEventListener('pagehide', handlePageHide);\n\n\t\treturn () => {\n\t\t\twindow.removeEventListener('hashchange', handleHashChange);\n\t\t\tdocument.removeEventListener('visibilitychange', handleVisibility);\n\t\t\twindow.removeEventListener('pageshow', handlePageShow);\n\t\t\twindow.removeEventListener('pagehide', handlePageHide);\n\t\t\tif (hiddenTimer) clearTimeout(hiddenTimer);\n\t\t};\n\t});\n\n\tfunction handleConnected() {\n\t\tconnect();\n\t}\n\n\t// \"Disconnect Server\" wipes the on-device cache (ADR 0013). Only here and in\n\t// ConnectionSettings' Disconnect, never in the shared disconnect(), which\n\t// Reconnect below also calls.\n\tfunction handleDisconnect() {\n\t\tleaveSession();\n\t\tdisconnect();\n\t\tclearConversationCache();\n\t}\n\n\tfunction handleReconnect() {\n\t\tdisconnect();\n\t\tsetTimeout(() => connect(), 100);\n\t}\n\n\tfunction handleRefresh() {\n\t\tfetchSessions();\n\t}\n\n\tfunction handleShowMainScreen() {\n\t\tif (typeof window !== 'undefined') {\n\t\t\twindow.location.hash = '';\n\t\t}\n\t\tleaveSession();\n\t\tsidebarOpen = false;\n\t}\n\n\tlet connected = $derived($isConnected);\n\tlet resyncing = $derived($isResyncing);\n\tlet agentPending = $derived($isAgentPending);\n\tlet loadingSession = $derived($isLoadingSession);\n\tlet interrupted = $derived($isInterrupted);\n\tlet sError = $derived($sessionError);\n\tlet notice = $derived($sessionNotice);\n\tlet fConflict = $derived($folderConflict);\n\tlet fMissing = $derived($folderMissing);\n\tlet readOnly = $derived($isReadOnly);\n\tlet sessionInfo = $derived($activeSessionInfo);\n\tlet appState = $derived($piState);\n\tlet models = $derived($availableModels.models);\n\n\tlet wasSessionActive = $state(false);\n\tlet currentSessionId = $derived(sessionInfo.sessionId);\n\n\t// Is the open session starred? Read from the session LISTS (the star lives on\n\t// the listing, server-side), checking both the main and the read-only list.\n\tlet currentStarred = $derived.by(() => {\n\t\tconst file = sessionInfo.sessionFile;\n\t\tif (!file) return false;\n\t\tfor (const store of [$sessionFolders, $readOnlySessionFolders]) {\n\t\t\tfor (const folder of store.folders) {\n\t\t\t\tconst hit = folder.sessions.find((s) => s.path === file);\n\t\t\t\tif (hit) return !!hit.starred;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t});\n\n\t// Update hash when sessionId changes, only if connected to prevent clearing on reload\n\t$effect(() => {\n\t\tif (typeof window !== 'undefined' && connected) {\n\t\t\tif (currentSessionId) {\n\t\t\t\twindow.location.hash = encodeURIComponent(currentSessionId);\n\t\t\t\twasSessionActive = true;\n\t\t\t} else if (wasSessionActive) {\n\t\t\t\twasSessionActive = false;\n\t\t\t\tif (window.location.hash) {\n\t\t\t\t\twindow.location.hash = '';\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t});\n\n\t// Auto-join session from hash when connected.\n\t//\n\t// Self-healing by design: it re-evaluates whenever we are connected with a hash\n\t// but no session is active for it. An earlier guard latched per join and was\n\t// reset on disconnect, but rapid connect/disconnect churn (e.g. a reconnect\n\t// racing a resume) could flip `connected` within a single effect flush so the\n\t// reset was never observed, leaving the guard latched and the session never\n\t// loaded, which hung the \"Loading session...\" spinner forever. Gating purely on\n\t// the live state (active session id + loading/resync flags) instead avoids that.\n\t//\n\t// But it must not retry a load that already FAILED: an untagged session_error\n\t// (e.g. the hash names a deleted session) clears loadingSession, which\n\t// re-runs this effect with currentSessionId still null, so it used to re-join\n\t// every ~300 ms forever with a flickering error and a permanent spinner.\n\t// `hashJoinAttempt` remembers the id we last issued a join for; it is reset\n\t// on success, on disconnect (a load cut by a dropped socket must be retried\n\t// after reconnecting) and on a hash change. decideHashJoin is unit-tested.\n\tlet hashJoinTimer: ReturnType<typeof setTimeout> | null = null;\n\tlet hashJoinAttempt: string | null = null;\n\tfunction readHashId(): string {\n\t\tif (typeof window === 'undefined' || !window.location.hash) return '';\n\t\treturn decodeURIComponent(window.location.hash.slice(1));\n\t}\n\t$effect(() => {\n\t\tif (!connected) {\n\t\t\thashJoinAttempt = null;\n\t\t\treturn;\n\t\t}\n\t\tconst hashId = readHashId();\n\t\tif (hashId && currentSessionId === hashId) hashJoinAttempt = null;\n\t\tconst decision = decideHashJoin({\n\t\t\tconnected,\n\t\t\thashId,\n\t\t\tcurrentSessionId,\n\t\t\tloading: loadingSession,\n\t\t\tresyncing,\n\t\t\tcreating: $isCreatingSession,\n\t\t\tattemptedHashId: hashJoinAttempt,\n\t\t});\n\t\tif (decision === 'failed') {\n\t\t\t// Stop here. The error banner explains why; drop the hash so the URL\n\t\t\t// no longer names a session that cannot be opened, and the message area\n\t\t\t// falls back to the home state instead of a spinner.\n\t\t\t// replaceState, NOT `location.hash = ''`: that pushed a history entry and\n\t\t\t// fired hashchange, so Back returned to the dead hash, which failed\n\t\t\t// again and pushed again, trapping the Back button. replaceState fires\n\t\t\t// no hashchange; the non-reactive hash read is covered by loadFailed.\n\t\t\thashJoinAttempt = null;\n\t\t\tif (window.location.hash) {\n\t\t\t\thistory.replaceState(\n\t\t\t\t\thistory.state,\n\t\t\t\t\t'',\n\t\t\t\t\twindow.location.pathname + window.location.search,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (decision !== 'join') return;\n\t\tif (hashJoinTimer) return; // a join is already pending\n\t\thashJoinTimer = setTimeout(() => {\n\t\t\thashJoinTimer = null;\n\t\t\tconst id = readHashId();\n\t\t\tif (\n\t\t\t\tdecideHashJoin({\n\t\t\t\t\tconnected,\n\t\t\t\t\thashId: id,\n\t\t\t\t\tcurrentSessionId,\n\t\t\t\t\tloading: loadingSession,\n\t\t\t\t\tresyncing,\n\t\t\t\t\tcreating: $isCreatingSession,\n\t\t\t\t\tattemptedHashId: hashJoinAttempt,\n\t\t\t\t}) !== 'join'\n\t\t\t) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\thashJoinAttempt = id;\n\t\t\tjoinSession(id);\n\t\t}, 300);\n\t});\n\n\t// Reset transient flags on disconnect.\n\t$effect(() => {\n\t\tif (!connected) {\n\t\t\twasSessionActive = false;\n\t\t}\n\t});\n\n\t// Close sidebar on mobile when a session is joined OR as soon as a load is in\n\t// flight. Previously it only closed once `currentSessionId` was set, so if the\n\t// load stalled (the \"Loading session...\" spinner hanging) the sidebar stayed\n\t// open over it. Closing on the loading/resync flag too means the tap always\n\t// dismisses the sidebar, and the user sees the spinner (or its eventual error)\n\t// rather than a stuck open sidebar.\n\t$effect(() => {\n\t\tif (currentSessionId || loadingSession || resyncing) {\n\t\t\tsidebarOpen = false;\n\t\t}\n\t});\n\n\tlet isCreating = $derived($isCreatingSession);\n\t// The CLONE half of a new session in a folder that has to be cloned first: the\n\t// server runs it as a restore job and reports it, so the create shows real\n\t// progress instead of a blind overlay a 25s watchdog gives up on. It ends by\n\t// itself -- the server continues into creating the session once the clone is\n\t// done -- so there is no Reload here, unlike the restore panel.\n\tlet createRestore = $derived(\n\t\t$restoreState?.forSessionCreate ? $restoreState : null,\n\t);\n\tlet searchFolder = $derived($searchFolderStore);\n\t// The Assistant entry point shows only while the assistant is ACTIVE on this\n\t// server (configured and holding its folder lock); Reset only on the current\n\t// assistant session itself.\n\tlet assistantActive = $derived($assistantStatusStore.active);\n\tlet viewingAssistant = $derived(\n\t\tisAssistantSession($assistantStatusStore, sessionInfo.sessionFile),\n\t);\n\n\t// The bottom composer is always mounted but mode-switched: it acts as the\n\t// search composer when connected, a search folder is configured, and no\n\t// session is active. Keeping it mounted (not conditionally rendered) means it\n\t// exists at tap time so we can focus it synchronously inside a user gesture.\n\tlet chatInput: {focusInput: () => void} | undefined = $state();\n\t// The composer's search mode must mirror the message area's empty-state so the\n\t// two never disagree (the bug: a \"Loading session...\" spinner with an enabled\n\t// search box). isSearchActive treats a session that is loading/resyncing, or a\n\t// hash pointing at a session we are about to open, as NOT the search state even\n\t// though sessionFile is briefly still null.\n\tlet searchActive = $derived(\n\t\tisSearchActive({\n\t\t\tconnected,\n\t\t\tsearchConfigured: !!searchFolder,\n\t\t\thasSession: !!sessionInfo.sessionFile,\n\t\t\tloading: loadingSession,\n\t\t\tresyncing,\n\t\t\thasSessionHash: typeof window !== 'undefined' && !!window.location.hash,\n\t\t\tloadFailed:\n\t\t\t\t!!sError && !loadingSession && !resyncing && !sessionInfo.sessionFile,\n\t\t}),\n\t);\n\n\t// Search-mode model picker. Options mirror the sidebar new-session list; the\n\t// selection is seeded from the search folder's server-resolved default (which\n\t// honors folder-local harness/pi config), falling back to the models list's\n\t// isDefault entry, then the first model.\n\tlet searchModels = $derived(\n\t\tmodels.map((m) => ({\n\t\t\tvalue: `${m.provider}:${m.modelId}`,\n\t\t\tlabel: `${m.label}${m.isDefault ? ' (default)' : ''}`,\n\t\t})),\n\t);\n\tlet searchDefaultModel = $derived($searchDefaultModelStore);\n\t// Visual identity of the connected instance: theming is applied at fetch\n\t// time (session-store), here it only feeds the title and the sidebar badge.\n\tlet appearanceLabel = $derived($appearanceStore.label);\n\tlet searchModel = $state('');\n\t// Seed (or re-seed) the selection once options are available and nothing valid\n\t// is chosen yet. Runs when the model list or folder default changes.\n\t$effect(() => {\n\t\tif (searchModels.length === 0) return;\n\t\tconst valid = searchModels.some((m) => m.value === searchModel);\n\t\tif (valid) return;\n\t\tconst folderDefault = searchModels.find(\n\t\t\t(m) => m.value === searchDefaultModel,\n\t\t);\n\t\tconst listDefault = models.find((m) => m.isDefault);\n\t\tsearchModel = folderDefault\n\t\t\t? folderDefault.value\n\t\t\t: listDefault\n\t\t\t\t? `${listDefault.provider}:${listDefault.modelId}`\n\t\t\t\t: searchModels[0].value;\n\t});\n\n\t// On page load with no session, focus the search composer so it is ready to\n\t// type. (One-shot; not inside the tap path, so no mobile-keyboard concern.)\n\tlet hasFocusedSearch = $state(false);\n\t$effect(() => {\n\t\tif (searchActive && !hasFocusedSearch && chatInput) {\n\t\t\thasFocusedSearch = true;\n\t\t\tchatInput.focusInput();\n\t\t}\n\t});\n\n\t// Top-bar magnifier (active-session case): leave the session and focus the\n\t// search composer SYNCHRONOUSLY inside this gesture so the mobile virtual\n\t// keyboard rises (focusing later from a reactive effect would not, esp. iOS).\n\tfunction startSearch() {\n\t\t// Clear the hash synchronously so the chat area drops straight to the\n\t\t// search empty-state instead of flashing the \"Loading session...\" spinner\n\t\t// (ChatMessageList reads window.location.hash, which is not reactive).\n\t\tif (typeof window !== 'undefined' && window.location.hash) {\n\t\t\twindow.location.hash = '';\n\t\t}\n\t\tleaveSession();\n\t\tchatInput?.focusInput();\n\t}\n</script>\n\n<Head\n\ttitle={appearanceLabel ? `Wherever · ${appearanceLabel}` : 'Wherever'}\n\tdescription=\"Create & maintain apps from wherever\"\n/>\n\n{#if createRestore}\n\t<div\n\t\tclass=\"fixed inset-0 z-[100] flex items-center justify-center bg-brand-dark/60 p-4 backdrop-blur-sm\"\n\t>\n\t\t<div\n\t\t\tclass=\"w-full max-w-sm rounded-lg border border-brand-border bg-brand-surface-2 p-5 text-brand-text\"\n\t\t>\n\t\t\t<div class=\"text-base font-bold\">Cloning the repository...</div>\n\t\t\t<div class=\"mt-1 text-xs text-brand-text-muted\">\n\t\t\t\tThe session is created as soon as the clone finishes, so there is\n\t\t\t\tnothing to wait for afterwards. It keeps running on the server if this\n\t\t\t\tpage goes away.\n\t\t\t</div>\n\t\t\t{#if createRestore.job?.url}\n\t\t\t\t<div class=\"mt-2 font-mono text-xs break-all text-brand-text-muted\">\n\t\t\t\t\t{createRestore.job.url}\n\t\t\t\t</div>\n\t\t\t{/if}\n\t\t\t<RestoreProgress job={createRestore.job} />\n\t\t\t<button\n\t\t\t\ttype=\"button\"\n\t\t\t\tonclick={() => cancelRestore()}\n\t\t\t\tclass=\"mt-3 rounded bg-brand-surface-3 px-3.5 py-1.5 text-xs font-semibold text-brand-text transition-colors hover:bg-brand-surface-2\"\n\t\t\t>\n\t\t\t\tCancel\n\t\t\t</button>\n\t\t</div>\n\t</div>\n{:else if isCreating}\n\t<div\n\t\tclass=\"fixed inset-0 z-[100] flex items-center justify-center bg-brand-dark/60 backdrop-blur-sm\"\n\t>\n\t\t<div class=\"flex flex-col items-center gap-4\">\n\t\t\t<div\n\t\t\t\tclass=\"h-12 w-12 animate-spin rounded-full border-4 border-brand-blue border-t-transparent\"\n\t\t\t></div>\n\t\t\t<span class=\"text-lg font-bold text-brand-text\">Creating session...</span>\n\t\t</div>\n\t</div>\n{/if}\n\n<div\n\tclass=\"fixed inset-0 flex overflow-hidden overscroll-none bg-brand-dark text-brand-text\"\n>\n\t<!-- Sidebar -->\n\t<div\n\t\tclass=\"app-chrome {sidebarOpen\n\t\t\t? 'translate-x-0'\n\t\t\t: '-translate-x-full'} fixed z-20 flex h-full w-72 flex-col border-r border-brand-border bg-brand-surface transition-transform duration-200 md:relative md:translate-x-0\"\n\t>\n\t\t<div class=\"border-b border-brand-border bg-brand-surface-2/20 p-4\">\n\t\t\t<div class=\"flex items-center justify-between\">\n\t\t\t\t{#if showSettings}\n\t\t\t\t\t<span class=\"text-lg font-bold text-brand-text\"\n\t\t\t\t\t\t>Connection Settings</span\n\t\t\t\t\t>\n\t\t\t\t\t<button\n\t\t\t\t\t\tonclick={() => (showSettings = false)}\n\t\t\t\t\t\tclass=\"rounded px-2 py-1 text-xs font-semibold text-brand-blue transition-colors hover:bg-brand-surface-2 hover:text-brand-blue\"\n\t\t\t\t\t>\n\t\t\t\t\t\t◀ Back\n\t\t\t\t\t</button>\n\t\t\t\t{:else}\n\t\t\t\t\t<button\n\t\t\t\t\t\tonclick={handleShowMainScreen}\n\t\t\t\t\t\tclass=\"flex items-center gap-2 text-left\"\n\t\t\t\t\t\ttitle=\"Show Main Screen / New Session\"\n\t\t\t\t\t>\n\t\t\t\t\t\t<img src={url('/logo.svg')} alt=\"Wherever\" class=\"h-6 w-6\" />\n\t\t\t\t\t\t<span class=\"gradient-text text-lg font-bold\">Wherever</span>\n\t\t\t\t\t\t{#if appearanceLabel}\n\t\t\t\t\t\t\t<!-- Instance badge: shows WHICH machine's server you are talking to,\n\t\t\t\t\t\t\t tinted by the instance accent (brand-blue). -->\n\t\t\t\t\t\t\t<span\n\t\t\t\t\t\t\t\tclass=\"max-w-32 truncate rounded-full border border-brand-border bg-brand-blue/15 px-2 py-0.5 text-[10px] font-semibold text-brand-blue\"\n\t\t\t\t\t\t\t\ttitle={appearanceLabel}>{appearanceLabel}</span\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t{/if}\n\t\t\t\t\t</button>\n\t\t\t\t\t<div class=\"flex items-center gap-2\">\n\t\t\t\t\t\t<button\n\t\t\t\t\t\t\tonclick={() => (showSettings = true)}\n\t\t\t\t\t\t\tclass=\"flex items-center gap-1 rounded border border-brand-border px-1.5 py-1 text-xs text-brand-text-muted transition-colors hover:bg-brand-surface-2 hover:text-brand-text\"\n\t\t\t\t\t\t\ttitle=\"Connection Settings\"\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t⚙️ Config\n\t\t\t\t\t\t</button>\n\t\t\t\t\t\t<button\n\t\t\t\t\t\t\tonclick={() => (sidebarOpen = false)}\n\t\t\t\t\t\t\tclass=\"text-brand-text-muted hover:text-brand-text md:hidden\"\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\tX\n\t\t\t\t\t\t</button>\n\t\t\t\t\t</div>\n\t\t\t\t{/if}\n\t\t\t</div>\n\t\t</div>\n\n\t\t{#if showSettings}\n\t\t\t<div class=\"flex-1 overflow-y-auto\">\n\t\t\t\t<ConnectionSettings\n\t\t\t\t\thost={appState.connected ? 'localhost' : 'localhost'}\n\t\t\t\t\tport={31415}\n\t\t\t\t\ttoken=\"\"\n\t\t\t\t\tonConnected={handleConnected}\n\t\t\t\t/>\n\n\t\t\t\t{#if $assistantStatusStore.active && $assistantStatusStore.webPush?.enabled}\n\t\t\t\t\t<AssistantPushSettings currentSessionId={currentSessionId ?? null} />\n\t\t\t\t{/if}\n\n\t\t\t\t{#if $assistantStatusStore.telegram && telegramSectionVisible($assistantStatusStore)}\n\t\t\t\t\t<AssistantTelegramSettings status={$assistantStatusStore.telegram} />\n\t\t\t\t{/if}\n\n\t\t\t\t<div class=\"mt-2 border-t border-brand-border p-4\">\n\t\t\t\t\t<h3\n\t\t\t\t\t\tclass=\"mb-3 text-xs font-bold tracking-wider text-brand-text-muted uppercase\"\n\t\t\t\t\t>\n\t\t\t\t\t\tServer Control\n\t\t\t\t\t</h3>\n\t\t\t\t\t<div class=\"space-y-2\">\n\t\t\t\t\t\t<button\n\t\t\t\t\t\t\tonclick={handleRefresh}\n\t\t\t\t\t\t\tclass=\"flex w-full items-center justify-between rounded border border-brand-border bg-brand-surface-2 px-3 py-2 text-left text-sm text-brand-text transition-colors hover:bg-brand-surface-3 hover:text-brand-text\"\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t<span>Refresh Session List</span>\n\t\t\t\t\t\t\t<span>🔄</span>\n\t\t\t\t\t\t</button>\n\t\t\t\t\t\t<button\n\t\t\t\t\t\t\tonclick={handleReconnect}\n\t\t\t\t\t\t\tclass=\"flex w-full items-center justify-between rounded border border-brand-border bg-brand-surface-2 px-3 py-2 text-left text-sm text-brand-text transition-colors hover:bg-brand-surface-3 hover:text-brand-text\"\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t<span>Reconnect WebSocket</span>\n\t\t\t\t\t\t\t<span>🔌</span>\n\t\t\t\t\t\t</button>\n\t\t\t\t\t\t<button\n\t\t\t\t\t\t\tonclick={handleDisconnect}\n\t\t\t\t\t\t\tclass=\"flex w-full items-center justify-between rounded border border-red-500/30 bg-red-500/10 px-3 py-2 text-left text-sm text-rose-400 transition-colors hover:bg-red-500/20 hover:text-rose-300\"\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t<span>Disconnect Server</span>\n\t\t\t\t\t\t\t<span>🛑</span>\n\t\t\t\t\t\t</button>\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n\t\t\t</div>\n\t\t{:else}\n\t\t\t<!-- Connection status -->\n\t\t\t<div class=\"border-b border-brand-border p-4\">\n\t\t\t\t<div class=\"flex items-center gap-2\">\n\t\t\t\t\t<div\n\t\t\t\t\t\tclass=\"h-2.5 w-2.5 rounded-full {connected\n\t\t\t\t\t\t\t? 'bg-emerald-500'\n\t\t\t\t\t\t\t: 'bg-rose-500'}\"\n\t\t\t\t\t></div>\n\t\t\t\t\t<span\n\t\t\t\t\t\tclass=\"text-sm {connected ? 'text-emerald-400' : 'text-rose-400'}\"\n\t\t\t\t\t>\n\t\t\t\t\t\t{connected ? 'Connected' : 'Disconnected'}\n\t\t\t\t\t</span>\n\t\t\t\t\t<span\n\t\t\t\t\t\tclass=\"selectable ml-auto font-mono text-xs text-brand-text-muted\"\n\t\t\t\t\t\ttitle={appState.serverVersion\n\t\t\t\t\t\t\t? `App build ${version} · server ${appState.serverVersion}${appState.piVersion ? ` · pi ${appState.piVersion}` : ''}`\n\t\t\t\t\t\t\t: `App build ${version}`}\n\t\t\t\t\t>\n\t\t\t\t\t\tv{version}{#if appState.serverVersion}<span\n\t\t\t\t\t\t\t\tclass=\"text-brand-text-muted/70\"\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t&nbsp;/ srv {appState.serverVersion}</span\n\t\t\t\t\t\t\t>{/if}\n\t\t\t\t\t</span>\n\t\t\t\t</div>\n\t\t\t\t{#if sessionInfo.sessionFile}\n\t\t\t\t\t<div class=\"mt-2 space-y-1\">\n\t\t\t\t\t\t{#if sessionInfo.cwd}\n\t\t\t\t\t\t\t<div\n\t\t\t\t\t\t\t\tclass=\"truncate text-xs text-brand-text-muted\"\n\t\t\t\t\t\t\t\ttitle={sessionInfo.cwd}\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t📁 {sessionInfo.cwd.split('/').pop() || sessionInfo.cwd}\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t{#if sessionInfo.model}\n\t\t\t\t\t\t\t<div\n\t\t\t\t\t\t\t\tclass=\"truncate text-xs text-brand-text-muted\"\n\t\t\t\t\t\t\t\ttitle={sessionInfo.model}\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t🤖 {sessionInfo.model}\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t<div class=\"pt-1.5\">\n\t\t\t\t\t\t\t<button\n\t\t\t\t\t\t\t\tonclick={handleShowMainScreen}\n\t\t\t\t\t\t\t\tclass=\"w-full rounded border border-brand-border bg-brand-surface-2 px-2 py-1 text-center text-xs text-brand-text transition-colors hover:bg-brand-surface-3 hover:text-brand-text\"\n\t\t\t\t\t\t\t\ttitle=\"Show Main Screen (Clear URL Hash)\"\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\tClose Session\n\t\t\t\t\t\t\t</button>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t</div>\n\t\t\t\t{/if}\n\t\t\t\t{#if appState.error && !connected}\n\t\t\t\t\t<div class=\"selectable mt-2 text-xs text-rose-400\">\n\t\t\t\t\t\t{appState.error}\n\t\t\t\t\t</div>\n\t\t\t\t{/if}\n\t\t\t</div>\n\n\t\t\t<!-- Sidebar navigation: switch between the main list and the read-only page -->\n\t\t\t<div class=\"border-b border-brand-border/50 px-2 py-1.5\">\n\t\t\t\t{#if sessionView === 'main'}\n\t\t\t\t\t{#if assistantActive}\n\t\t\t\t\t\t<button\n\t\t\t\t\t\t\tonclick={() => {\n\t\t\t\t\t\t\t\topenAssistant();\n\t\t\t\t\t\t\t\tsidebarOpen = false;\n\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\tdisabled={!connected}\n\t\t\t\t\t\t\tclass=\"flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-xs transition-colors hover:bg-brand-surface-3/50 hover:text-brand-text disabled:opacity-50 {viewingAssistant\n\t\t\t\t\t\t\t\t? 'font-semibold text-brand-blue'\n\t\t\t\t\t\t\t\t: 'text-brand-text-muted'}\"\n\t\t\t\t\t\t\ttitle={$assistantStatusStore.timezone\n\t\t\t\t\t\t\t\t? `Open the current assistant session (your timezone: ${$assistantStatusStore.timezone})`\n\t\t\t\t\t\t\t\t: 'Open the current assistant session'}\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t<span>🧭</span>\n\t\t\t\t\t\t\t<span>Assistant</span>\n\t\t\t\t\t\t\t{#if $assistantStatusStore.timezone}\n\t\t\t\t\t\t\t\t<span\n\t\t\t\t\t\t\t\t\tclass=\"ml-auto truncate text-[10px] font-normal text-brand-text-muted\"\n\t\t\t\t\t\t\t\t\t>{$assistantStatusStore.timezone}</span\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t\t<span class={$assistantStatusStore.timezone ? '' : 'ml-auto'}\n\t\t\t\t\t\t\t\t>→</span\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t</button>\n\t\t\t\t\t{/if}\n\t\t\t\t\t<button\n\t\t\t\t\t\tonclick={() => openSearch(false)}\n\t\t\t\t\t\tclass=\"flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-xs text-brand-text-muted transition-colors hover:bg-brand-surface-3/50 hover:text-brand-text\"\n\t\t\t\t\t\ttitle=\"Search everything ever said in any session\"\n\t\t\t\t\t>\n\t\t\t\t\t\t<span>🔎</span>\n\t\t\t\t\t\t<span>Search conversations</span>\n\t\t\t\t\t\t<span class=\"ml-auto\">→</span>\n\t\t\t\t\t</button>\n\t\t\t\t\t<button\n\t\t\t\t\t\tonclick={() => {\n\t\t\t\t\t\t\tsessionView = 'readonly';\n\t\t\t\t\t\t\tfetchReadOnlySessions();\n\t\t\t\t\t\t}}\n\t\t\t\t\t\tclass=\"flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-xs text-brand-text-muted transition-colors hover:bg-brand-surface-3/50 hover:text-brand-text\"\n\t\t\t\t\t\ttitle=\"View read-only sessions (e.g. autonomous agent fleets)\"\n\t\t\t\t\t>\n\t\t\t\t\t\t<span>👁️</span>\n\t\t\t\t\t\t<span>Read-only sessions</span>\n\t\t\t\t\t\t<span class=\"ml-auto\">→</span>\n\t\t\t\t\t</button>\n\t\t\t\t{:else if sessionView === 'search'}\n\t\t\t\t\t<button\n\t\t\t\t\t\tonclick={() => (sessionView = searchReadOnly ? 'readonly' : 'main')}\n\t\t\t\t\t\tclass=\"flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-xs font-semibold text-brand-blue transition-colors hover:bg-brand-surface-3/50\"\n\t\t\t\t\t\ttitle=\"Back to the session list\"\n\t\t\t\t\t>\n\t\t\t\t\t\t<span>←</span>\n\t\t\t\t\t\t<span\n\t\t\t\t\t\t\t>Back to {searchReadOnly\n\t\t\t\t\t\t\t\t? 'read-only sessions'\n\t\t\t\t\t\t\t\t: 'sessions'}</span\n\t\t\t\t\t\t>\n\t\t\t\t\t</button>\n\t\t\t\t{:else}\n\t\t\t\t\t<button\n\t\t\t\t\t\tonclick={() => (sessionView = 'main')}\n\t\t\t\t\t\tclass=\"flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-xs font-semibold text-brand-blue transition-colors hover:bg-brand-surface-3/50\"\n\t\t\t\t\t\ttitle=\"Back to your sessions\"\n\t\t\t\t\t>\n\t\t\t\t\t\t<span>←</span>\n\t\t\t\t\t\t<span>Back to sessions</span>\n\t\t\t\t\t</button>\n\t\t\t\t\t<button\n\t\t\t\t\t\tonclick={() => openSearch(true)}\n\t\t\t\t\t\tclass=\"flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-xs text-brand-text-muted transition-colors hover:bg-brand-surface-3/50 hover:text-brand-text\"\n\t\t\t\t\t\ttitle=\"Search the read-only conversations\"\n\t\t\t\t\t>\n\t\t\t\t\t\t<span>🔎</span>\n\t\t\t\t\t\t<span>Search these conversations</span>\n\t\t\t\t\t\t<span class=\"ml-auto\">→</span>\n\t\t\t\t\t</button>\n\t\t\t\t{/if}\n\t\t\t</div>\n\n\t\t\t<!-- Session Browser -->\n\t\t\t<div class=\"flex-1 overflow-hidden\">\n\t\t\t\t{#if sessionView === 'search'}\n\t\t\t\t\t<!-- onOpened closes the mobile sidebar even when the tapped result is\n\t\t\t\t\t the session already open: that path starts no load, so the\n\t\t\t\t\t loading/resync effect below would never fire for it. -->\n\t\t\t\t\t<ConversationSearch\n\t\t\t\t\t\treadOnly={searchReadOnly}\n\t\t\t\t\t\tinitialQuery={searchInitialQuery}\n\t\t\t\t\t\tonOpened={() => (sidebarOpen = false)}\n\t\t\t\t\t/>\n\t\t\t\t{:else if sessionView === 'readonly'}\n\t\t\t\t\t<SessionBrowser readOnly onSearchAll={(q) => openSearch(true, q)} />\n\t\t\t\t{:else}\n\t\t\t\t\t<SessionBrowser onSearchAll={(q) => openSearch(false, q)} />\n\t\t\t\t{/if}\n\t\t\t</div>\n\t\t{/if}\n\t</div>\n\n\t<!-- Main content -->\n\t<div class=\"flex min-w-0 flex-1 flex-col\">\n\t\t<!-- Top bar -->\n\t\t<div\n\t\t\tclass=\"app-chrome flex items-center gap-3 border-b border-brand-border bg-brand-surface p-3\"\n\t\t>\n\t\t\t<button\n\t\t\t\tonclick={() => (sidebarOpen = !sidebarOpen)}\n\t\t\t\tclass=\"p-1 text-brand-text-muted hover:text-brand-text md:hidden\"\n\t\t\t>\n\t\t\t\t=\n\t\t\t</button>\n\n\t\t\t<!-- Compact search affordance (active-session case): drop to the search\n\t\t\t empty-state. Hidden in the empty-state itself, where the bottom\n\t\t\t composer already IS the search input. -->\n\t\t\t{#if connected && searchFolder && sessionInfo.sessionFile}\n\t\t\t\t<button\n\t\t\t\t\ttype=\"button\"\n\t\t\t\t\tonclick={startSearch}\n\t\t\t\t\tclass=\"flex flex-shrink-0 items-center justify-center rounded border border-brand-border bg-brand-surface-2 px-2.5 py-1.5 text-sm text-brand-text-muted transition-colors hover:bg-brand-surface-3 hover:text-brand-text\"\n\t\t\t\t\ttitle=\"Search the web\"\n\t\t\t\t\taria-label=\"Search the web\"\n\t\t\t\t>\n\t\t\t\t\t🔍\n\t\t\t\t</button>\n\t\t\t{/if}\n\n\t\t\t<!-- Status indicator -->\n\t\t\t{#if !connected || !sessionInfo.sessionFile}\n\t\t\t\t<div class=\"flex min-w-0 items-center gap-2\">\n\t\t\t\t\t{#if connected && searchActive}\n\t\t\t\t\t\t<span class=\"text-sm text-brand-text-muted\"\n\t\t\t\t\t\t\t>Search the web below, or pick a session from the sidebar</span\n\t\t\t\t\t\t>\n\t\t\t\t\t{:else if connected}\n\t\t\t\t\t\t<span class=\"text-sm text-brand-text-muted\"\n\t\t\t\t\t\t\t>Select a session from sidebar</span\n\t\t\t\t\t\t>\n\t\t\t\t\t{:else}\n\t\t\t\t\t\t<span class=\"text-sm text-brand-text-muted\">Not connected</span>\n\t\t\t\t\t{/if}\n\t\t\t\t</div>\n\t\t\t{/if}\n\n\t\t\t<!-- Folder and model info -->\n\t\t\t{#if sessionInfo.sessionFile}\n\t\t\t\t<div class=\"flex min-w-0 flex-1 items-center gap-3\">\n\t\t\t\t\t<!-- Folder -->\n\t\t\t\t\t{#if sessionInfo.cwd}\n\t\t\t\t\t\t<div\n\t\t\t\t\t\t\tclass=\"flex min-w-0 items-center gap-1.5 text-xs text-brand-text-muted\"\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t<span class=\"flex-shrink-0\">📁</span>\n\t\t\t\t\t\t\t<span class=\"truncate\" title={sessionInfo.cwd}\n\t\t\t\t\t\t\t\t>{sessionInfo.cwd.split('/').pop() || sessionInfo.cwd}</span\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t{/if}\n\n\t\t\t\t\t<!-- Model selector -->\n\t\t\t\t\t{#if sessionInfo.model}\n\t\t\t\t\t\t<div class=\"flex min-w-0 items-center gap-1.5 text-xs\">\n\t\t\t\t\t\t\t<span\n\t\t\t\t\t\t\t\tclass=\"relative flex flex-shrink-0 items-center justify-center text-sm\"\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t<span>🤖</span>\n\t\t\t\t\t\t\t\t<span\n\t\t\t\t\t\t\t\t\tclass=\"absolute -right-0.5 -bottom-0.5 h-2 w-2 rounded-full border border-brand-surface {appState.isStreaming\n\t\t\t\t\t\t\t\t\t\t? 'animate-pulse bg-orange-500'\n\t\t\t\t\t\t\t\t\t\t: 'bg-emerald-500'}\"\n\t\t\t\t\t\t\t\t\ttitle={appState.isStreaming ? 'Agent working...' : 'Ready'}\n\t\t\t\t\t\t\t\t></span>\n\t\t\t\t\t\t\t</span>\n\t\t\t\t\t\t\t{#if models.length > 0 && !readOnly}\n\t\t\t\t\t\t\t\t<select\n\t\t\t\t\t\t\t\t\tvalue={sessionInfo.model}\n\t\t\t\t\t\t\t\t\toninput={(e) => changeModel(e.currentTarget.value)}\n\t\t\t\t\t\t\t\t\tclass=\"max-w-48 truncate rounded border border-brand-border bg-brand-surface-2 px-1.5 py-0.5 text-brand-text focus:border-brand-blue focus:outline-none\"\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t{#each models as model}\n\t\t\t\t\t\t\t\t\t\t<option value={`${model.provider}:${model.modelId}`}>\n\t\t\t\t\t\t\t\t\t\t\t{model.label}\n\t\t\t\t\t\t\t\t\t\t</option>\n\t\t\t\t\t\t\t\t\t{/each}\n\t\t\t\t\t\t\t\t</select>\n\t\t\t\t\t\t\t{:else}\n\t\t\t\t\t\t\t\t<span\n\t\t\t\t\t\t\t\t\tclass=\"truncate text-brand-text-muted\"\n\t\t\t\t\t\t\t\t\ttitle={sessionInfo.model}>{sessionInfo.model}</span\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t</div>\n\t\t\t\t\t{/if}\n\t\t\t\t</div>\n\t\t\t{/if}\n\n\t\t\t<!-- Reset the assistant: a fresh session in its folder becomes current\n\t\t\t (the old turn is aborted, its queue cleared). The folder is the\n\t\t\t memory, so this is cheap. Same effect as /new or /reset here. -->\n\t\t\t{#if connected && viewingAssistant}\n\t\t\t\t<button\n\t\t\t\t\ttype=\"button\"\n\t\t\t\t\tonclick={resetAssistant}\n\t\t\t\t\tclass=\"flex flex-shrink-0 items-center justify-center rounded border border-brand-border bg-brand-surface-2 px-2 py-1 text-xs text-brand-text-muted transition-colors hover:bg-brand-surface-3 hover:text-brand-text\"\n\t\t\t\t\ttitle=\"Reset the assistant: start a fresh session (its memory lives in its folder)\"\n\t\t\t\t\taria-label=\"Reset the assistant\"\n\t\t\t\t>\n\t\t\t\t\t↺ Reset\n\t\t\t\t</button>\n\t\t\t{/if}\n\n\t\t\t<!-- Star the open session: \"come back to this\". The natural moment is\n\t\t\t right after this session hands a prompt to a new one, which will take\n\t\t\t the top of the list. The star also shows on the session's sidebar row. -->\n\t\t\t{#if sessionInfo.sessionFile}\n\t\t\t\t<button\n\t\t\t\t\ttype=\"button\"\n\t\t\t\t\tonclick={() =>\n\t\t\t\t\t\tsetSessionStarred(sessionInfo.sessionFile!, !currentStarred).catch(\n\t\t\t\t\t\t\t() => {},\n\t\t\t\t\t\t)}\n\t\t\t\t\tclass=\"flex flex-shrink-0 items-center justify-center rounded border px-2 py-1 text-sm transition-colors {currentStarred\n\t\t\t\t\t\t? 'border-amber-400/50 bg-amber-400/10 text-amber-400 hover:bg-amber-400/20'\n\t\t\t\t\t\t: 'border-brand-border bg-brand-surface-2 text-brand-text-muted hover:bg-brand-surface-3 hover:text-amber-400'}\"\n\t\t\t\t\ttitle={currentStarred\n\t\t\t\t\t\t? 'Starred. Click to unstar.'\n\t\t\t\t\t\t: 'Star this session to come back to it later'}\n\t\t\t\t\taria-label={currentStarred ? 'Unstar session' : 'Star session'}\n\t\t\t\t\taria-pressed={currentStarred}\n\t\t\t\t>\n\t\t\t\t\t{currentStarred ? '★' : '☆'}\n\t\t\t\t</button>\n\t\t\t{/if}\n\n\t\t\t{#if readOnly}\n\t\t\t\t<span\n\t\t\t\t\tclass=\"flex-shrink-0 rounded bg-yellow-500/20 px-2 py-1 text-xs text-yellow-400\"\n\t\t\t\t\t>Read-only</span\n\t\t\t\t>\n\t\t\t{/if}\n\t\t</div>\n\n\t\t<!-- Interruption notification -->\n\t\t{#if interrupted}\n\t\t\t<div\n\t\t\t\tclass=\"border border-red-500/30 bg-red-500/10 px-4 py-2 text-center text-sm text-rose-400\"\n\t\t\t>\n\t\t\t\tYour session was interrupted — another client took over.\n\t\t\t</div>\n\t\t{/if}\n\n\t\t<!-- Session notice (non-fatal). e.g. a CLI took over this session while it\n\t\t was mid-turn here, discarding the in-flight tool call or streaming\n\t\t reply. The session stays attached; the user just needs to know why the\n\t\t running turn stopped. Dismissible. -->\n\t\t{#if notice}\n\t\t\t<div\n\t\t\t\tclass=\"flex items-start justify-between gap-2 border px-4 py-2 text-sm {notice.level ===\n\t\t\t\t'warning'\n\t\t\t\t\t? 'border-yellow-500/30 bg-yellow-500/10 text-yellow-400'\n\t\t\t\t\t: 'border-blue-500/30 bg-blue-500/10 text-blue-400'}\"\n\t\t\t>\n\t\t\t\t<span class=\"min-w-0 flex-1 break-words whitespace-pre-wrap\"\n\t\t\t\t\t>{notice.message}</span\n\t\t\t\t>\n\t\t\t\t<button\n\t\t\t\t\tonclick={() => dismissNotice()}\n\t\t\t\t\taria-label=\"Dismiss notice\"\n\t\t\t\t\tclass=\"flex-shrink-0 opacity-80 hover:opacity-100\">X</button\n\t\t\t\t>\n\t\t\t</div>\n\t\t{/if}\n\n\t\t<!-- Folder-conflict warning banner. Shown while ANOTHER active session\n\t\t exists in this session's folder. Before the user continues, the\n\t\t composer is read-only and the banner offers \"Continue anyway\" (which\n\t\t enables sending WITHOUT aborting the other session). After continuing,\n\t\t the button is gone but the banner stays as a passive warning until the\n\t\t other session leaves the folder (folderConflict cleared by the server). -->\n\t\t{#if fConflict?.active}\n\t\t\t<div\n\t\t\t\tclass=\"flex items-center justify-between gap-3 border border-yellow-500/30 bg-yellow-500/10 px-4 py-2 text-sm text-yellow-400\"\n\t\t\t>\n\t\t\t\t<span class=\"min-w-0 flex-1 break-words\">\n\t\t\t\t\t⚠️ Another client is active in this folder.\n\t\t\t\t\t{#if fConflict.continued}\n\t\t\t\t\t\tYou are both working in it &mdash; changes may conflict.\n\t\t\t\t\t{:else}\n\t\t\t\t\t\tYou are observing (read-only) to avoid clashing.\n\t\t\t\t\t{/if}\n\t\t\t\t</span>\n\t\t\t\t{#if !fConflict.continued}\n\t\t\t\t\t<button\n\t\t\t\t\t\tonclick={() => continueFolderConflict()}\n\t\t\t\t\t\tclass=\"flex-shrink-0 rounded-md border border-yellow-500/40 bg-yellow-500/20 px-3 py-1 text-xs font-medium text-yellow-300 transition-colors hover:bg-yellow-500/30\"\n\t\t\t\t\t\t>Continue anyway</button\n\t\t\t\t\t>\n\t\t\t\t{/if}\n\t\t\t</div>\n\t\t{/if}\n\n\t\t<!-- Session error notification. The message can be long, so it scrolls\n\t\t within a bounded, wrapping area while the close button stays pinned and\n\t\t never gets pushed off-screen. -->\n\t\t{#if sError}\n\t\t\t<div\n\t\t\t\tclass=\"flex items-start justify-between gap-2 border border-red-500/30 bg-red-500/10 px-4 py-2 text-sm text-rose-400\"\n\t\t\t>\n\t\t\t\t<span\n\t\t\t\t\tclass=\"max-h-24 min-w-0 flex-1 overflow-y-auto break-words whitespace-pre-wrap\"\n\t\t\t\t\t>{sError}</span\n\t\t\t\t>\n\t\t\t\t<button\n\t\t\t\t\tonclick={() => dismissSessionError()}\n\t\t\t\t\taria-label=\"Dismiss error\"\n\t\t\t\t\tclass=\"flex-shrink-0 text-rose-300 hover:text-rose-200\">X</button\n\t\t\t\t>\n\t\t\t</div>\n\t\t{/if}\n\n\t\t<!-- Read-only banner. Suppressed only while the DISMISSIBLE folder-conflict\n\t\t banner is up: that one already explains why this session is read-only and\n\t\t carries the \"Continue anyway\" escape, so showing both reads as a dead end.\n\t\t Once continued, the conflict banner has no button left, so a read-only\n\t\t that SURVIVED the continue (a hard sessions.readOnly folder, which the\n\t\t server refuses to lift) must still explain itself here. -->\n\t\t{#if readOnly && !interrupted && !fMissing && !(fConflict?.active && !fConflict.continued)}\n\t\t\t<div\n\t\t\t\tclass=\"border border-yellow-500/30 bg-yellow-500/10 px-4 py-2 text-center text-sm text-yellow-400\"\n\t\t\t>\n\t\t\t\tRead-only: this session cannot be driven from here\n\t\t\t</div>\n\t\t{/if}\n\n\t\t<!-- Chat area -->\n\t\t<ChatMessageList bind:this={chatList} onMessageSent={() => {}} />\n\n\t\t<!-- Input: one composer, mode-switched. Search mode when connected, a\n\t\t search folder is configured, and no session is active; chat mode\n\t\t otherwise. Always mounted so it can be focused inside a tap gesture.\n\t\t EXCEPTION: a read-only session (e.g. a sessions.readOnly fleet folder)\n\t\t hides the composer entirely -- it is an observe-only view. -->\n\t\t{#if fMissing}\n\t\t\t<!-- MISSING FOLDER: this session's working folder is not usable on this\n\t\t\t machine -- it does not exist (the transcript synced, the clone did\n\t\t\t not), or a restore is still materialising it. The conversation above\n\t\t\t is fully readable, but the server built no agent and refuses every\n\t\t\t send, so the composer is replaced by the RESTORE PANEL: the missing\n\t\t\t path, an editable pre-filled URL, and the clone with live progress,\n\t\t\t ending in a reload that brings the session back live. There is\n\t\t\t deliberately no dismiss: unlike the folder conflict this is not a\n\t\t\t warning, it is the absence of the folder. -->\n\t\t\t<RestorePanel />\n\t\t{:else if readOnly && sessionInfo.sessionFile}\n\t\t\t<div\n\t\t\t\tclass=\"border-t border-brand-border bg-brand-surface px-4 py-3 text-center text-xs text-brand-text-muted\"\n\t\t\t>\n\t\t\t\t👁️ Read-only session, observing only, no input.\n\t\t\t</div>\n\t\t{:else}\n\t\t\t<!-- Suspended/reconnecting: show a thin status banner ABOVE the composer\n\t\t\t instead of replacing it. Keeping ChatInput mounted preserves the\n\t\t\t textarea (and any in-progress draft) in the live DOM so a resync can\n\t\t\t never destroy what the user was typing. The composer stays EDITABLE\n\t\t\t (type, attach; uploads wait for the socket): only SENDING is blocked\n\t\t\t (sendDisabled) until the socket is back and the session has resynced. -->\n\t\t\t{#if sessionInfo.sessionFile && (resyncing || !connected)}\n\t\t\t\t<div\n\t\t\t\t\tclass=\"flex items-center justify-center gap-2 border-t border-brand-border bg-brand-surface px-4 py-2 text-center text-sm text-brand-text-muted\"\n\t\t\t\t>\n\t\t\t\t\t<span\n\t\t\t\t\t\tclass=\"h-3.5 w-3.5 animate-spin rounded-full border-2 border-brand-blue border-t-transparent\"\n\t\t\t\t\t></span>\n\t\t\t\t\t<span>Reconnecting and syncing session...</span>\n\t\t\t\t</div>\n\t\t\t{:else if sessionInfo.sessionFile && agentPending}\n\t\t\t\t<!-- Fast-first load: the conversation is already readable above, but the\n\t\t\t\t live agent is still building (cold session). Block only the\n\t\t\t\t composer, with a distinct hint, so reading/scrolling stay instant. -->\n\t\t\t\t<div\n\t\t\t\t\tclass=\"flex items-center justify-center gap-2 border-t border-brand-border bg-brand-surface px-4 py-2 text-center text-sm text-brand-text-muted\"\n\t\t\t\t>\n\t\t\t\t\t<span\n\t\t\t\t\t\tclass=\"h-3.5 w-3.5 animate-spin rounded-full border-2 border-brand-blue border-t-transparent\"\n\t\t\t\t\t></span>\n\t\t\t\t\t<span>Preparing the session agent...</span>\n\t\t\t\t</div>\n\t\t\t{/if}\n\t\t\t<ChatInput\n\t\t\t\tbind:this={chatInput}\n\t\t\t\tsearchMode={searchActive}\n\t\t\t\tsearchConfigured={!!searchFolder}\n\t\t\t\t{searchModels}\n\t\t\t\tbind:searchModel\n\t\t\t\tonSubmit={(q, files) => runSearch(q, searchModel, files)}\n\t\t\t\tplaceholder=\"Search the web...\"\n\t\t\t\tsubmitLabel=\"Search\"\n\t\t\t\tdisabled={searchActive\n\t\t\t\t\t? !connected\n\t\t\t\t\t: readOnly || !sessionInfo.sessionFile}\n\t\t\t\tsendDisabled={!searchActive &&\n\t\t\t\t\t(!connected || resyncing || agentPending)}\n\t\t\t\tonSend={() => chatList?.forceScrollToBottom()}\n\t\t\t/>\n\t\t{/if}\n\t</div>\n\n\t<!-- Sudo password prompt for `!sudo ...` commands -->\n\t<SudoPasswordDialog />\n\n\t<!-- Overlay for mobile sidebar -->\n\t{#if sidebarOpen}\n\t\t<button\n\t\t\ttype=\"button\"\n\t\t\tclass=\"fixed inset-0 z-10 bg-brand-dark/50 md:hidden\"\n\t\t\tonclick={() => (sidebarOpen = false)}\n\t\t\taria-label=\"Close sidebar\"\n\t\t></button>\n\t{/if}\n</div>\n"],"file":"2.D_6BVhWL.js"}