limixbot 0.3.116 → 0.3.118

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 (56) hide show
  1. package/dist/assets/{ActivityPanel-CPyIoUmY.js → ActivityPanel-D0KzaLSM.js} +1 -1
  2. package/dist/assets/{App-D_fqRJhk.js → App-zFyDHpWG.js} +127 -127
  3. package/dist/assets/{AppEventEditor-DTYGJT1f.js → AppEventEditor-sHziWn3v.js} +1 -1
  4. package/dist/assets/{BotSettingsDialog-De6r2yvR.js → BotSettingsDialog-BurY3EqJ.js} +1 -1
  5. package/dist/assets/{BrowserPanel-abUgbX2z.js → BrowserPanel-BWaLYZKx.js} +1 -1
  6. package/dist/assets/{BrowserProfilesManager-IuxTSnih.js → BrowserProfilesManager-CdIpBHTc.js} +1 -1
  7. package/dist/assets/{CloudAddDialog-C8OGeyq3.js → CloudAddDialog-CB8wDxwp.js} +1 -1
  8. package/dist/assets/{ComputerFilesPane-BCaN6XSL.js → ComputerFilesPane-BzE_KXPA.js} +1 -1
  9. package/dist/assets/ComputerPanel-ChCzmSlC.js +2 -0
  10. package/dist/assets/{DataPanel-X1VUpw1U.js → DataPanel-7we9c7pu.js} +1 -1
  11. package/dist/assets/{GrokMoveDialog-D-z86fT9.js → GrokMoveDialog-DhexplQR.js} +1 -1
  12. package/dist/assets/{InspectorPanel-DbJq2m5L.js → InspectorPanel-BPYilEJU.js} +1 -1
  13. package/dist/assets/{KeyboardShortcutsModal-DYTFL_aJ.js → KeyboardShortcutsModal-CQQ6KV0K.js} +1 -1
  14. package/dist/assets/{LimixResizeHandles-DLDtm0nE.js → LimixResizeHandles-BDK9cm0J.js} +1 -1
  15. package/dist/assets/{LiveDesktop-B8KndeA2.js → LiveDesktop-CGM59sts.js} +1 -1
  16. package/dist/assets/{LocalVmWorkspace-B2V9D2cJ.js → LocalVmWorkspace--AY6YKvR.js} +1 -1
  17. package/dist/assets/{MacLocalControl-6LKkmAKt.js → MacLocalControl-D8kvLy1b.js} +1 -1
  18. package/dist/assets/{MarkdownFilePreview-BCxhBtBJ.js → MarkdownFilePreview-DawkE0MD.js} +1 -1
  19. package/dist/assets/{NewBotDialog-o7l4HJW-.js → NewBotDialog-DdxqTnNw.js} +1 -1
  20. package/dist/assets/{PhoneAppDialog-C4mtXK2o.js → PhoneAppDialog-MCSHv0Yl.js} +1 -1
  21. package/dist/assets/{PluginsPanel-D-4XAvSO.js → PluginsPanel-Cy9ntn3B.js} +1 -1
  22. package/dist/assets/{ProIntroduction-BBpRtakG.js → ProIntroduction-B5jCzDs1.js} +1 -1
  23. package/dist/assets/{RemoteAgentSettingsPanel-Ce3lFnoM.js → RemoteAgentSettingsPanel-Dntwp988.js} +1 -1
  24. package/dist/assets/{RoomPanel-CtqyNeOi.js → RoomPanel-B9SDwPbf.js} +1 -1
  25. package/dist/assets/{RoutinesPage-D9VQa8Id.js → RoutinesPage-o4aF8_qs.js} +1 -1
  26. package/dist/assets/SettingsModal-CGTUsDfy.js +19 -0
  27. package/dist/assets/{ShareTeamDialog-CDAXGizM.js → ShareTeamDialog-B6EYRWvu.js} +1 -1
  28. package/dist/assets/{SignedInSites-B9tzCm-B.js → SignedInSites-DKeE15y0.js} +1 -1
  29. package/dist/assets/{TeamLibraryPanel-CU39m2wr.js → TeamLibraryPanel-Df5k1HgV.js} +1 -1
  30. package/dist/assets/{TeamMapPage-kKb_yOAX.js → TeamMapPage-Ba07EWOq.js} +1 -1
  31. package/dist/assets/{TriggersPage-DRuKK0G6.js → TriggersPage-BFpVZd69.js} +1 -1
  32. package/dist/assets/{VisibilitySection-B-4LSDjd.js → VisibilitySection-DDK6CG0T.js} +1 -1
  33. package/dist/assets/{WebhookTrigger-rBYKz_RM.js → WebhookTrigger-Bj8V3yyI.js} +1 -1
  34. package/dist/assets/{WorksOnGrid-DCpYS0ZD.js → WorksOnGrid-CJdNJU6D.js} +1 -1
  35. package/dist/assets/{core-PnDBcOH3.js → core-CRuI-yVu.js} +1 -1
  36. package/dist/assets/{import-name-BSWA4Waq.js → import-name-C-HWHnM2.js} +1 -1
  37. package/dist/assets/{index-CD6r_oet.js → index-CjtChfAw.js} +2 -2
  38. package/dist/assets/{index-CRS8Hcp2.js → index-CzF2QuHP.js} +1 -1
  39. package/dist/assets/{mcp-servers-6KR1t77y.js → mcp-servers-UAcu8HOu.js} +1 -1
  40. package/dist/assets/{new-bot-Dapj-7yH.js → new-bot-wl6Y52Eh.js} +1 -1
  41. package/dist/assets/{org-library-Q_EDTsK1.js → org-library-DjAEblry.js} +1 -1
  42. package/dist/assets/{package-format-G8_Vezo4.js → package-format-n9juk_T9.js} +1 -1
  43. package/dist/assets/{remote-desktop-panel-CaJgKj1v.js → remote-desktop-panel-CMiAx-v8.js} +1 -1
  44. package/dist/index.html +1 -1
  45. package/dist-server/index.js +42 -39
  46. package/dist-server/limixbot.js +17 -16
  47. package/dist-server/package.json +1 -1
  48. package/dist-server/pair-cli.js +17 -16
  49. package/dist-server/server/browser/chrome/launcher.js +23 -6
  50. package/dist-server/server/host/browser.js +8 -3
  51. package/dist-server/server/workspace-backup-policy.js +18 -1
  52. package/dist-server/server/workspace-backup.js +6 -4
  53. package/dist-server/workspace-backup.worker.js +29 -29
  54. package/package.json +1 -1
  55. package/dist/assets/ComputerPanel-LPwMftDF.js +0 -2
  56. package/dist/assets/SettingsModal-D1thqDC-.js +0 -19
@@ -217,11 +217,11 @@ ne Chief of Staff. Change the Chief before moving this bot.","serverError.depart
217
217
  .bot.viewOnly":"You can view {bot}, not chat with it.","serverError.secret.mailboxAlreadyConnected":"this mailbox was already connected","serverError.secret.emailAndPassword":"Enter your email address and its password.","serverError.secret.emailUnavailable":"Email can't be connected here.","serverError.mailbox.adminOnly":"Only the owner or an admin can manage the mailboxes.","serverError.mailbox.addressAndPassword":"Enter your email address and password.","serverError.mailbox.outgoingFields":"Ch\
218
218
  eck the outgoing server: a name like mail.example.com, a port from 1 to 65535, and SSL/TLS or STARTTLS.","serverError.voice.fishKeyRequired":"Add a Fish Audio key in Settings \u2192 API keys to talk to your bots here.","serverError.voice.fishTranscribeConnection":"Couldn't reach Fish Audio to hear you \u2014 check your connection.","serverError.file.tooLarge":"This file is {size}, over the {limit} limit for opening files from chat. The file itself is still saved as {name}."};function userError(key,params){
219
219
  let safe=params&&redactParams(params);return{error:formatServerText(USER_ERROR[key],safe),errorKey:key,...safe?{errorParams:safe}:{}}}function userErrorThrown(key,params){let{error:error62,...fields}=userError(key,params);return Object.assign(new Error(error62),fields)}function userErrorFields(value){let{errorKey,errorParams}=Object(value);if(typeof errorKey!="string"||!Object.hasOwn(USER_ERROR,errorKey))return{};let params=errorParams&&typeof errorParams=="object"&&!Array.isArray(errorParams)?redactParams(
220
- errorParams):void 0;return{errorKey,...params?{errorParams:params}:{}}}import{createHash,timingSafeEqual}from"node:crypto";function transferAccountHash(id2){if(typeof id2!="string"||!/^limix:[a-z0-9._-]{1,64}$/.test(id2))throw new Error("H\xE3y \u0111\u0103ng nh\u1EADp t\xE0i kho\u1EA3n Limix tr\u01B0\u1EDBc khi chuy\u1EC3n m\xE1y Offline.");return createHash("sha256").update(`limix-offline-transfer-v1:${id2}`).digest("hex")}import{createCipheriv,createDecipheriv,createHash as createHash3,randomBytes,randomUUID as randomUUID2,scrypt}from"node:crypto";import{chmodSync,closeSync as closeSync3,constants as constants2,cpSync,createReadStream,createWriteStream,existsSync as existsSync3,fstatSync as fstatSync3,fsyncSync as fsyncSync2,lstatSync as lstatSync2,mkdirSync as mkdirSync2,openSync as openSync3,readFileSync as readFileSync5,readdirSync as readdirSync3,readSync as readSync2,realpathSync,renameSync as renameSync4,rmSync as rmSync2,
220
+ errorParams):void 0;return{errorKey,...params?{errorParams:params}:{}}}import{createHash,timingSafeEqual}from"node:crypto";function transferAccountHash(id2){if(typeof id2!="string"||!/^limix:[a-z0-9._-]{1,64}$/.test(id2))throw new Error("H\xE3y \u0111\u0103ng nh\u1EADp t\xE0i kho\u1EA3n Limix tr\u01B0\u1EDBc khi chuy\u1EC3n m\xE1y Offline.");return createHash("sha256").update(`limix-offline-transfer-v1:${id2}`).digest("hex")}import{createCipheriv,createDecipheriv,createHash as createHash3,randomBytes,randomUUID as randomUUID2,scrypt}from"node:crypto";import{chmodSync,closeSync as closeSync3,constants as constants2,cpSync,createReadStream,createWriteStream,existsSync as existsSync3,fstatSync as fstatSync3,fsyncSync as fsyncSync2,lstatSync as lstatSync3,mkdirSync as mkdirSync2,openSync as openSync3,readFileSync as readFileSync5,readdirSync as readdirSync3,readSync as readSync2,realpathSync,renameSync as renameSync4,rmSync as rmSync2,
221
221
  writeFileSync as writeFileSync2,writeSync as writeSync2}from"node:fs";import{isAbsolute as isAbsolute3,join as join13,parse as parse3,posix,relative as relative2,resolve as resolve2,sep,win32}from"node:path";import{homedir as homedir2}from"node:os";import{backup,DatabaseSync as DatabaseSync3}from"node:sqlite";import{pipeline}from"node:stream/promises";import{randomUUID}from"node:crypto";import{closeSync,constants,fstatSync,fsyncSync,lstatSync,openSync,readFileSync,renameSync,unlinkSync,writeFileSync}from"node:fs";var RENAME_RETRY_DELAYS_MS=[5,10,20,40,80],RETRYABLE_RENAME_CODES=new Set(["EPERM","EACCES","EBUSY"]);function sleepSync(ms2){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,ms2)}function renameWithRetry(tmp,path,rename=renameSync){for(let attempt=0;;attempt+=1)try{rename(tmp,path);return}catch(e){let code=e.code;if(!code||
222
222
  !RETRYABLE_RENAME_CODES.has(code)||attempt>=RENAME_RETRY_DELAYS_MS.length)throw e;sleepSync(RENAME_RETRY_DELAYS_MS[attempt])}}function writeFileAtomic(path,data,options2={}){let tmp=`${path}.${process.pid}.${randomUUID()}.tmp`,fd=null;try{fd=openSync(tmp,"w",options2.mode),writeFileSync(fd,data),options2.durable!==!1&&fsyncSync(fd),closeSync(fd),fd=null,renameWithRetry(tmp,path)}catch(e){if(fd!==null)try{closeSync(fd)}catch{}try{unlinkSync(tmp)}catch{}throw e}}var WORKSPACE_BACKUP_CLIENT_KEYS=["omb-drafts","omb-draft-attachments","omb-draft-send-ids","omb-draft-channel-modes","omb-skin","omb-show-threads","omb-show-run-card","omb-send-key","omb-color-user-bubbles","omb-chat-width","openmausbot.sidebarDensity","openmausbot.sidebarToolsLayout","openmausbot.sidebarCollapsedSections.v1","openmausbot.sidebarSectionOrder.v1","omb-analytics-opt-out","openmausbot.remote-voice.v1"];import{isAbsolute,join}from"node:path";var IMAGE_MAX_BYTES=10*1024*1024;var TURN_IMAGE_MAX_BYTES=4*IMAGE_MAX_BYTES;var DOCUMENT_MIMES={txt:"text/plain",md:"text/markdown",markdown:"text/markdown",csv:"text/csv",tsv:"text/tab-separated-values",json:"application/json",pdf:"application/pdf",rtf:"application/rtf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presenta\
223
223
  tionml.presentation",odt:"application/vnd.oasis.opendocument.text",ods:"application/vnd.oasis.opendocument.spreadsheet",odp:"application/vnd.oasis.opendocument.presentation",xmind:"application/vnd.xmind.workbook"},ACCEPTED_DOCUMENT_MIMES=new Set(Object.values(DOCUMENT_MIMES)),AUDIO_MIMES_BY_EXTENSION={opus:"audio/opus",ogg:"audio/ogg",mp3:"audio/mpeg",m4a:"audio/mp4",aac:"audio/aac",wav:"audio/wav",flac:"audio/flac",webm:"audio/webm"};var ACCEPTED_AUDIO_MIMES=new Set([...Object.values(AUDIO_MIMES_BY_EXTENSION),"audio/x-m4a","audio/x-wav","audio/wave","audio/x-flac"]);var INLINE_DROP_LIMIT=512*1024;var COMMONMARK_BLOCK_TAGS=["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","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"].join("|");var COMMONMARK_TYPE_6=new RegExp(`^ {0,3}</?(?:${COMMONMARK_BLOCK_TAGS})(?:[\\t ]|/?>|$)`,"i"),HTML_ATTRIBUTE_NAME="[A-Za-z_:][A-Za-z0-9_.:-]*",HTML_ATTRIBUTE_VALUE=`(?:[^\\s"'=<>\\x60]+|'[^']*'|"[^"]*")`,HTML_ATTRIBUTE=`(?:[\\t ]+${HTML_ATTRIBUTE_NAME}(?:[\\t ]*=[\\t ]*${HTML_ATTRIBUTE_VALUE})?)`,COMMONMARK_TYPE_7=new RegExp(`^ {0,3}(?:<[A-Za-z][A-Za-z0-9-]*${HTML_ATTRIBUTE}*[\\t ]*/?>|</[A-Za-z][A-Za-z0-9-]*[\\t ]*>)[\\t ]*$`);function validRelative(path){return!!path&&path.length<=4096&&!isAbsolute(path)&&!/[\\\0:]/.test(path)&&path.split("/").every(part=>!!part&&part!=="."&&part!==".."&&!/[. ]$/.test(part)&&!/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(part))}var CJK="\\p{Script=Han}\\p{Script=Hiragana}\\p{Script=Katakana}",CJK_CHAR=new RegExp(`[${CJK}]`,"u"),HAN=new RegExp("\\p{Script=Han}","u"),CJK_RUNS=new RegExp(`[${CJK}]+|[^${CJK}]+`,"gu"),CJK_BOUNDARY=new RegExp(`(?<=[${CJK}])(?=[\\p{L}\\p{N}])|(?<=[\\p{L}\\p{N}])(?=[${CJK}])`,"gu");var FILLER=new RegExp("\u6211\u4EEC|\u4F60\u4EEC|\u4ED6\u4EEC|\u5979\u4EEC|\u5B83\u4EEC|\u8FD9\u4E2A|\u90A3\u4E2A|\u4E00\u4E0B|\u4E00\u4E2A|\u53EF\u4EE5|\u65F6\u5019|\u73B0\u5728|\u77E5\u9053|\u544A\u8BC9|\u8BB0\u5F97|\u8FD8\u662F|\u5C31\u662F|\u4E0D\u662F|\u6CA1\u6709|\u5DF2\u7ECF|\u56E0\u4E3A|\u6240\u4EE5|\u4F46\u662F|\u5982\u679C|\u7136\u540E|\u8FD8\u6709|\u8BF7\u95EE|\u5E2E\u6211|\u600E\u6837|\u8FD9\u6837|\u90A3\u6837|\u54EA\u91CC|\u54EA\u4E2A|\u5E94\u8BE5|\u4E00\u4E9B|[\u7684\u4E86\u662F\u5417\u5462\u5427\u554A\u5440\u54E6\u55EF\u4E48]",
224
- "gu");import{readlinkSync}from"node:fs";import{dirname,isAbsolute as isAbsolute2,join as join4,relative,resolve}from"node:path";import{readFileSync as readFileSync3,mkdirSync,existsSync,renameSync as renameSync2}from"node:fs";import{mkdtempSync}from"node:fs";import{homedir,tmpdir,userInfo}from"node:os";import{join as join2}from"node:path";var home;function dataHome(){if(home!==void 0)return home;let real=homedir();return home=process.env.VITEST!==void 0&&real===userInfo().homedir?mkdtempSync(join2(tmpdir(),"omb-test-home-")):real,home}import{join as join3}from"node:path";var external_exports={};__export(external_exports,{$brand:()=>$brand,$input:()=>$input,$output:()=>$output,INVALID:()=>INVALID,NEVER:()=>NEVER,TimePrecision:()=>TimePrecision,ZodAny:()=>ZodAny,ZodArray:()=>ZodArray,ZodBase64:()=>ZodBase64,ZodBase64URL:()=>ZodBase64URL,ZodBigInt:()=>ZodBigInt,ZodBigIntFormat:()=>ZodBigIntFormat,ZodBoolean:()=>ZodBoolean,ZodCIDRv4:()=>ZodCIDRv4,ZodCIDRv6:()=>ZodCIDRv6,ZodCUID:()=>ZodCUID,ZodCUID2:()=>ZodCUID2,ZodCatch:()=>ZodCatch,ZodCodec:()=>ZodCodec,ZodCompileAsyncError:()=>ZodCompileAsyncError,
224
+ "gu");import{lstatSync as lstatSync2,readlinkSync}from"node:fs";import{dirname,isAbsolute as isAbsolute2,join as join4,relative,resolve}from"node:path";import{readFileSync as readFileSync3,mkdirSync,existsSync,renameSync as renameSync2}from"node:fs";import{mkdtempSync}from"node:fs";import{homedir,tmpdir,userInfo}from"node:os";import{join as join2}from"node:path";var home;function dataHome(){if(home!==void 0)return home;let real=homedir();return home=process.env.VITEST!==void 0&&real===userInfo().homedir?mkdtempSync(join2(tmpdir(),"omb-test-home-")):real,home}import{join as join3}from"node:path";var external_exports={};__export(external_exports,{$brand:()=>$brand,$input:()=>$input,$output:()=>$output,INVALID:()=>INVALID,NEVER:()=>NEVER,TimePrecision:()=>TimePrecision,ZodAny:()=>ZodAny,ZodArray:()=>ZodArray,ZodBase64:()=>ZodBase64,ZodBase64URL:()=>ZodBase64URL,ZodBigInt:()=>ZodBigInt,ZodBigIntFormat:()=>ZodBigIntFormat,ZodBoolean:()=>ZodBoolean,ZodCIDRv4:()=>ZodCIDRv4,ZodCIDRv6:()=>ZodCIDRv6,ZodCUID:()=>ZodCUID,ZodCUID2:()=>ZodCUID2,ZodCatch:()=>ZodCatch,ZodCodec:()=>ZodCodec,ZodCompileAsyncError:()=>ZodCompileAsyncError,
225
225
  ZodCompileUnsupportedError:()=>ZodCompileUnsupportedError,ZodCreditCard:()=>ZodCreditCard,ZodCustom:()=>ZodCustom,ZodCustomStringFormat:()=>ZodCustomStringFormat,ZodDate:()=>ZodDate,ZodDefault:()=>ZodDefault,ZodDiscriminatedUnion:()=>ZodDiscriminatedUnion,ZodE164:()=>ZodE164,ZodEmail:()=>ZodEmail,ZodEmoji:()=>ZodEmoji,ZodEnum:()=>ZodEnum,ZodError:()=>ZodError,ZodExactOptional:()=>ZodExactOptional,ZodFile:()=>ZodFile,ZodFirstPartyTypeKind:()=>ZodFirstPartyTypeKind,ZodFunction:()=>ZodFunction,ZodGUID:()=>ZodGUID,
226
226
  ZodIBAN:()=>ZodIBAN,ZodIPv4:()=>ZodIPv4,ZodIPv6:()=>ZodIPv6,ZodISODate:()=>ZodISODate,ZodISODateTime:()=>ZodISODateTime,ZodISODuration:()=>ZodISODuration,ZodISOTime:()=>ZodISOTime,ZodInstanceOf:()=>ZodInstanceOf,ZodIntersection:()=>ZodIntersection,ZodIssueCode:()=>ZodIssueCode,ZodJWT:()=>ZodJWT,ZodKSUID:()=>ZodKSUID,ZodLazy:()=>ZodLazy,ZodLiteral:()=>ZodLiteral,ZodMAC:()=>ZodMAC,ZodMap:()=>ZodMap,ZodNaN:()=>ZodNaN,ZodNanoID:()=>ZodNanoID,ZodNever:()=>ZodNever,ZodNonOptional:()=>ZodNonOptional,ZodNull:()=>ZodNull,
227
227
  ZodNullable:()=>ZodNullable,ZodNumber:()=>ZodNumber,ZodNumberFormat:()=>ZodNumberFormat,ZodObject:()=>ZodObject,ZodOptional:()=>ZodOptional,ZodPipe:()=>ZodPipe,ZodPrefault:()=>ZodPrefault,ZodPreprocess:()=>ZodPreprocess,ZodPromise:()=>ZodPromise,ZodReadonly:()=>ZodReadonly,ZodRealError:()=>ZodRealError,ZodRecord:()=>ZodRecord,ZodSet:()=>ZodSet,ZodString:()=>ZodString,ZodStringFormat:()=>ZodStringFormat,ZodSuccess:()=>ZodSuccess,ZodSymbol:()=>ZodSymbol,ZodTemplateLiteral:()=>ZodTemplateLiteral,ZodTransform:()=>ZodTransform,
@@ -1552,7 +1552,7 @@ object({apiKey:optionalText2,providerKeys:external_exports.record(external_expor
1552
1552
  shape,jsonObjectSchema2=external_exports.record(external_exports.string(),external_exports.json());function parseStoredConfig(value){let parsed=storedAppConfigSchema.safeParse(value);if(!parsed.success)throw new Error(schemaIssue(parsed.error,"Invalid stored configuration"));return parsed.data.localVm&&parsed.data.localVm.automaticCapacity===void 0&&(parsed.data.localVm.automaticCapacity=!0),parsed.data}var DEFAULT_CAPTURE_QUIET_MS=2*6e4;var DATA_DIR=process.env.OMB_DATA_DIR||join3(dataHome(),".limixbot"),LEGACY_DATA_DIR=join3(dataHome(),".opengrokbot"),EVENTS_DIR=join3(DATA_DIR,"events"),NATIVE_DIR=join3(DATA_DIR,"native");var storedConfig=settledFileCache(()=>join3(DATA_DIR,"config.json"),()=>parseStoredConfig(parseJson(readFileSync3(join3(DATA_DIR,"config.json"),"utf8"))));var SECRET_FOLDER=".limixbot-secrets";function inSecretFolder(path){return path.split(/[\\/]/).includes(SECRET_FOLDER)}var PORTABLE_CONFIG_KEYS=["profile","language","budgets","billing","rooms","threads","localVm","features","browserProfiles"];function portableWorkspaceConfig(value){if(!value||typeof value!="object"||Array.isArray(value))throw new Error("Invalid workspace configuration in backup.");let config2=parseStoredConfig(value);return Object.fromEntries(PORTABLE_CONFIG_KEYS.filter(key=>config2[key]!==void 0).map(key=>[key,config2[key]]))}function excludedWorkspaceAuthPath(path){return inSecretFolder(path)||/^command-allowlist\.json(?:$|\.\d+\.[0-9a-f-]+\.tmp$)/.test(path)||/^mcp-oauth\.json(?:$|\.\d+\.[0-9a-f-]+\.tmp$)/.test(path)||/^(?:logins\.json\.enc|logins-key|webhook-key)(?:$|\.\d+\.[0-9a-f-]+\.tmp$)/.test(path)||/^connected-apps-installation\.json(?:$|\.\d+\.[0-9a-f-]+\.tmp$)/.test(path)||/^team-policy\.json(?:$|\.\d+\.[0-9a-f-]+\.tmp$)/.test(path)||/^people-connections(?:\/|$)/.test(path)?!0:/^(?:(?:providers|caddy|chrome-profile|\.agent-browser)(?:\/|$)|workspace-credentials\.json$|external-runtimes\.json$|browser-engine-key$)/.
1553
1553
  test(path)||/^(?:config\.json|webhooks\.json|workspace-credentials\.json|external-runtimes\.json|browser-engine-key|sessions\.json|tunnel-account\.json)\.\d+(?:\.[0-9a-f-]+)?\.tmp$/.test(path)||/^(?:vm-home|vm-homes\/[^/]+)\/\.browser-profiles(?:\/|$)/.test(path)}function redownloadedOrgLibraryPath(path){return/^org-library\/(?:catalog\.json(?:\.[0-9a-f-]{36}\.tmp)?$|blobs(?:\/|$))/.test(path)}function ephemeralWorkspaceTokenPath(path){return/^(?:hook-tokens(?:\/|$)|sessions\.json\.open$)/.test(
1554
1554
  path)}function liveDataEnginePath(path){return/^bots\/[^/]+\/(?:data\.duckdb(?:\.wal)?$|data-tmp(?:\/|$))/.test(path)}function managedTaskSkillLink(source,path,roots){let match=/^task-workspaces\/([^/]+)\/[^/]+\/\.(?:claude|agents|grok)\/skills\/([^/]+)$/.exec(path);if(!match)return!1;let target;try{target=resolve(dirname(source),readlinkSync(source).replace(/^\\\\\?\\/,""))}catch{return!1}return roots.some(root=>{let rel=relative(join4(root,"workspaces",match[1],"skills"),target);return rel!==""&&
1555
- !rel.startsWith("..")&&!isAbsolute2(rel)||relative(join4(root,"imported-skills",match[2]),target)===""})}import{existsSync as existsSync2,readdirSync as readdirSync2,readFileSync as readFileSync4}from"node:fs";import{join as join12}from"node:path";import{DatabaseSync as DatabaseSync2}from"node:sqlite";import{createHash as createHash2}from"node:crypto";var CLOUD_OUTSIDE_KEY=`p_${createHash2("sha256").update("cloud-outside").digest("base64url").slice(0,22)}`,CLOUD_NOBODY_KEY=`p_${createHash2("sha256").update("cloud-nobody").digest("base64url").slice(0,22)}`;import{join as join11}from"node:path";import{appendFileSync}from"node:fs";import{join as join5}from"node:path";import{closeSync as closeSync2,fstatSync as fstatSync2,openSync as openSync2,readSync,renameSync as renameSync3,rmSync,statSync as statSync2,writeSync}from"node:fs";var capProvider=()=>null;function currentThreadLogCap(){try{return capProvider()}catch{return null}}function capThreadLog(file2,maxBytes){if(typeof maxBytes!="number"||!Number.isFinite(maxBytes)||maxBytes<=0)return;let size;try{size=statSync2(file2).size}catch{return}size<=maxBytes||trimToTail(file2,Math.max(1,Math.floor(maxBytes/2)))}function trimToTail(file2,keepBytes){let staging=`${file2}.trim`;try{let source=openSync2(file2,"r");try{let size=fstatSync2(source).size,start=Math.max(0,size-keepBytes),window=Buffer.allocUnsafe(
1555
+ !rel.startsWith("..")&&!isAbsolute2(rel)||relative(join4(root,"imported-skills",match[2]),target)===""})}function installedDependencyFolder(source,name,stat){if(!stat.isDirectory()&&!stat.isSymbolicLink())return!1;if(name==="node_modules")return!0;try{return lstatSync2(join4(source,"pyvenv.cfg")).isFile()}catch{return!1}}var bytecodeCache=(name,stat)=>name==="__pycache__"&&(stat.isDirectory()||stat.isSymbolicLink());import{existsSync as existsSync2,readdirSync as readdirSync2,readFileSync as readFileSync4}from"node:fs";import{join as join12}from"node:path";import{DatabaseSync as DatabaseSync2}from"node:sqlite";import{createHash as createHash2}from"node:crypto";var CLOUD_OUTSIDE_KEY=`p_${createHash2("sha256").update("cloud-outside").digest("base64url").slice(0,22)}`,CLOUD_NOBODY_KEY=`p_${createHash2("sha256").update("cloud-nobody").digest("base64url").slice(0,22)}`;import{join as join11}from"node:path";import{appendFileSync}from"node:fs";import{join as join5}from"node:path";import{closeSync as closeSync2,fstatSync as fstatSync2,openSync as openSync2,readSync,renameSync as renameSync3,rmSync,statSync as statSync2,writeSync}from"node:fs";var capProvider=()=>null;function currentThreadLogCap(){try{return capProvider()}catch{return null}}function capThreadLog(file2,maxBytes){if(typeof maxBytes!="number"||!Number.isFinite(maxBytes)||maxBytes<=0)return;let size;try{size=statSync2(file2).size}catch{return}size<=maxBytes||trimToTail(file2,Math.max(1,Math.floor(maxBytes/2)))}function trimToTail(file2,keepBytes){let staging=`${file2}.trim`;try{let source=openSync2(file2,"r");try{let size=fstatSync2(source).size,start=Math.max(0,size-keepBytes),window=Buffer.allocUnsafe(
1556
1556
  size-start),filled=0;for(;filled<window.length;){let count2=readSync(source,window,filled,window.length-filled,start+filled);if(count2===0)return;filled+=count2}let firstNewline=window.indexOf(10);if(firstNewline===-1||firstNewline+1>=window.length)return;let target=openSync2(staging,"w",384);try{let written=firstNewline+1;for(;written<window.length;){let count2=writeSync(target,window,written,window.length-written);if(count2===0)throw new Error(`no progress writing ${staging}`);written+=count2}}finally{
1557
1557
  closeSync2(target)}}finally{closeSync2(source)}renameSync3(staging,file2)}catch{try{rmSync(staging,{force:!0})}catch{}}}var MAX_HELD_CHARS=256*1024,held=new Map,heldChars=0,timer=null;function flushNativeLog(threadId){let lines=take(threadId);if(!lines)return;let file2=join5(NATIVE_DIR,`${threadId}.ndjson`);try{appendFileSync(file2,lines.join(""),{mode:384}),capThreadLog(file2,currentThreadLogCap())}catch{}}function flushNativeLogs(){timer&&clearTimeout(timer),timer=null;for(let threadId of Array.from(held.keys()))flushNativeLog(threadId)}function take(threadId){let lines=held.get(threadId);if(lines){held.delete(threadId);for(let line of lines)heldChars-=line.length;return lines}}process.once("exit",flushNativeLogs);import{join as join7}from"node:path";import{join as join6}from"node:path";var PUBLISHED_TEAMS_FILE=join6(DATA_DIR,"published-teams.json"),keyMap=external_exports.record(external_exports.string(),external_exports.string()),publishedTeamSchema=external_exports.object({packageId:external_exports.string().min(1),lastRelease:external_exports.string().min(1),keys:external_exports.object({bots:keyMap,rooms:keyMap,routines:keyMap}).default({bots:{},rooms:{},routines:{}})}),fileSchema=external_exports.object({version:external_exports.literal(1),teams:external_exports.record(external_exports.
1558
1558
  string(),external_exports.unknown())});var SECTION_CONTEXTS_FILE=join7(DATA_DIR,"section-contexts.json"),sectionContextRecordSchema=external_exports.object({text:external_exports.string(),updatedAt:external_exports.number().finite()}),sectionContextFileSchema=external_exports.object({version:external_exports.literal(1),sections:external_exports.array(external_exports.string()).optional(),memoryKeys:external_exports.record(external_exports.string(),external_exports.string().min(1)).optional(),contexts:external_exports.record(external_exports.
@@ -1622,42 +1622,42 @@ prepare("SELECT DISTINCT bot_id AS id FROM memory_files").all().map(row=>String(
1622
1622
  assignments),deleteWhereIn(db,"inbox","owner_thread_id",threads),deleteWhereIn(db,"assignments","id",assignments)})}var TEAM_PRIVATE_NOTE="Members' private chats are theirs alone and are not in this export: their conversations, what bots remember from them, their own Limix Bot and their About you stay out.";var MAX_WORKSPACE_BACKUP_BYTES=10*1024**3,MAX_WORKSPACE_BACKUP_FILES=1e5,MAX_WORKSPACE_BACKUP_UPLOAD_BYTES=MAX_WORKSPACE_BACKUP_BYTES+256*1024**2,MAX_METADATA_BYTES=16*1024**2,MAGIC=Buffer.from(`OMB-WORKSPACE-1
1623
1623
  `),HEADER_BYTES=MAGIC.length+16+12;var ID=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,WAITS_FILE="waits.json",EXCLUDED=new Set([".backups","tools","browser","agent-browser-profiles","cache",".cache","tmp",".tmp","dist-native","tunnel-runtime","evidence",".limixbot-server-child","environment-id","sessions.json","tunnel-account.json","team-computers.json","vm-working-folders.json",".limixbot-server-child",".openmausbot-server-child","openmausbot-server.lease","limixbot-server.lease","box-create-requests.\
1624
1624
  lock","messages.db-wal","messages.db-shm","runtime.db-wal","runtime.db-shm","decider-log","cloud-owner.json","sync","claude-user-skills","box","engine-homes",WAITS_FILE,"data-format.json"]),EXCLUSION_NOTES=["Device pairing, server identity, live leases and runtime files (existing destination identities are preserved).","Saved credentials, provider and MCP connections, managed provider login homes and browser login profiles are not transferred. Destination connections are preserved; reconnect on \
1625
- a new device.","Downloaded tools and caches (they can be installed again), and recorded browser step screenshots (export them from a conversation to keep them).","Installed dependency folders (node_modules) and symbolic links inside conversation work folders; reinstall or recreate them in the project.","External project folders, CLI login homes, browser session homes, OS keychains, companion devices and other servers.","VM/container disk layers and remote cloud data; durable files inside this wo\
1626
- rkspace are included.","Waits bots set up: they end within a week, so ask the bot again after restoring."],RESTORE_WARNING="Restoring pauses routines, webhooks and calendar calls, ends every wait, and does not resume pending delegations, queued chat messages or queued runs. Definitions and historical receipts are retained; review before enabling them again.";function excluded(name){return EXCLUDED.has(name)||excludedWorkspaceAuthPath(name)||/^(?:limixbot|openmausbot)-server\.lease\./.test(name)||
1627
- name.startsWith("box-create-requests.lock.")||/^perm-[A-Za-z0-9_-]+\.sock$/.test(name)}function forbiddenArchivePath(path){let folded=path.toLowerCase();return excluded(folded.split("/")[0])||excludedWorkspaceAuthPath(folded)||path!==folded&&["config.json","webhooks.json"].includes(folded)}var SNAPSHOT_DATABASES={"messages.db":"messages-snapshot.db","runtime.db":"runtime-snapshot.db"},LIVE_DATABASE_SIDECARS=new Set(Object.keys(SNAPSHOT_DATABASES).flatMap(name=>[`${name}-wal`,`${name}-shm`]));function folder(path){mkdirSync2(path,{recursive:!0,mode:448});let stat=lstatSync2(path);if(!stat.isDirectory()||stat.isSymbolicLink())throw new Error("The backup directory must be a real directory, not a symbolic link.");chmodSync(path,448)}function backupRoot(dataDir2){let root=resolve2(dataDir2);if(root===parse3(root).root)throw new Error("A filesystem root cannot be a workspace backup target.");let stat=lstatSync2(root);if(!stat.isDirectory()||stat.isSymbolicLink())throw new Error("The works\
1628
- pace data directory must not be a symbolic link.");let path=join13(root,".backups");return folder(path),path}function jobPath(dataDir2,id2){if(!ID.test(id2))throw new Error("Invalid workspace backup identifier.");let path=join13(backupRoot(dataDir2),id2);if(entryExists(path)){let stat=lstatSync2(path);if(!stat.isDirectory()||stat.isSymbolicLink())throw new Error("Unsafe workspace backup job directory.")}return path}function newJob(dataDir2,id2=randomUUID2()){let directory=jobPath(dataDir2,id2);return mkdirSync2(
1629
- directory,{mode:448}),{id:id2,directory}}function record3(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function entryExists(path){try{return lstatSync2(path),!0}catch(error62){if(error62.code==="ENOENT")return!1;throw error62}}function privateJson(path){let fd=openSync3(path,constants2.O_RDONLY|constants2.O_NOFOLLOW);try{let stat=fstatSync3(fd);if(!stat.isFile()||stat.size>MAX_METADATA_BYTES)throw new Error("Workspace backup metadata is too large or is not a regular \
1625
+ a new device.","Downloaded tools and caches (they can be installed again), and recorded browser step screenshots (export them from a conversation to keep them).","Installed dependency folders (node_modules, Python virtual environments), Python bytecode caches and symbolic links inside conversation work folders; reinstall or recreate them in the project.","External project folders, CLI login homes, browser session homes, OS keychains, companion devices and other servers.","VM/container disk layer\
1626
+ s and remote cloud data; durable files inside this workspace are included.","Waits bots set up: they end within a week, so ask the bot again after restoring."],RESTORE_WARNING="Restoring pauses routines, webhooks and calendar calls, ends every wait, and does not resume pending delegations, queued chat messages or queued runs. Definitions and historical receipts are retained; review before enabling them again.";function excluded(name){return EXCLUDED.has(name)||excludedWorkspaceAuthPath(name)||/^(?:limixbot|openmausbot)-server\.lease\./.
1627
+ test(name)||name.startsWith("box-create-requests.lock.")||/^perm-[A-Za-z0-9_-]+\.sock$/.test(name)}function forbiddenArchivePath(path){let folded=path.toLowerCase();return excluded(folded.split("/")[0])||excludedWorkspaceAuthPath(folded)||path!==folded&&["config.json","webhooks.json"].includes(folded)}var SNAPSHOT_DATABASES={"messages.db":"messages-snapshot.db","runtime.db":"runtime-snapshot.db"},LIVE_DATABASE_SIDECARS=new Set(Object.keys(SNAPSHOT_DATABASES).flatMap(name=>[`${name}-wal`,`${name}-shm`]));function folder(path){mkdirSync2(path,{recursive:!0,mode:448});let stat=lstatSync3(path);if(!stat.isDirectory()||stat.isSymbolicLink())throw new Error("The backup directory must be a real directory, not a symbolic link.");chmodSync(path,448)}function backupRoot(dataDir2){let root=resolve2(dataDir2);if(root===parse3(root).root)throw new Error("A filesystem root cannot be a workspace backup target.");let stat=lstatSync3(root);if(!stat.isDirectory()||stat.isSymbolicLink())throw new Error("The works\
1628
+ pace data directory must not be a symbolic link.");let path=join13(root,".backups");return folder(path),path}function jobPath(dataDir2,id2){if(!ID.test(id2))throw new Error("Invalid workspace backup identifier.");let path=join13(backupRoot(dataDir2),id2);if(entryExists(path)){let stat=lstatSync3(path);if(!stat.isDirectory()||stat.isSymbolicLink())throw new Error("Unsafe workspace backup job directory.")}return path}function newJob(dataDir2,id2=randomUUID2()){let directory=jobPath(dataDir2,id2);return mkdirSync2(
1629
+ directory,{mode:448}),{id:id2,directory}}function record3(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function entryExists(path){try{return lstatSync3(path),!0}catch(error62){if(error62.code==="ENOENT")return!1;throw error62}}function privateJson(path){let fd=openSync3(path,constants2.O_RDONLY|constants2.O_NOFOLLOW);try{let stat=fstatSync3(fd);if(!stat.isFile()||stat.size>MAX_METADATA_BYTES)throw new Error("Workspace backup metadata is too large or is not a regular \
1630
1630
  file.");return JSON.parse(readFileSync5(fd,"utf8"))}finally{closeSync3(fd)}}function writeJson(path,value){let text=JSON.stringify(value);if(Buffer.byteLength(text)>MAX_METADATA_BYTES)throw new Error("Workspace backup metadata exceeds the size limit.");writeFileAtomic(path,text,{mode:384})}function assertLocalAuthOutsideSnapshot(dataDir2){let configPath=join13(dataDir2,"config.json"),config2=existsSync3(configPath)?privateJson(configPath):{},instances=record3(config2)&&record3(config2.instances)?config2.instances:{},fields=["HOME","USERPROFILE","CLAUDE_CONFIG_DIR","CODEX_HOME","GROK_HOME","KIMI_CODE_HOME","HERMES_HOME","FACTORY_HOME_OVERRIDE","XDG_CONFIG_HOME","XDG_DATA_HOME","LOCALAPPDATA"],check2=(value,field,home2)=>{if(typeof value!="string"||!value.trim())return;let text=value.
1631
1631
  trim(),expanded=text.startsWith("~/")||text.startsWith("~\\")?join13(home2,text.slice(2)):text,resolved=resolve2(expanded),exists=entryExists(resolved),path=relative2(exists?realpathSync(dataDir2):resolve2(dataDir2),exists?realpathSync(resolved):resolved).replaceAll("\\","/");if(!(path===".."||path.startsWith("../")||isAbsolute3(path))&&!(path&&(excluded(path.split("/")[0])||excludedWorkspaceAuthPath(path))))throw new Error(`Provider authentication storage (${field}) is inside backed-up workspac\
1632
1632
  e files. Move that login storage into the excluded providers folder or outside this workspace before backing up or restoring.`)},environments=[process.env,...Object.values(instances).filter(record3).map(instance=>({...process.env,...record3(instance.environment)?instance.environment:{}}))];for(let environment of environments){let home2=String(environment.HOME||environment.USERPROFILE||homedir2());for(let field of fields)check2(environment[field],field,home2)}for(let instance of Object.values(instances)){
1633
1633
  if(!record3(instance)||instance.driver!=="claudeAgent"||!record3(instance.config))continue;let environment={...process.env,...record3(instance.environment)?instance.environment:{}};check2(instance.config.configDir,"config.configDir",String(environment.HOME||environment.USERPROFILE||homedir2()))}}function passwordKey(password,salt){if(typeof password!="string"||password.length<12||Buffer.byteLength(password)>1024)throw new Error("Use a backup password of at least 12 characters (at most 1024 bytes\
1634
1634
  ).");return new Promise((resolveKey,reject)=>{scrypt(password,salt,32,{N:131072,r:8,p:1,maxmem:256*1024**2},(error62,key)=>{error62?reject(error62):resolveKey(key)})})}function copyRegular(source,destination){let input2=openSync3(source,constants2.O_RDONLY|constants2.O_NOFOLLOW),output2;try{let before=fstatSync3(input2);if(!before.isFile()||before.size>MAX_WORKSPACE_BACKUP_BYTES)throw new Error("A workspace file is not regular or exceeds the 10 GB backup limit.");let mode=before.mode&64?448:384;
1635
- output2=openSync3(destination,"wx",mode);let chunk=Buffer.allocUnsafe(1024*1024),hash2=createHash3("sha256"),size=0;for(;;){let count2=readSync2(input2,chunk,0,chunk.length,null);if(!count2)break;if(size+=count2,size>before.size)throw new Error("A workspace file changed during backup. Stop its writer and retry.");hash2.update(chunk.subarray(0,count2));let offset=0;for(;offset<count2;)offset+=writeSync2(output2,chunk,offset,count2-offset)}let after=fstatSync3(input2),current=lstatSync2(source);if(size!==
1635
+ output2=openSync3(destination,"wx",mode);let chunk=Buffer.allocUnsafe(1024*1024),hash2=createHash3("sha256"),size=0;for(;;){let count2=readSync2(input2,chunk,0,chunk.length,null);if(!count2)break;if(size+=count2,size>before.size)throw new Error("A workspace file changed during backup. Stop its writer and retry.");hash2.update(chunk.subarray(0,count2));let offset=0;for(;offset<count2;)offset+=writeSync2(output2,chunk,offset,count2-offset)}let after=fstatSync3(input2),current=lstatSync3(source);if(size!==
1636
1636
  before.size||after.mtimeMs!==before.mtimeMs||after.ctimeMs!==before.ctimeMs||current.ino!==before.ino||current.dev!==before.dev||current.isSymbolicLink())throw new Error("A workspace file changed during backup. Stop its writer and retry.");return fsyncSync2(output2),{size,mode,sha256:hash2.digest("hex")}}finally{closeSync3(input2),output2!==void 0&&closeSync3(output2)}}function hashFile(path){let fd=openSync3(path,constants2.O_RDONLY|constants2.O_NOFOLLOW);try{if(!fstatSync3(fd).isFile())throw new Error(
1637
1637
  "The workspace archive contains an unsafe file.");let hash2=createHash3("sha256"),chunk=Buffer.allocUnsafe(1024*1024);for(;;){let count2=readSync2(fd,chunk,0,chunk.length,null);if(!count2)return hash2.digest("hex");hash2.update(chunk.subarray(0,count2))}}finally{closeSync3(fd)}}function countJsonArray(path){if(!existsSync3(path))return 0;let value=privateJson(path);if(!Array.isArray(value))throw new Error("A workspace roster is not a valid JSON array.");let ids=new Set;for(let item of value){if(!record3(
1638
1638
  item)||typeof item.id!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(item.id)||ids.has(item.id))throw new Error("A workspace roster contains an invalid or duplicate identifier.");if(ids.add(item.id),item.threadId!==void 0&&(typeof item.threadId!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(item.threadId)))throw new Error("A workspace roster contains an invalid thread identifier.");if(item.tasks!==void 0&&(!Array.isArray(item.tasks)||!item.tasks.every(task=>record3(task)&&typeof task.threadId=="string"&&/^[A-Za-z0-9_-]{1,128}$/.
1639
1639
  test(task.threadId))))throw new Error("A workspace roster contains invalid task records.")}return value.length}function databaseCounts(path){if(!existsSync3(path))return{threads:0,messages:0};let db=new DatabaseSync3(path,{readOnly:!0});try{let check2=db.prepare("PRAGMA quick_check").all();if(check2.length!==1||Object.values(check2[0])[0]!=="ok")throw new Error("The message database failed its integrity check.");if(db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name IN ('messa\
1640
1640
  ges', 'thread_state')").all().length!==2)throw new Error("The backup does not contain a supported message database.");let counts=db.prepare("SELECT COUNT(*) AS messages, COUNT(DISTINCT thread_id) AS threads FROM messages").get();return{threads:Number(counts.threads),messages:Number(counts.messages)}}finally{db.close()}}async function createWorkspaceBackupSnapshot(dataDir2,options2,jobId2){if(Object.hasOwn(options2,"credentials"))throw new Error("Workspace backups do not transfer credentials.");assertLocalAuthOutsideSnapshot(dataDir2);let salt=randomBytes(16),key=await passwordKey(options2.password,salt),job=newJob(dataDir2,jobId2),snapshot=join13(job.directory,"snapshot");folder(join13(snapshot,"data"));let entries=[],foldedPaths=new Map,warnings=["Stop external editors and managed desktops before exporting; f\
1641
- iles written outside this server cannot be frozen by the backup gate.","Conversation text and user files are not redacted and may contain secrets you pasted. Keep the encrypted backup private.",RESTORE_WARNING],bytes=0,skippedLinks=0,skippedDependencies=0,skippedWorkLinks=0,copiedLinks=0;try{let root=realpathSync(dataDir2);for(let[name,snapshotName]of Object.entries(SNAPSHOT_DATABASES)){let sourceDb=join13(root,name);if(!existsSync3(sourceDb))continue;if(lstatSync2(sourceDb).isSymbolicLink())throw new Error(
1641
+ iles written outside this server cannot be frozen by the backup gate.","Conversation text and user files are not redacted and may contain secrets you pasted. Keep the encrypted backup private.",RESTORE_WARNING],bytes=0,skippedLinks=0,skippedDependencies=0,skippedWorkLinks=0,copiedLinks=0;try{let root=realpathSync(dataDir2);for(let[name,snapshotName]of Object.entries(SNAPSHOT_DATABASES)){let sourceDb=join13(root,name);if(!existsSync3(sourceDb))continue;if(lstatSync3(sourceDb).isSymbolicLink())throw new Error(
1642
1642
  `The ${name==="messages.db"?"message":"runtime"} database must not be a symbolic link.`);let db=new DatabaseSync3(sourceDb,{readOnly:!0,timeout:5e3}),completionPulse=setInterval(()=>{},25);try{await backup(db,join13(snapshot,snapshotName))}finally{clearInterval(completionPulse),db.close()}let snapshotDb=new DatabaseSync3(join13(snapshot,snapshotName));try{snapshotDb.exec("PRAGMA journal_mode = DELETE")}finally{snapshotDb.close()}}let teamPrivate=teamPrivateThreads({starters:join13(root,"thread-s\
1643
1643
  tarters.json"),groups:join13(root,"groups.json"),bots:join13(root,"bots.json")}),privacy=teamPrivate&&{...teamPrivate,attachments:teamPrivateAttachments(root,join13(snapshot,SNAPSHOT_DATABASES["messages.db"]),teamPrivate)};privacy&&(stripTeamPrivate({messages:join13(snapshot,SNAPSHOT_DATABASES["messages.db"]),runtime:join13(snapshot,SNAPSHOT_DATABASES["runtime.db"])},privacy),warnings.push(TEAM_PRIVATE_NOTE));let walk=(directory,prefix="",chain=[root])=>{for(let name of readdirSync3(directory).sort()){
1644
1644
  if(!prefix&&excluded(name))continue;let path2=prefix?`${prefix}/${name}`:name;if(options2.omitMedia&&(/^(?:attachments|uploads|media|screenshots)(?:\/|$)/i.test(path2)||/\.(?:png|jpe?g|gif|webp|avif|bmp|ico|svg|heic|heif|tiff?|dng|mp4|m4v|mkv|mov|webm|avi|mpeg|mpg|3gp|m2ts|mts|flv|wmv|mp3|wav|ogg|flac|m4a|aac|opus|wma|aiff?)$/i.test(name))||excludedWorkspaceAuthPath(path2)||ephemeralWorkspaceTokenPath(path2)||redownloadedOrgLibraryPath(path2)||liveDataEnginePath(path2)||privacy&&omittedAsTeamPrivate(
1645
- path2,privacy))continue;if(forbiddenArchivePath(path2))throw new Error("A workspace filename conflicts with a protected authentication or runtime path.");if(!validRelative(path2))throw new Error(`Cannot back up a name that cannot be restored on every supported platform, such as one with ":" or "\\", a trailing dot or space, or a Windows device name like CON or AUX; rename it first: ${path2}`);let source=join13(directory,name),stat=lstatSync2(source);if(name==="node_modules"&&(stat.isDirectory()||
1646
- stat.isSymbolicLink())){skippedDependencies++;continue}if(stat.isSymbolicLink()&&path2.startsWith("task-workspaces/")){managedTaskSkillLink(source,path2,[root,resolve2(dataDir2)])?skippedLinks++:skippedWorkLinks++;continue}if(stat.isSymbolicLink()){let target;try{target=realpathSync(source)}catch{throw new Error(`Cannot back up dangling symbolic link: ${path2}`)}let rel=relative2(root,target);if(rel===".."||rel.startsWith(`..${process.platform==="win32"?"\\":"/"}`)||isAbsolute3(rel))throw new Error(
1647
- `Cannot back up symbolic link outside the workspace: ${path2}`);let portableRel=rel.replaceAll("\\","/");if(/^workspaces\/[^/]+\/\.(?:claude|agents|grok)\/skills\/[^/]+$/.test(path2)&&portableRel.startsWith(`workspaces/${path2.split("/")[1]}/skills/`)){skippedLinks++;continue}let workspace=/^workspaces\/[^/]+\//.exec(path2)?.[0];if(!workspace||!portableRel.startsWith(workspace))throw new Error(`Cannot back up user-created symbolic link; replace it with regular files first: ${path2}`);if(chain.some(
1648
- folder2=>folder2===target||folder2.startsWith(`${target}${sep}`)))throw userErrorThrown("serverError.backup.recursiveLink",{path:path2});source=target,stat=lstatSync2(source),copiedLinks++}if(entries.length>=MAX_WORKSPACE_BACKUP_FILES)throw new Error("The workspace exceeds the 100,000-entry backup limit.");let caseTwin=foldedPaths.get(path2.toLowerCase());if(caseTwin)throw new Error(`Cannot back up names that differ only by letter case, which collide on Windows and macOS; rename one first: ${caseTwin}\
1649
- and ${path2}`);foldedPaths.set(path2.toLowerCase(),path2);let destination=join13(snapshot,"data",path2);if(stat.isDirectory())folder(destination),entries.push({path:path2,type:"directory",size:0,mode:448}),walk(source,path2,[...chain,source]);else if(stat.isFile()){let copied;if(path2==="config.json"||path2==="webhooks.json"||privacy&&(path2==="bots.json"||path2==="routines.json")){let value=privateJson(source);if(path2==="config.json")writeJson(destination,portableWorkspaceConfig(value));else if(path2===
1650
- "bots.json")writeJson(destination,withoutTeamPrivate(value,privacy));else if(path2==="routines.json")writeJson(destination,routinesWithoutTeamPrivate(value,privateJson(join13(root,"bots.json")),privacy));else{if(!record3(value))throw new Error("Invalid webhook definitions in workspace backup.");if(Array.isArray(value.webhooks))for(let webhook of value.webhooks)record3(webhook)&&(delete webhook.secretHash,delete webhook.sealedSecret);if(Array.isArray(value.deleted))for(let entry of value.deleted)
1651
- record3(entry)&&record3(entry.webhook)&&delete entry.webhook.sealedSecret;writeJson(destination,value)}copied={size:lstatSync2(destination).size,mode:384,sha256:hashFile(destination)}}else copied=copyRegular(SNAPSHOT_DATABASES[path2]?join13(snapshot,SNAPSHOT_DATABASES[path2]):source,destination);if(bytes+=copied.size,bytes>MAX_WORKSPACE_BACKUP_BYTES)throw new Error("The workspace exceeds the 10 GB backup limit.");entries.push({path:path2,type:"file",...copied})}else throw new Error(`Cannot back \
1652
- up special or live runtime file: ${path2}`)}};walk(root),skippedLinks&&warnings.push(`${skippedLinks} managed skill discovery link(s) were omitted and are recreated by the app.`),skippedDependencies&&warnings.push(`${skippedDependencies} installed dependency folder(s) (node_modules) were omitted; reinstall them in the project after restoring.`),copiedLinks&&warnings.push(`${copiedLinks} symbolic link(s) inside a workspace were saved as copies of what they point to; restoring creates regular file\
1653
- s and folders there.`),skippedWorkLinks&&warnings.push(`${skippedWorkLinks} symbolic link(s) in conversation work folders were omitted; what they point to is outside this backup.`);let summary={format:"openmaus.workspace-backup",version:1,id:job.id,createdAt:new Date().toISOString(),appVersion:options2.appVersion??"unknown",files:entries.filter(entry=>entry.type==="file").length,directories:entries.filter(entry=>entry.type==="directory").length,bytes,bots:countJsonArray(join13(snapshot,"data","b\
1654
- ots.json")),groups:countJsonArray(join13(snapshot,"data","groups.json")),...databaseCounts(join13(snapshot,"data","messages.db")),exclusions:options2.omitMedia?[...EXCLUSION_NOTES,"Media files and attachment/upload folders are omitted from this offline transfer."]:EXCLUSION_NOTES,warnings},manifest={...options2.accountId!==void 0?{account:transferAccountHash(options2.accountId)}:{},summary,sourceDataDir:resolve2(dataDir2),clientState:options2.clientState??{},entries};writeJson(join13(snapshot,"m\
1655
- anifest.json"),manifest),validateManifest(privateJson(join13(snapshot,"manifest.json")));let path=join13(job.directory,"workspace.ombbackup"),iv=randomBytes(12),header=Buffer.concat([MAGIC,salt,iv]),cipher=createCipheriv("aes-256-gcm",key,iv);cipher.setAAD(header),writeFileSync2(path,header,{mode:384,flag:"wx"});let tar=await Promise.resolve().then(()=>(init_index_min(),index_min_exports));await pipeline(tar.c({cwd:snapshot,portable:!0,strict:!0},["manifest.json","data"]),cipher,createWriteStream(
1656
- path,{flags:"a",mode:384}));let fd=openSync3(path,"a");try{writeSync2(fd,cipher.getAuthTag()),fsyncSync2(fd)}finally{closeSync3(fd)}return rmSync2(snapshot,{recursive:!0,force:!0}),{id:job.id,path,summary}}catch(error62){throw rmSync2(job.directory,{recursive:!0,force:!0}),error62}finally{key.fill(0)}}function validateManifest(value){if(!record3(value)||!record3(value.summary)||value.summary.format!=="openmaus.workspace-backup"||value.summary.version!==1||typeof value.summary.id!="string"||!ID.test(
1657
- value.summary.id)||typeof value.summary.createdAt!="string"||!Number.isFinite(Date.parse(value.summary.createdAt))||typeof value.summary.appVersion!="string"||typeof value.sourceDataDir!="string"||!(posix.isAbsolute(value.sourceDataDir)||win32.isAbsolute(value.sourceDataDir))||value.sourceDataDir.length>4096||value.sourceDataDir.includes("\0")||value.sourceDataDir===posix.parse(value.sourceDataDir).root||value.sourceDataDir===win32.parse(value.sourceDataDir).root||value.sourceDataDir.replaceAll(
1658
- "\\","/").split("/").some(part=>part==="."||part==="..")||Object.keys(value).some(key=>!["summary","sourceDataDir","clientState","entries","account"].includes(key))||Object.keys(value.summary).some(key=>!["format","version","id","createdAt","appVersion","files","directories","bytes","bots","groups","threads","messages","exclusions","warnings"].includes(key))||!record3(value.clientState)||!Object.values(value.clientState).every(item=>typeof item=="string")||!Array.isArray(value.entries)||value.entries.
1659
- length>MAX_WORKSPACE_BACKUP_FILES)throw new Error("Invalid or unsupported workspace backup metadata.");if(Object.keys(value.clientState).some(key=>!WORKSPACE_BACKUP_CLIENT_KEYS.includes(key))||Buffer.byteLength(JSON.stringify(value.clientState))>2*1024**2)throw new Error("Invalid or oversized workspace client preferences.");for(let key of["files","directories","bytes","bots","groups","threads","messages"])if(!Number.isSafeInteger(value.summary[key])||value.summary[key]<0)throw new Error("Invalid\
1660
- workspace backup summary.");for(let key of["exclusions","warnings"])if(!Array.isArray(value.summary[key])||!value.summary[key].every(item=>typeof item=="string"))throw new Error("Invalid workspace backup summary.");if(value.account!==void 0&&(typeof value.account!="string"||!/^[0-9a-f]{64}$/.test(value.account)))throw new Error("Invalid backup account binding.");let names=new Map,bytes=0,files=0;for(let raw of value.entries){if(!record3(raw)||typeof raw.path!="string"||!validRelative(raw.path)||
1661
- forbiddenArchivePath(raw.path)||Object.keys(raw).some(key=>!["path","type","size","mode","sha256"].includes(key))||!["file","directory"].includes(String(raw.type))||!Number.isSafeInteger(raw.size)||raw.size<0||![384,448].includes(raw.mode)||names.has(raw.path.toLowerCase()))throw new Error("Unsafe or duplicate workspace backup entry.");if(names.set(raw.path.toLowerCase(),String(raw.type)),raw.type==="file"){if(typeof raw.sha256!="string"||!/^[0-9a-f]{64}$/.test(raw.sha256))throw new Error("A bac\
1662
- kup file has no valid checksum.");bytes+=raw.size,files++}else if(raw.size!==0)throw new Error("A backup directory has an invalid size.")}if(bytes>MAX_WORKSPACE_BACKUP_BYTES||bytes!==value.summary.bytes||files!==value.summary.files||names.size-files!==value.summary.directories)throw new Error("Workspace backup contents do not match their summary or exceed the limit.");for(let path of names.keys()){let parts=path.split("/");for(let i=1;i<parts.length;i++)if(names.get(parts.slice(0,i).join("/"))!==
1663
- "directory")throw new Error("A backup entry has an unsafe parent.")}return value}var{dataDir,options,jobId}=workerData;try{parentPort.postMessage({result:await createWorkspaceBackupSnapshot(dataDir,options,jobId)})}catch(error62){parentPort.postMessage({error:error62 instanceof Error?error62.message:"The workspace backup could not finish.",...userErrorFields(error62)})}
1645
+ path2,privacy))continue;if(forbiddenArchivePath(path2))throw new Error("A workspace filename conflicts with a protected authentication or runtime path.");if(!validRelative(path2))throw new Error(`Cannot back up a name that cannot be restored on every supported platform, such as one with ":" or "\\", a trailing dot or space, or a Windows device name like CON or AUX; rename it first: ${path2}`);let source=join13(directory,name),stat=lstatSync3(source);if(installedDependencyFolder(source,name,stat)){
1646
+ skippedDependencies++;continue}if(bytecodeCache(name,stat))continue;if(stat.isSymbolicLink()&&path2.startsWith("task-workspaces/")){managedTaskSkillLink(source,path2,[root,resolve2(dataDir2)])?skippedLinks++:skippedWorkLinks++;continue}if(stat.isSymbolicLink()){let target;try{target=realpathSync(source)}catch{throw new Error(`Cannot back up dangling symbolic link: ${path2}`)}let rel=relative2(root,target);if(rel===".."||rel.startsWith(`..${process.platform==="win32"?"\\":"/"}`)||isAbsolute3(rel))
1647
+ throw new Error(`Cannot back up symbolic link outside the workspace: ${path2}`);let portableRel=rel.replaceAll("\\","/");if(/^workspaces\/[^/]+\/\.(?:claude|agents|grok)\/skills\/[^/]+$/.test(path2)&&portableRel.startsWith(`workspaces/${path2.split("/")[1]}/skills/`)){skippedLinks++;continue}let workspace=/^workspaces\/[^/]+\//.exec(path2)?.[0];if(!workspace||!portableRel.startsWith(workspace))throw new Error(`Cannot back up user-created symbolic link; replace it with regular files first: ${path2}`);
1648
+ if(chain.some(folder2=>folder2===target||folder2.startsWith(`${target}${sep}`)))throw userErrorThrown("serverError.backup.recursiveLink",{path:path2});source=target,stat=lstatSync3(source),copiedLinks++}if(entries.length>=MAX_WORKSPACE_BACKUP_FILES)throw new Error("The workspace exceeds the 100,000-entry backup limit.");let caseTwin=foldedPaths.get(path2.toLowerCase());if(caseTwin)throw new Error(`Cannot back up names that differ only by letter case, which collide on Windows and macOS; rename on\
1649
+ e first: ${caseTwin} and ${path2}`);foldedPaths.set(path2.toLowerCase(),path2);let destination=join13(snapshot,"data",path2);if(stat.isDirectory())folder(destination),entries.push({path:path2,type:"directory",size:0,mode:448}),walk(source,path2,[...chain,source]);else if(stat.isFile()){let copied;if(path2==="config.json"||path2==="webhooks.json"||privacy&&(path2==="bots.json"||path2==="routines.json")){let value=privateJson(source);if(path2==="config.json")writeJson(destination,portableWorkspaceConfig(
1650
+ value));else if(path2==="bots.json")writeJson(destination,withoutTeamPrivate(value,privacy));else if(path2==="routines.json")writeJson(destination,routinesWithoutTeamPrivate(value,privateJson(join13(root,"bots.json")),privacy));else{if(!record3(value))throw new Error("Invalid webhook definitions in workspace backup.");if(Array.isArray(value.webhooks))for(let webhook of value.webhooks)record3(webhook)&&(delete webhook.secretHash,delete webhook.sealedSecret);if(Array.isArray(value.deleted))for(let entry of value.
1651
+ deleted)record3(entry)&&record3(entry.webhook)&&delete entry.webhook.sealedSecret;writeJson(destination,value)}copied={size:lstatSync3(destination).size,mode:384,sha256:hashFile(destination)}}else copied=copyRegular(SNAPSHOT_DATABASES[path2]?join13(snapshot,SNAPSHOT_DATABASES[path2]):source,destination);if(bytes+=copied.size,bytes>MAX_WORKSPACE_BACKUP_BYTES)throw new Error("The workspace exceeds the 10 GB backup limit.");entries.push({path:path2,type:"file",...copied})}else throw new Error(`Cann\
1652
+ ot back up special or live runtime file: ${path2}`)}};walk(root),skippedLinks&&warnings.push(`${skippedLinks} managed skill discovery link(s) were omitted and are recreated by the app.`),skippedDependencies&&warnings.push(`${skippedDependencies} installed dependency folder(s) (node_modules or Python virtual environments) were omitted; reinstall them in the project after restoring.`),copiedLinks&&warnings.push(`${copiedLinks} symbolic link(s) inside a workspace were saved as copies of what they p\
1653
+ oint to; restoring creates regular files and folders there.`),skippedWorkLinks&&warnings.push(`${skippedWorkLinks} symbolic link(s) in conversation work folders were omitted; what they point to is outside this backup.`);let summary={format:"openmaus.workspace-backup",version:1,id:job.id,createdAt:new Date().toISOString(),appVersion:options2.appVersion??"unknown",files:entries.filter(entry=>entry.type==="file").length,directories:entries.filter(entry=>entry.type==="directory").length,bytes,bots:countJsonArray(
1654
+ join13(snapshot,"data","bots.json")),groups:countJsonArray(join13(snapshot,"data","groups.json")),...databaseCounts(join13(snapshot,"data","messages.db")),exclusions:options2.omitMedia?[...EXCLUSION_NOTES,"Media files and attachment/upload folders are omitted from this offline transfer."]:EXCLUSION_NOTES,warnings},manifest={...options2.accountId!==void 0?{account:transferAccountHash(options2.accountId)}:{},summary,sourceDataDir:resolve2(dataDir2),clientState:options2.clientState??{},entries};writeJson(
1655
+ join13(snapshot,"manifest.json"),manifest),validateManifest(privateJson(join13(snapshot,"manifest.json")));let path=join13(job.directory,"workspace.ombbackup"),iv=randomBytes(12),header=Buffer.concat([MAGIC,salt,iv]),cipher=createCipheriv("aes-256-gcm",key,iv);cipher.setAAD(header),writeFileSync2(path,header,{mode:384,flag:"wx"});let tar=await Promise.resolve().then(()=>(init_index_min(),index_min_exports));await pipeline(tar.c({cwd:snapshot,portable:!0,strict:!0},["manifest.json","data"]),cipher,
1656
+ createWriteStream(path,{flags:"a",mode:384}));let fd=openSync3(path,"a");try{writeSync2(fd,cipher.getAuthTag()),fsyncSync2(fd)}finally{closeSync3(fd)}return rmSync2(snapshot,{recursive:!0,force:!0}),{id:job.id,path,summary}}catch(error62){throw rmSync2(job.directory,{recursive:!0,force:!0}),error62}finally{key.fill(0)}}function validateManifest(value){if(!record3(value)||!record3(value.summary)||value.summary.format!=="openmaus.workspace-backup"||value.summary.version!==1||typeof value.summary.id!=
1657
+ "string"||!ID.test(value.summary.id)||typeof value.summary.createdAt!="string"||!Number.isFinite(Date.parse(value.summary.createdAt))||typeof value.summary.appVersion!="string"||typeof value.sourceDataDir!="string"||!(posix.isAbsolute(value.sourceDataDir)||win32.isAbsolute(value.sourceDataDir))||value.sourceDataDir.length>4096||value.sourceDataDir.includes("\0")||value.sourceDataDir===posix.parse(value.sourceDataDir).root||value.sourceDataDir===win32.parse(value.sourceDataDir).root||value.sourceDataDir.
1658
+ replaceAll("\\","/").split("/").some(part=>part==="."||part==="..")||Object.keys(value).some(key=>!["summary","sourceDataDir","clientState","entries","account"].includes(key))||Object.keys(value.summary).some(key=>!["format","version","id","createdAt","appVersion","files","directories","bytes","bots","groups","threads","messages","exclusions","warnings"].includes(key))||!record3(value.clientState)||!Object.values(value.clientState).every(item=>typeof item=="string")||!Array.isArray(value.entries)||
1659
+ value.entries.length>MAX_WORKSPACE_BACKUP_FILES)throw new Error("Invalid or unsupported workspace backup metadata.");if(Object.keys(value.clientState).some(key=>!WORKSPACE_BACKUP_CLIENT_KEYS.includes(key))||Buffer.byteLength(JSON.stringify(value.clientState))>2*1024**2)throw new Error("Invalid or oversized workspace client preferences.");for(let key of["files","directories","bytes","bots","groups","threads","messages"])if(!Number.isSafeInteger(value.summary[key])||value.summary[key]<0)throw new Error(
1660
+ "Invalid workspace backup summary.");for(let key of["exclusions","warnings"])if(!Array.isArray(value.summary[key])||!value.summary[key].every(item=>typeof item=="string"))throw new Error("Invalid workspace backup summary.");if(value.account!==void 0&&(typeof value.account!="string"||!/^[0-9a-f]{64}$/.test(value.account)))throw new Error("Invalid backup account binding.");let names=new Map,bytes=0,files=0;for(let raw of value.entries){if(!record3(raw)||typeof raw.path!="string"||!validRelative(raw.
1661
+ path)||forbiddenArchivePath(raw.path)||Object.keys(raw).some(key=>!["path","type","size","mode","sha256"].includes(key))||!["file","directory"].includes(String(raw.type))||!Number.isSafeInteger(raw.size)||raw.size<0||![384,448].includes(raw.mode)||names.has(raw.path.toLowerCase()))throw new Error("Unsafe or duplicate workspace backup entry.");if(names.set(raw.path.toLowerCase(),String(raw.type)),raw.type==="file"){if(typeof raw.sha256!="string"||!/^[0-9a-f]{64}$/.test(raw.sha256))throw new Error(
1662
+ "A backup file has no valid checksum.");bytes+=raw.size,files++}else if(raw.size!==0)throw new Error("A backup directory has an invalid size.")}if(bytes>MAX_WORKSPACE_BACKUP_BYTES||bytes!==value.summary.bytes||files!==value.summary.files||names.size-files!==value.summary.directories)throw new Error("Workspace backup contents do not match their summary or exceed the limit.");for(let path of names.keys()){let parts=path.split("/");for(let i=1;i<parts.length;i++)if(names.get(parts.slice(0,i).join("\
1663
+ /"))!=="directory")throw new Error("A backup entry has an unsafe parent.")}return value}var{dataDir,options,jobId}=workerData;try{parentPort.postMessage({result:await createWorkspaceBackupSnapshot(dataDir,options,jobId)})}catch(error62){parentPort.postMessage({error:error62 instanceof Error?error62.message:"The workspace backup could not finish.",...userErrorFields(error62)})}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "limixbot",
3
- "version": "0.3.116",
3
+ "version": "0.3.118",
4
4
  "description": "Run the Limix Bot server anywhere and pair your devices to it (Leox ৹ Limix AI)",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -1,2 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/DataPanel-X1VUpw1U.js","assets/styles-DaC7RuGF.js","assets/styles-D55d5vt1.css","assets/App-D_fqRJhk.js","assets/index-CD6r_oet.js","assets/PlacesRail-3RYT-fm8.js","assets/monitor-Ehduuiym.js","assets/MenuMotion-READmdk4.js","assets/calendar-days-BuEc0yb0.js","assets/LiveDesktop-B8KndeA2.js","assets/desktop-connection-Dfaq6k5a.js","assets/desktop-viewer-CF-OpSo0.js"])))=>i.map(i=>d[i]);
2
- import{c as ht,r as a,t as n,j as e,a as K,ah as hr,X as gr,ai as vr,o as yr,f as yn,u as wr,s as kr,_ as Pn}from"./styles-DaC7RuGF.js";import{c as jr,a as Nr,b as Sr,i as Cr,d as Ir}from"./remote-desktop-DDRRx8uY.js";import{v as Rr}from"./desktop-viewer-CF-OpSo0.js";import{dO as Ze,S as zn,E as Er,w as Pr,bR as zr,bu as Tr,R as pt,P as Ar,U as Ye,dP as Dr,Y as Ge,bt as Lr,af as Mr,dQ as Or,G as Ft,C as Tn,dR as $t,dS as dt,u as Vr,dT as _r,dU as Fr,dV as $r,dW as Br,a0 as Wr,dX as Kr,dY as Ur,dZ as Hr,d_ as qr,d$ as Xr,k as Yr,bW as Gr,bV as wn,j as F,e0 as Zr,e1 as Jr,l as Qr,X as es,bX as kn,e2 as ts,e3 as ns,a1 as rs,e4 as jn,e5 as ss,e6 as as,e7 as os,m as Nn,x as is,e8 as ls,e9 as Vt,a8 as cs,a9 as ds,cw as us,ea as ps,eb as ms,Z as xs,A as bs,ec as fs,ed as hs,ee as gs,ef as vs,n as ys,eg as ws,eh as ks,ei as js}from"./App-D_fqRJhk.js";import{L as O,p as Sn,M as Ns,w as Ss}from"./MacLocalControl-6LKkmAKt.js";import{R as Cs,C as Is}from"./ComputerFilesPane-BCaN6XSL.js";import{L as A,X as An,u as Dn,d as Je,c as Rs,v as Cn,e as mt,W as In}from"./PlacesRail-3RYT-fm8.js";import{u as Bt,B as Es}from"./BrowserPanel-abUgbX2z.js";import{M as De}from"./monitor-Ehduuiym.js";import{C as Ln,w as Ps,a as zs,p as Ts,W as As}from"./WorksOnGrid-DCpYS0ZD.js";import{C as Ds}from"./MenuMotion-READmdk4.js";import"./index-CD6r_oet.js";import"./RoutinesPage-D9VQa8Id.js";import"./ProIntroduction-BBpRtakG.js";import"./BrowserProfilesManager-IuxTSnih.js";import"./SignedInSites-B9tzCm-B.js";import"./minimize-6B5ELLt0.js";import"./file-up-CMuz1zvC.js";const Ls=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M12 3v18",key:"108xh3"}]],Ms=ht("columns-2",Ls);const Os=[["path",{d:"M12 17v4",key:"1riwvh"}],["path",{d:"m14.305 7.53.923-.382",key:"1mlnsw"}],["path",{d:"m15.228 4.852-.923-.383",key:"82mpwg"}],["path",{d:"m16.852 3.228-.383-.924",key:"ln4sir"}],["path",{d:"m16.852 8.772-.383.923",key:"1dejw0"}],["path",{d:"m19.148 3.228.383-.924",key:"192kgf"}],["path",{d:"m19.53 9.696-.382-.924",key:"fiavlr"}],["path",{d:"m20.772 4.852.924-.383",key:"1j8mgp"}],["path",{d:"m20.772 7.148.924.383",key:"zix9be"}],["path",{d:"M22 13v2a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7",key:"1tnzv8"}],["path",{d:"M8 21h8",key:"1ev6f3"}],["circle",{cx:"18",cy:"6",r:"3",key:"1h7g24"}]],Vs=ht("monitor-cog",Os);const _s=[["path",{d:"m14.5 12.5-5-5",key:"1jahn5"}],["path",{d:"m9.5 12.5 5-5",key:"1k2t7b"}],["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["path",{d:"M12 17v4",key:"1riwvh"}],["path",{d:"M8 21h8",key:"1ev6f3"}]],Fs=ht("monitor-x",_s);const $s=[["circle",{cx:"10",cy:"7",r:"1",key:"dypaad"}],["circle",{cx:"4",cy:"20",r:"1",key:"22iqad"}],["path",{d:"M4.7 19.3 19 5",key:"1enqfc"}],["path",{d:"m21 3-3 1 2 2Z",key:"d3ov82"}],["path",{d:"M9.26 7.68 5 12l2 5",key:"1esawj"}],["path",{d:"m10 14 5 2 3.5-3.5",key:"v8oal5"}],["path",{d:"m18 12 1-1 1 1-1 1Z",key:"1bh22v"}]],Bs=ht("usb",$s);function Ws({src:s,name:i,error:d,starting:S,opening:f,disabled:v,refreshing:k=!1,retry:j=0,onOpen:y,onRetry:P}){const[u,m]=a.useState(null),[h,g]=a.useState(null);a.useEffect(()=>{g(null)},[j]);const x=!!(s&&u===s&&h!==s),w=d??(s&&h===s?n("computer.preview.imageFailed"):null);return e.jsxs("div",{className:"relative h-full w-full","aria-busy":!w&&(!x||f||k),children:[s&&e.jsxs("button",{type:"button",onClick:y,disabled:v||S||f||!x,className:"group absolute inset-0 flex h-full w-full items-center justify-center disabled:cursor-wait","aria-label":n("computer.openLiveDesktopAria",{name:i}),title:n("computer.openLiveDesktop"),children:[e.jsx("img",{src:s,alt:n("computer.screenOf",{name:i}),onLoad:()=>{m(s),g(null)},onError:()=>g(s),className:`h-full w-full object-contain transition group-hover:brightness-75 ${x?"":"invisible"}`},j),x&&e.jsxs("span",{className:"absolute right-2 top-2 flex items-center gap-1 rounded-md bg-black/70 px-2 py-1 text-[11px] font-medium text-white",children:[f?e.jsx(A,{size:12,className:"animate-spin"}):e.jsx(Ze,{size:12}),f?n("computer.preview.connecting"):n("computer.open")]})]}),!x&&!w&&e.jsxs("div",{role:"status",className:"absolute inset-0 flex flex-col items-center justify-center gap-2 px-6 text-center text-[12px] text-ink-secondary",children:[e.jsx(A,{size:18,className:"animate-spin"}),S?n("computer.phase.starting"):n("computer.preview.connectingScreen")]}),x&&k&&!w&&e.jsxs("div",{role:"status",className:"absolute bottom-2 left-2 flex items-center gap-1 rounded-md bg-black/70 px-2 py-1 text-[11px] text-white",children:[e.jsx(A,{size:12,className:"animate-spin"}),n("computer.preview.connectingScreen")]}),w&&e.jsxs("div",{role:"alert",className:`absolute inset-x-0 flex flex-col items-center justify-center gap-2 bg-card/95 p-4 text-center text-[12px] text-ink-secondary ${x?"bottom-0":"inset-y-0"}`,children:[!x&&e.jsx(De,{size:22}),e.jsxs("span",{children:[x?n("computer.preview.paused"):n("computer.preview.cantConnect")," ",w]}),e.jsx("button",{type:"button",onClick:()=>P(!x),className:"rounded-md bg-control px-3 py-1.5 text-ink hover:bg-raised-hover",children:n("computer.preview.retry")})]})]})}function Ks({bot:s,backend:i,onBackend:d,onAutoStart:S}){return e.jsxs("div",{"data-testid":"vps-choices",children:[e.jsx(Ln,{compact:!0,value:i,onChange:d}),!s.computer&&e.jsxs("div",{className:"mt-3 flex items-center justify-between gap-4 rounded-lg bg-inset px-3 py-2.5",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[13px] text-ink",children:n("botAccess.cloud.startVps")}),e.jsx("div",{className:"mt-0.5 text-[12px] text-ink-secondary",children:n("botAccess.cloud.startVpsDescription")})]}),e.jsx(zn,{checked:!!s.autoStartVps,"aria-label":n("botAccess.cloud.startVps"),onClick:S})]})]})}const Us={available:!1,devices:[]};function Hs(){const s=window.ogb?.androidDevice,[i,d]=a.useState(Us),[S,f]=a.useState(!1),v=Bt();return a.useEffect(()=>{if(!s){f(!0);return}if(!v)return;let k=!0,j=0,y=0;const P=async()=>{const m=++j,h=()=>m<y;try{const g=await s.status();k&&!h()&&(y=m,d(g))}catch(g){k&&!h()&&(y=m,d({available:!1,devices:[],reasonCode:"adb-failed",message:g instanceof Error?g.message:String(g)}))}finally{k&&!h()&&f(!0)}};P();const u=window.setInterval(()=>{P()},2e3);return()=>{k=!1,window.clearInterval(u)}},[s,v]),{...i,scanned:S}}function ct(s){return s.model==="Android device"?s.serial:s.model}function qs({status:s}){const i=window.ogb?.androidDevice,d=Bt(),S=s.devices.filter(p=>p.state==="device"),[f,v]=a.useState(S[0]?.serial??s.devices[0]?.serial??""),[k,j]=a.useState(null),[y,P]=a.useState({width:0,height:0}),[u,m]=a.useState(null),h=a.useRef(null),g=a.useRef(null),x=a.useRef({x:0,y:0,timer:null}),w=s.devices.find(p=>p.serial===f)??s.devices[0],$=w?.serial,E=w?.state;a.useEffect(()=>{!w&&s.devices[0]&&v(s.devices[0].serial),w&&!s.devices.some(p=>p.serial===w.serial)&&v(s.devices[0]?.serial??"")},[w,s.devices]),a.useEffect(()=>{if(!i||!$||E!=="device"||!d){if(!d)return;j(null);return}let p=!0,C=null;const V=async()=>{try{const _=await i.frame($);p&&(j(_.dataUrl),m(null))}catch(_){p&&m(_ instanceof Error?_.message:String(_))}finally{p&&(C=window.setTimeout(()=>{V()},850))}};return V(),()=>{p=!1,C!==null&&window.clearTimeout(C)}},[i,$,E,d]),a.useEffect(()=>()=>{x.current.timer&&clearTimeout(x.current.timer)},[]);const D=p=>{!i||!w||w.state!=="device"||i.input(w.serial,p).catch(C=>{m(C instanceof Error?C.message:String(C))})},B=(p,C=!1)=>{if(!h.current||!y.width||!y.height)return null;const _=p.currentTarget.getBoundingClientRect(),L=Math.min(_.width/y.width,_.height/y.height),Y=y.width*L,J=y.height*L,G=_.left+(_.width-Y)/2,Le=_.top+(_.height-J)/2,Ce=(p.clientX-G)/Y,te=(p.clientY-Le)/J;return C?{x:Math.max(0,Math.min(1,Ce)),y:Math.max(0,Math.min(1,te))}:Ce>=0&&Ce<=1&&te>=0&&te<=1?{x:Ce,y:te}:null},ye=p=>{if(p.metaKey||p.ctrlKey||p.altKey)return;const C={ArrowDown:"down",ArrowLeft:"left",ArrowRight:"right",ArrowUp:"up",Backspace:"delete",Delete:"delete",Enter:"enter",Escape:"back",Tab:"tab"};C[p.key]?(p.preventDefault(),D({type:"key",key:C[p.key]})):/^[A-Za-z0-9 _.,@-]$/.test(p.key)&&(p.preventDefault(),D({type:"text",text:p.key}))},me=p=>{if(!y.width||!y.height)return;p.preventDefault();const C=x.current;C.x+=p.deltaX,C.y+=p.deltaY,C.timer&&clearTimeout(C.timer),C.timer=setTimeout(()=>{const V=Math.abs(C.x)>Math.abs(C.y),_=V?C.x:C.y;if(C.x=0,C.y=0,C.timer=null,Math.abs(_)<2)return;const L=Math.max(.18,Math.min(.45,Math.abs(_)/500)),Y=_>0?-1:1,J=V?{x:.5,y:.5}:{x:.5,y:.65},G=V?{x:J.x+Y*L,y:J.y}:{x:J.x,y:J.y+Y*L};D({type:"swipe",fromX:J.x,fromY:J.y,toX:G.x,toY:G.y,durationMs:260,width:y.width,height:y.height})},80)};if(!w)return null;const r=w.state==="device";return e.jsxs("div",{className:"space-y-3 pb-5",children:[e.jsxs("div",{className:"rounded-xl bg-card p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 text-[15px] font-medium text-ink",children:[e.jsx(An,{size:16,className:"text-success"})," ",ct(w)]}),e.jsx("div",{className:"mt-1 text-[12px] leading-relaxed text-ink-secondary",children:n("computer.android.usbSubtitle")})]}),e.jsxs("span",{className:"flex shrink-0 items-center gap-1 text-[11px] text-success",children:[e.jsx(Er,{size:12})," ",n("computer.android.usb")]})]}),s.devices.length>1&&e.jsx(Pr,{value:w.serial,onChange:p=>v(p.target.value),className:"mt-3 w-full",children:s.devices.map(p=>e.jsxs("option",{value:p.serial,children:[ct(p)," · ",p.state]},p.serial))})]}),r?e.jsxs(e.Fragment,{children:[e.jsx("div",{role:"application","aria-label":n("computer.android.screenAria",{name:ct(w)}),tabIndex:0,onKeyDown:ye,onWheel:me,onPointerDown:p=>{const C=B(p);C&&(p.currentTarget.setPointerCapture(p.pointerId),g.current={point:C,at:performance.now()})},onPointerUp:p=>{const C=g.current,V=B(p,!0);if(g.current=null,!C||!V)return;Math.hypot(V.x-C.point.x,V.y-C.point.y)<.012?D({type:"tap",...V,...y}):D({type:"swipe",fromX:C.point.x,fromY:C.point.y,toX:V.x,toY:V.y,durationMs:performance.now()-C.at,...y}),p.currentTarget.focus()},onPointerCancel:()=>{g.current=null},className:"mx-auto flex h-[520px] w-full touch-none cursor-pointer items-center justify-center overflow-hidden overscroll-none rounded-[28px] bg-black outline-none ring-1 ring-white/10 focus:ring-2 focus:ring-accent",children:k?e.jsx("img",{ref:h,src:k,alt:n("computer.android.screenAlt",{name:ct(w)}),draggable:!1,onLoad:p=>{P({width:p.currentTarget.naturalWidth,height:p.currentTarget.naturalHeight})},className:"pointer-events-none h-full w-full select-none object-contain"}):e.jsx(A,{size:20,className:"animate-spin text-ink-secondary"})}),e.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[e.jsxs("button",{onClick:()=>D({type:"key",key:"back"}),className:"flex items-center justify-center gap-1.5 rounded-lg bg-raised py-2 text-[12px] text-ink hover:bg-raised-hover",children:[e.jsx(zr,{size:13})," ",n("computer.android.back")]}),e.jsxs("button",{onClick:()=>D({type:"key",key:"home"}),className:"flex items-center justify-center gap-1.5 rounded-lg bg-raised py-2 text-[12px] text-ink hover:bg-raised-hover",children:[e.jsx(Tr,{size:12})," ",n("computer.android.home")]}),e.jsxs("button",{onClick:()=>D({type:"key",key:"recent"}),className:"flex items-center justify-center gap-1.5 rounded-lg bg-raised py-2 text-[12px] text-ink hover:bg-raised-hover",children:[e.jsx(pt,{size:13})," ",n("computer.android.recent")]})]}),e.jsx("div",{className:"text-center text-[11px] leading-relaxed text-ink-secondary",children:n("computer.android.hint")})]}):e.jsx("div",{className:"rounded-xl border border-warning/25 bg-warning/10 p-4 text-[12px] leading-relaxed text-warning",children:w.state==="unauthorized"?n("computer.android.unauthorized"):n("computer.android.badState",{state:w.state})}),u&&e.jsx("div",{className:"rounded-lg border border-danger/30 bg-danger/10 px-3 py-2 text-[12px] text-danger",children:u}),e.jsxs("div",{className:"rounded-xl bg-card p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[13px] font-medium text-ink",children:[e.jsx(Bs,{size:15,className:"text-accent"})," ",n("computer.android.setupTitle")]}),e.jsxs("ol",{className:"mt-2 list-decimal space-y-1.5 pl-4 text-[12px] leading-relaxed text-ink-secondary",children:[e.jsx("li",{children:n("computer.android.step1")}),e.jsx("li",{children:n("computer.android.step2").split(/(\{buildNumber\}|\{usbDebugging\})/).map((p,C)=>p==="{buildNumber}"||p==="{usbDebugging}"?e.jsx("span",{className:"text-ink",children:n(p==="{buildNumber}"?"computer.android.buildNumber":"computer.android.usbDebugging")},C):p)}),e.jsxs("li",{children:[n("computer.android.step3a")," ",e.jsx("span",{className:"text-ink",children:n("computer.android.allowUsbDebugging")})," ",n("computer.android.step3b")]})]}),e.jsx("div",{className:"mt-2 text-[11px] leading-relaxed text-ink-secondary",children:n("computer.android.agentNote")}),e.jsx("div",{className:"mt-2 rounded-lg bg-inset px-3 py-2 text-[11px] leading-relaxed text-ink-secondary",children:n("computer.android.harnessNote")})]})]})}const Xs=1500,Ys=2e5,Mn=()=>Array.from(crypto.getRandomValues(new Uint8Array(18)),s=>s.toString(16).padStart(2,"0")).join("");function Gs(s,i){const d=window.setInterval(()=>{s.closed&&(window.clearInterval(d),i())},1e3)}async function Zs({botId:s,title:i,held:d,request:S,join:f,current:v}){let k=null,j=null;!window.ogb?.desktopViewer&&!window.ogb?.openExternal&&(j=window.open("","_blank"),j&&(j.opener=null));const y=()=>new DOMException("The selected conversation changed","AbortError");try{if(!d&&(k=Mn(),!(await S("take",k)).held))throw new O("computer.err.confirmControl");if(!v())throw y();const{joinUrl:P}=await f(AbortSignal.timeout(Ys)),u=typeof P=="string"&&P?P:null;if(!v())throw y();if(!u)throw new O("computer.err.noDesktopLink");if(window.ogb?.desktopViewer){if(!await window.ogb.desktopViewer.open(u,i,s))throw new O("computer.err.openDesktop")}else if(j){j.location.replace(u);const m=k;m&&Gs(j,()=>{S("release",m).catch(()=>{})})}else if(window.ogb?.openExternal){if(!await window.ogb.openExternal(u))throw new O("computer.err.openDesktopLink")}else if(!window.open(u,"_blank","noopener"))throw new O("computer.err.popupBlocked")}catch(P){throw j?.close(),k&&await S("release",k).catch(()=>{}),P}}function _t(s,i){fetch(s,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(i),keepalive:!0}).catch(()=>{})}function Js({botId:s,session:i,held:d,request:S,viewerClose:f}){const[v,k]=a.useState(!1),[j,y]=a.useState(!1),[P,u]=a.useState(!1),m=a.useRef(null),h=a.useRef(f);h.current=f;const g=a.useCallback(()=>{k(!1),y(!1)},[]),x=a.useCallback(()=>{const E=m.current;m.current=null,g(),E&&(_t(`/api/bots/${s}/computer/control`,{action:"release",controlLeaseId:E.id}),E.viewerClose&&_t(E.viewerClose,{}))},[s,g]),w=a.useCallback(async(E=!1)=>{const D=Mn(),B=await S("take",D);if(!B.held)throw new O("computer.err.confirmControl");m.current=B.owned?{id:D,viewerClose:h.current}:null,k(!0),y(E)},[S]),$=a.useCallback(async()=>{const E=m.current?.viewerClose??h.current;m.current=null,g(),u(!0);try{await S("release")}finally{u(!1),E&&_t(E,{})}},[g,S]);return a.useEffect(()=>x,[i,x]),a.useEffect(()=>(window.addEventListener("pagehide",x),()=>window.removeEventListener("pagehide",x)),[x]),a.useEffect(()=>{if(!v||d)return;const E=setTimeout(()=>{m.current=null,g()},Xs);return()=>clearTimeout(E)},[v,d,g]),{here:v,expanded:j,setExpanded:y,handingBack:P,take:w,handBack:$,leave:x}}function Qs({held:s,frame:i,name:d,disabled:S,takeDisabled:f,error:v,onTakeControl:k}){const[j,y]=a.useState(!1),P=a.useCallback(()=>y(!1),[]);return a.useEffect(()=>{s&&y(!1)},[s]),e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",onClick:()=>s?k(!0):y(!0),disabled:S,className:"flex flex-auto items-center justify-center gap-2 whitespace-nowrap rounded-lg bg-control px-3 py-2 text-[13px] text-ink hover:bg-raised-hover disabled:opacity-50",title:n(s?"computer.openLiveDesktop":"computer.watchFullScreenTitle"),children:[e.jsx(Ze,{size:14}),n("computer.fullScreen")]}),j&&!s&&e.jsx(ea,{frame:i,name:d,takeDisabled:f,error:v,onClose:P,onTakeControl:()=>k(!0)})]})}function ea({frame:s,name:i,takeDisabled:d,error:S,onClose:f,onTakeControl:v}){const k=a.useRef(null),j=a.useRef(null),{dragProps:y,noDragStyle:P}=Dn(),u=Je().capabilities.windowChrome==="mac-inset",m=a.useRef(null),[h,g]=a.useState(!1);Rs(k,f),a.useEffect(()=>j.current?.focus(),[]),a.useEffect(()=>{const $=E=>{E.key!=="Escape"||E.defaultPrevented||!(E.target instanceof Node)||!k.current?.contains(E.target)||(E.preventDefault(),E.stopPropagation(),f())};return window.addEventListener("keydown",$,!0),()=>window.removeEventListener("keydown",$,!0)},[f]),a.useEffect(()=>{const $=document.activeElement;d&&($===m.current||$===document.body)&&k.current?.focus()},[d]);const x="flex items-center gap-1.5 rounded-lg px-2.5 py-1.5 text-[12px] focus-visible:outline-2 focus-visible:outline-focus disabled:opacity-50",w=n("computer.screenOf",{name:i});return e.jsxs("div",{ref:k,tabIndex:-1,"data-watch-full-screen":!0,role:"dialog","aria-modal":"true","aria-label":w,className:"fixed inset-0 z-[65] flex flex-col bg-app outline-none",children:[e.jsxs("header",{...y,className:K("flex shrink-0 flex-wrap items-center gap-2 border-b border-hairline/40 bg-panel px-3 py-2",u&&"pl-[86px]"),children:[e.jsx("span",{className:"min-w-0 truncate text-[13px] font-medium text-ink",children:w}),e.jsx("span",{className:"pointer-events-none rounded-full bg-black/70 px-2.5 py-1 text-[11px] font-medium text-white shadow-sm",children:n("computer.watchingBotWorks")}),e.jsxs("button",{ref:j,type:"button",style:P,onClick:f,"aria-label":n("desktopViewer.exitFullscreen"),className:K(x,"ml-auto bg-control text-ink hover:bg-raised-hover"),children:[e.jsx(Ar,{size:14,"aria-hidden":"true"}),e.jsx("span",{className:"max-sm:hidden",children:n("desktopViewer.exitFullscreen")})]}),e.jsxs("button",{ref:m,type:"button",style:P,onClick:()=>{g(!0),v()},disabled:d,className:K(x,"bg-accent font-medium text-accent-ink hover:brightness-110"),title:n("computer.takeControlTitle"),children:[e.jsx(Ye,{size:14,"aria-hidden":"true"}),n("computer.takeControl")]})]}),h&&S&&e.jsx("div",{role:"alert",className:"shrink-0 border-b border-danger/30 bg-danger/10 px-3 py-2 text-[12px] text-danger",children:S}),e.jsx("div",{className:"relative flex min-h-0 flex-1 items-center justify-center overflow-hidden bg-inset",children:s?e.jsx("img",{src:s,alt:w,className:"h-full w-full object-contain"}):e.jsxs("span",{role:"status",className:"flex items-center gap-2 text-[12px] text-ink-secondary",children:[e.jsx(A,{size:16,className:"animate-spin","aria-hidden":"true"}),n("computer.waitingFrame")]})})]})}function ut(s){for(const i of s?.getTracks()??[])i.stop()}function ta(s){const i=s instanceof DOMException?s.name:"";return i==="NotAllowedError"||i==="AbortError"?{ok:!1,phase:"cancelled",messageKey:"computer.screen.cancelled"}:i==="NotFoundError"||i==="NotReadableError"||i==="NotSupportedError"||i==="SecurityError"?{ok:!1,phase:"unavailable",messageKey:"computer.screen.unavailableNow"}:{ok:!1,phase:"error",messageKey:"computer.screen.error"}}async function na({beginIntent:s,getDisplayMedia:i}){try{if(!s())return{ok:!1,phase:"unavailable",messageKey:"computer.screen.unavailableWindow"};const d=await i({video:!0,audio:!1});return d.getVideoTracks().length===0?(ut(d),{ok:!1,phase:"unavailable",messageKey:"computer.screen.noVideoTrack"}):{ok:!0,stream:d}}catch(d){return ta(d)}}const Xe={idle:"computer.screen.idle",ended:"computer.screen.ended",unavailable:"computer.screen.unavailable"};function ra(){const{capabilities:s,ready:i}=Je(),d=s.screenPreview,S=s.host.platform==="linux",[f,v]=a.useState("idle"),[k,j]=a.useState(Xe.idle),[y,P]=a.useState(""),u=a.useRef(null),m=a.useRef(null),h=a.useRef(0),g=a.useCallback((E,D)=>{h.current+=1;const B=m.current;m.current=null,u.current&&(u.current.srcObject=null),ut(B),v(E),j(D)},[]);a.useEffect(()=>()=>{h.current+=1;const E=m.current;m.current=null,ut(E)},[]);const x=async()=>{if(!d.available||!window.ogb?.beginScreenPreviewIntent||!navigator.mediaDevices?.getDisplayMedia){v("unavailable"),j(Xe.unavailable);return}g("requesting","computer.screen.waiting");const E=h.current,D=await na({beginIntent:()=>window.ogb.beginScreenPreviewIntent(),getDisplayMedia:r=>navigator.mediaDevices.getDisplayMedia(r)});if(E!==h.current){D.ok&&ut(D.stream);return}if(!D.ok){v(D.phase),j(D.messageKey);return}const B=D.stream,ye=B.getVideoTracks()[0];m.current=B,P(ye.label),ye.addEventListener("ended",()=>{m.current===B&&g("ended",Xe.ended)},{once:!0});const me=u.current;if(!me){g("error","computer.screen.displayFailed");return}me.srcObject=B;try{await me.play()}catch{E===h.current&&m.current===B&&g("error","computer.screen.displayFailed");return}E!==h.current||m.current!==B||(v("streaming"),j("computer.screen.active"))};if(!S)return null;const w=y||n("computer.screen.selected"),$=f==="cancelled"||f==="ended"||f==="unavailable"||f==="error";return e.jsxs("section",{className:"mt-4 rounded-xl bg-card p-4","aria-labelledby":"local-preview-title",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{id:"local-preview-title",className:"text-[15px] font-medium text-ink",children:n("computer.screen.title")}),e.jsx("div",{className:"mt-0.5 text-[12px] leading-relaxed text-ink-secondary",children:n("computer.screen.subtitle")})]}),e.jsx("span",{className:"shrink-0 rounded-full bg-raised px-2 py-1 text-[10px] font-medium text-ink-secondary",children:n("computer.screen.badge")})]}),e.jsxs("div",{className:"relative mt-3 flex aspect-[16/10] items-center justify-center overflow-hidden rounded-lg bg-panel",children:[e.jsx("video",{ref:u,autoPlay:!0,muted:!0,playsInline:!0,"aria-label":n("computer.screen.videoAria"),className:f==="streaming"?"h-full w-full object-contain":"hidden"}),f!=="streaming"&&e.jsxs("div",{className:"flex flex-col items-center gap-2 px-6 text-center text-ink-secondary",children:[f==="requesting"?e.jsx(A,{size:18,className:"animate-spin"}):e.jsx(De,{size:22}),e.jsx("span",{className:"text-[12px]","aria-live":"polite",children:i?n(d.available?k:Xe.unavailable):n("computer.screen.checking")})]})]}),f==="streaming"&&e.jsxs("div",{className:"mt-2 flex items-center justify-between gap-3 text-[11px] text-ink-secondary",children:[e.jsx("span",{className:"truncate",title:w,children:d.interaction==="portal-picker"?w:n("vm.dest.local")}),e.jsxs("span",{className:"flex items-center gap-1.5 text-success",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-success"})," ",n("computer.screen.sharing")]})]}),e.jsxs("button",{type:"button",disabled:f==="requesting"||!d.available&&f!=="streaming",onClick:f==="streaming"?()=>g("idle",Xe.idle):()=>{x()},className:"mt-3 flex w-full items-center justify-center gap-2 rounded-lg bg-raised py-2 text-[13px] text-ink hover:bg-raised-hover disabled:cursor-not-allowed disabled:opacity-50",children:[f==="requesting"?e.jsx(A,{size:14,className:"animate-spin"}):f==="streaming"?e.jsx(Dr,{size:13}):$?e.jsx(pt,{size:14}):e.jsx(De,{size:14}),f==="requesting"?n("computer.screen.choosing"):f==="streaming"?n("computer.screen.stop"):$?n("computer.linux.tryAgain"):d.interaction==="portal-picker"?n("computer.screen.choose"):n("computer.screen.start")]})]})}const sa="https://github.com/leomieo/limix-bot/blob/main/docs/linux-desktop.md#enable-local-control",aa="https://github.com/leomieo/limix-bot/blob/main/docs/linux-desktop.md#omarchy-hyprland-experimental",oa="https://cua.ai/docs/cua-sdk/guides/omarchy";function ia(){const{capabilities:s}=Je(),i=s.localComputer,[d,S]=a.useState(null),[f,v]=a.useState(null);if(s.host.platform!=="linux")return null;const k=d!==null||i.status==="checking"||i.status==="starting",j=i.available,y=i.reasonCode==="linux-wayland-seat-safety-blocked",P=i.reasonCode==="linux-hyprland-plugin-required",u=i.compositor==="hyprland",m=s.host.session==="wayland",h=i.driverSource==="bundled",g=async x=>{if(window.ogb?.localControl){S(x),v(null);try{if((x==="disable"||x==="retry")&&!(await fetch("/api/local-computer/interrupt",{method:"POST"})).ok){v({key:"computer.linux.stopFailed"});return}await window.ogb.localControl[x]()}catch(w){v(w instanceof Error?w.message:String(w))}finally{S(null)}}};return e.jsxs("section",{className:"mt-4 rounded-xl bg-card p-4","aria-labelledby":"linux-local-control-title",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("div",{id:"linux-local-control-title",className:"flex items-center gap-2 text-[15px] font-medium text-ink",children:[e.jsx(Vs,{size:16,className:j?"text-success":"text-ink-secondary"}),n("computer.linux.title")]}),e.jsx("div",{className:"mt-1 text-[12px] leading-relaxed text-ink-secondary",children:u?n("computer.linux.metaOmarchy"):n("computer.linux.meta",{session:m?"Wayland":"Xorg"})})]}),e.jsx("span",{className:K("shrink-0 rounded-full px-2 py-1 text-[10px] font-medium",j?"bg-success/10 text-success":y?"bg-danger/10 text-danger":P||i.enabled?"bg-warning/10 text-warning":"bg-raised text-ink-secondary"),children:j?n("computer.linux.ready"):y?n("computer.linux.waylandBadge"):P?n("computer.linux.pluginBadge"):i.enabled?n("vm.state.attention"):n("vm.dest.off")})]}),y?e.jsx("div",{className:"mt-3 rounded-lg border border-danger/20 bg-danger/5 p-3",children:e.jsxs("div",{className:"flex gap-2 text-[12px] leading-relaxed text-ink-secondary",children:[e.jsx(Ge,{size:15,className:"mt-0.5 shrink-0 text-danger"}),e.jsxs("span",{children:[n("computer.linux.waylandBefore")," ",e.jsx("strong",{className:"font-medium text-ink",children:n("computer.linux.waylandXorg")})," ",n("computer.linux.waylandAfter")]})]})}):P?e.jsxs("div",{className:"mt-3 rounded-lg border border-warning/20 bg-warning/5 p-3","data-linux-hyprland-plugin-required":!0,children:[e.jsxs("div",{className:"flex gap-2 text-[12px] leading-relaxed text-ink-secondary",children:[e.jsx(Ge,{size:15,className:"mt-0.5 shrink-0 text-warning"}),e.jsx("span",{children:n("computer.linux.hyprlandPlugin")})]}),e.jsxs("button",{type:"button",onClick:()=>window.open(oa,"_blank","noopener,noreferrer"),className:"mt-2 flex items-center gap-1.5 text-[12px] font-medium text-accent hover:underline",children:[n("computer.linux.omarchyGuide")," ",e.jsx(Cn,{size:11})]})]}):i.enabled?e.jsxs("div",{className:"mt-3 rounded-lg bg-panel p-3 text-[12px] text-ink-secondary",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[j?e.jsx(Lr,{size:15,className:"mt-0.5 shrink-0 text-success"}):k?e.jsx(A,{size:15,className:"mt-0.5 shrink-0 animate-spin"}):e.jsx(Ge,{size:15,className:"mt-0.5 shrink-0 text-warning"}),e.jsx("span",{"aria-live":"polite",children:j?n(u?"computer.linux.hyprlandReady":"computer.linux.readyMsg"):i.message??n("computer.linux.checking")})]}),i.driverPath&&e.jsxs("div",{className:"mt-2 break-all font-mono text-[10px] text-ink-tertiary",title:i.driverPath,children:[h?n("computer.linux.bundledDriver"):i.driverPath,i.driverVersion?` · ${i.driverVersion}`:""]})]}):e.jsx("div",{className:"mt-3 rounded-lg border border-warning/20 bg-warning/5 p-3",children:e.jsxs("div",{className:"flex gap-2 text-[12px] leading-relaxed text-ink-secondary",children:[e.jsx(Ge,{size:15,className:"mt-0.5 shrink-0 text-warning"}),e.jsxs("span",{children:[n("computer.linux.enableBefore")," ",e.jsx("strong",{className:"font-medium text-ink",children:n("vm.dest.local")})," ",n("computer.linux.enableAfter"),m&&!u&&` ${n("computer.linux.waylandInput")}`]})]})}),f&&e.jsx("div",{className:"mt-2 text-[12px] text-danger",children:typeof f=="string"?f:n(f.key)}),!y&&e.jsx("div",{className:"mt-3 flex gap-2",children:P?e.jsxs("button",{type:"button",disabled:k,onClick:()=>{g("enable")},className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-raised py-2 text-[13px] text-ink hover:bg-raised-hover disabled:opacity-50",children:[d==="enable"?e.jsx(A,{size:14,className:"animate-spin"}):e.jsx(pt,{size:14}),n("computer.linux.tryAgain")]}):i.enabled?e.jsxs(e.Fragment,{children:[!j&&e.jsxs("button",{type:"button",disabled:k,onClick:()=>{g("retry")},className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-raised py-2 text-[13px] text-ink hover:bg-raised-hover disabled:opacity-50",children:[d==="retry"?e.jsx(A,{size:14,className:"animate-spin"}):e.jsx(pt,{size:14}),n("computer.linux.tryAgain")]}),e.jsxs("button",{type:"button",disabled:d!==null,onClick:()=>{g("disable")},className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-raised py-2 text-[13px] text-ink hover:bg-raised-hover disabled:opacity-50",children:[d==="disable"?e.jsx(A,{size:14,className:"animate-spin"}):e.jsx(mt,{size:14}),n("computer.linux.disable")]})]}):e.jsxs("button",{type:"button",disabled:k,onClick:()=>{g("enable")},className:"flex flex-1 items-center justify-center gap-2 rounded-lg bg-accent py-2 text-[13px] font-medium text-white hover:opacity-90 disabled:opacity-50",children:[d==="enable"?e.jsx(A,{size:14,className:"animate-spin"}):e.jsx(mt,{size:14}),n("computer.linux.enable")]})}),e.jsxs("button",{type:"button",onClick:()=>window.open(u?aa:sa,"_blank","noopener,noreferrer"),className:"mt-2 flex w-full items-center justify-center gap-1.5 rounded-lg py-1.5 text-[11px] text-ink-secondary hover:bg-raised hover:text-ink",children:[s.host.packaged?n("computer.linux.guide"):n("computer.linux.driverSetup")," ",e.jsx(Cn,{size:11})]})]})}function la(){const{capabilities:s}=Je(),[i,d]=a.useState(!1),[S,f]=a.useState(null),v=s.localComputer;if(s.host.platform!=="win32"||v.reasonCode==="remote-server"||v.available)return null;const k=async()=>{d(!0),f(null);try{await window.ogb?.localControl?.retry()}catch(j){f(j instanceof Error?j.message:String(j))}finally{d(!1)}};return e.jsx("section",{"data-windows-local-control":v.reasonCode??"unavailable",className:"mt-4 rounded-xl border border-warning/25 bg-warning/10 p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Fs,{size:16,className:"mt-0.5 shrink-0 text-warning","aria-hidden":"true"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-[14px] font-medium text-ink",children:n("computer.windows.title")}),e.jsxs("p",{className:"mt-1 text-[13px] leading-relaxed text-ink-secondary",children:[n("computer.windows.body"),v.reasonCode==="cua-driver-blocked"&&e.jsxs(e.Fragment,{children:[" ",n("computer.windows.blocked")]})]}),v.message&&e.jsxs("details",{className:"mt-2 text-[12px] text-ink-secondary",children:[e.jsx("summary",{className:"cursor-pointer",children:n("computer.windows.detail")}),e.jsx("p",{className:"mt-1 break-words",children:v.message})]}),S&&e.jsxs("div",{role:"alert",className:"mt-2 flex gap-1.5 text-[12px] text-danger",children:[e.jsx(Ge,{size:13,className:"mt-0.5 shrink-0","aria-hidden":"true"}),e.jsx("span",{children:S})]}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:e.jsxs("button",{type:"button",onClick:()=>{k()},disabled:i,className:"inline-flex items-center gap-1.5 rounded-lg bg-accent px-3 py-1.5 text-[13px] font-medium text-white hover:brightness-110 disabled:opacity-50",children:[i&&e.jsx(A,{size:13,className:"animate-spin","aria-hidden":"true"}),n(i?"computer.windows.starting":"computer.windows.start")]})})]})]})})}const ca={computer:{Icon:De,label:"computer.tab.computer"},routines:{Icon:Tn,label:"computer.tab.routines"},android:{Icon:An,label:"computer.tab.android"},browser:{Icon:Ft,label:"computer.tab.browser",tour:"computer-browser"},data:{Icon:Or,label:"computer.tab.data",tour:"computer-data"},files:{Icon:Mr,label:"computer.tab.files"}},Ne="outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-accent/60",xt=s=>`computer-panel-tabs-tab-${s}`,On=s=>`computer-panel-tabs-panel-${s}`,da=(s,i)=>({id:xt(s),role:"tab","aria-selected":i,"aria-controls":On(s),tabIndex:i?0:-1}),Se=s=>({role:"tabpanel",id:On(s),"aria-labelledby":xt(s),tabIndex:0});function ua(s){const i=s.currentTarget;Math.abs(s.deltaY)<=Math.abs(s.deltaX)||i.scrollWidth<=i.clientWidth||(i.scrollLeft+=s.deltaY)}function pa(s,i,d){if(s.ctrlKey||s.metaKey||s.altKey)return;const S=Math.max(0,i.findIndex(k=>xt(k)===s.target.id)),f=s.key==="ArrowRight"?1:s.key==="ArrowLeft"?-1:0,v=s.key==="Home"?i[0]:s.key==="End"?i[i.length-1]:f?i[(S+f+i.length)%i.length]:void 0;v&&(s.preventDefault(),d(v),document.getElementById(xt(v))?.focus())}function ma(s,i,d){const S=i.scanned&&i.devices.length===0&&i.reasonCode!=="adb-unavailable"&&i.reasonCode!=="adb-failed";a.useEffect(()=>{!S||$t(s)!=="android"||(d("computer"),dt(s,"computer"))},[s,S,d])}const Vn="omb-computer-panel-width",bt=360,ft=960,xa=400,Rn=40;function ba(){try{const s=Number(localStorage.getItem(Vn));if(Number.isFinite(s)&&s>=bt&&s<=ft)return s}catch{}return xa}function fa(){const[s,i]=a.useState(ba),d=a.useRef(null),S=h=>{try{localStorage.setItem(Vn,String(h))}catch{}},f=h=>{d.current={x:h.clientX,width:s},h.currentTarget.setPointerCapture(h.pointerId)},v=h=>{if(!d.current)return;const g=Math.min(ft,Math.max(bt,d.current.width+(d.current.x-h.clientX)));i(g)},k=h=>{d.current&&(d.current=null,h.currentTarget.releasePointerCapture(h.pointerId),S(s))},j=h=>{i(g=>{const x=Math.min(ft,Math.max(bt,g+h));return S(x),x})},y=a.useRef(null),[P,u]=a.useState(null);return a.useEffect(()=>{const h=y.current?.closest("aside");if(!h)return;const g=()=>u(h.offsetWidth);g();const x=new ResizeObserver(g);return x.observe(h),()=>x.disconnect()},[]),{panelWidth:s,separatorRef:y,separatorWidth:P,onSeparatorKeyDown:h=>{if(h.ctrlKey||h.metaKey||h.altKey)return;const g=h.key==="ArrowLeft"?Rn:h.key==="ArrowRight"?-Rn:null;g===null||P===null||(h.preventDefault(),j(g))},onResizeStart:f,onResizeMove:v,onResizeEnd:k}}const ha=a.lazy(()=>Pn(()=>import("./DataPanel-X1VUpw1U.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8])).then(s=>({default:s.DataPanel}))),_n=()=>Pn(()=>import("./LiveDesktop-B8KndeA2.js"),__vite__mapDeps([9,1,2,10,11,5,6,7,3,4])).then(s=>({default:s.LiveDesktop})),ga=a.lazy(_n),En=yr({held:yn().optional().default(!1),helpReason:kr().nullable().optional().default(null),help:wr().optional().transform(xs),owned:yn().optional()}).passthrough();function Oa({bot:s,onOpenVmWorkspace:i}){const{dragProps:d}=Dn(),{panelWidth:S,separatorRef:f,separatorWidth:v,onSeparatorKeyDown:k,onResizeStart:j,onResizeMove:y,onResizeEnd:P}=fa(),{state:u,dispatch:m,flushBotPatches:h}=Vr(),g=s.tasks?.find(t=>t.threadId===s.threadId),x=_r(s,g),w=Fr(g),$=$r(s),E=`${s.id}:${s.threadId}:${x}:${s.cloudBackend??"box"}:${$.modelSelection.instanceId}`,[D,B]=a.useState(null),ye=D?.key===E,me=x!=="auto"||ye,r={...$,computer:x==="auto"?ye?D.surface:void 0:x},p=`${r.id}:${r.threadId}:${r.computer}:${r.cloudBackend??"box"}`,C=a.useRef(p);C.current=p;const V=a.useRef(null);a.useEffect(()=>()=>V.current?.abort(),[p]);const _=!!r.busy,L=a.useCallback(t=>`/api/bots/${s.id}/${t}?threadId=${encodeURIComponent(s.threadId)}`,[s.id,s.threadId]),Y=s.computer==="cloud"&&x==="cloud",J=s.computer==="vm"&&x==="vm",{capabilities:G,ready:Le}=Je(),Ce=G.localComputer.available,te=G.host.platform==="linux",Me=Br(u.instances,r),Wt=Wr("local",u.config)&&Kr({capabilities:G,providerSupportsLocal:Me}),[Kt,gt]=a.useState(null),Ut=Ur({capabilities:G,providerSupportsLocal:Me}),Fn=Hr(u.config,G),[c,N]=a.useState("checking"),[Oe,Ht]=a.useState(null),[xe,ne]=a.useState(null),[vt,yt]=a.useState(null),T=r.cloudBackend??"box",Qe=!!(Oe&&Oe.botId===r.id&&Oe.computer===s.computer&&Oe.cloudBackend===T&&Oe.section===(r.section?.trim()??"")),U=!!(xe&&xe.botId===r.id&&xe.threadId===r.threadId&&xe.computer===r.computer&&xe.cloudBackend===T),we=U&&x==="auto"&&T==="box"&&vt?.botId===r.id&&vt.section===(r.section?.trim()??"")?vt:null,W=U&&qr({computer:r.computer,cloudBackend:T,phase:c,botId:r.id,resolvedBotId:xe?.botId??null,resolvedComputer:xe?.computer??null,resolvedCloudBackend:xe?.cloudBackend??null}),Ie=a.useCallback(t=>{ne(null),yt(null),N("checking"),m({type:"updateBot",botId:r.id,patch:t})},[r.id,m]);a.useEffect(()=>{let t=!0;return Ht(null),h(r.id).then(o=>{t&&(o&&!Xr({computer:s.computer,cloudBackend:T,persistedBot:o})||o&&(o.section?.trim()??"")!==(r.section?.trim()??"")||Ht({botId:r.id,computer:s.computer,cloudBackend:T,section:r.section?.trim()??""}))}),()=>{t=!1}},[r.id,s.computer,r.section,T,h]);const[Ve,ae]=a.useState(null),[wt,et]=a.useState(null),[$n,ce]=a.useState(null),[Bn,Re]=a.useState(!1),[qt,Wn]=a.useState(0),[Kn,kt]=a.useState(null),[H,_e]=a.useState(null),[Xt,jt]=a.useState(null),[Un,Yt]=a.useState(null),[R,oe]=a.useState(null),[ie,Ee]=a.useState(!1),[tt,Gt]=a.useState(!1),[nt,I]=a.useState(null),be=Sn(nt),Q=hr(),[Hn,Fe]=a.useState(()=>$t(r.id)),$e=u.dataResultFocus?.botId===r.id?u.dataResultFocus:void 0,[qn,Xn]=a.useState(),Nt=Hs(),St=Nt.devices.length>0,Zt=gs({advanced:Q,androidConnected:St}),M=ps(Hn,{advanced:Q,androidConnected:St}),Ct=Yr(s.id,M),Jt=Gr(u.config),fe=wn(u.config)&&r.browser!==!1&&(Jt||u.config?.browserEngine?.installable===!0),[Qt,Pe]=a.useState(0),[Yn,Gn]=a.useState(!1);a.useEffect(()=>{if(x!=="auto"||!Qe)return;const t=new AbortController;return B(null),F(L("computer"),{signal:t.signal}).then(o=>{if(t.signal.aborted)return;const l=o.surface;B({key:E,surface:l==="cloud"||l==="vm"||l==="local"||l==="browser"||l==="off"?l:void 0})}).catch(o=>{t.signal.aborted||(I(o instanceof Error?o:String(o)),N("error"))}),()=>t.abort()},[E,x,Qe,L,Qt]);const It=c==="vm-unavailable"&&H?.resumable===!0,Be=a.useRef(0),ke=a.useRef(null);a.useEffect(()=>(ke.current?.signal.aborted&&(ke.current=null,oe(null)),()=>{ke.current?.abort()}),[r.id,r.threadId,r.computer,M]);const rt=u.instances.find(t=>t.instanceId===r.modelSelection.instanceId),We=a.useRef(!1),st=t=>{We.current=!0,Fe(t),dt(r.id,t)},en=a.useRef(null),at=`${s.id}:${s.threadId}:${x}:${s.cloudBackend??"box"}`;a.useEffect(()=>{const t=en.current;t===at&&(We.current||!(r.computer==="browser"&&fe))||(t!==at&&(We.current=!1),en.current=at,Fe(r.computer==="browser"&&fe?"browser":t===null?$t(r.id):"computer"))},[at,r.id,r.computer,fe]),a.useEffect(()=>{!$e||$e.consumed||(We.current=!0,Xn($e),Fe("data"),dt(r.id,"data"),m({type:"dataResultFocusConsumed",requestId:$e.requestId}))},[r.id,m,$e]);const he=u.signInFocus?.botId===r.id?u.signInFocus:void 0,[Zn,Jn]=a.useState(),[Qn,er]=a.useState();Zr(r.id,t=>{st("browser"),er(t)}),a.useEffect(()=>{if(!he||he.consumed)return;const t=he.place==="browser"?"browser":"computer";We.current=!0,Fe(t),dt(r.id,t),t==="browser"&&Jn({url:he.url,site:he.site,nonce:he.requestId}),m({type:"signInFocusConsumed",requestId:he.requestId})},[r.id,m,he]),a.useEffect(()=>{let t=!0;const o=window.ogb?.desktopViewer;o?.currentState&&o.currentState().then(b=>{t&&Gt(b.open&&b.contextId===r.id)}).catch(()=>{});const l=o?.onState(b=>{b.contextId===r.id&&Gt(b.open)});return()=>{t=!1,l?.()}},[r.id]),ma(r.id,Nt,Fe),a.useEffect(()=>{Be.current=0},[r.id,r.computer]);const tn=!!(rt?.snapshot.state==="available"&&rt.capabilities?.computerMcp),Rt=jr(Nr(rt)),nn=u.routines.filter(t=>t.botId===r.id).sort((t,o)=>Number(o.enabled)-Number(t.enabled)||(t.nextRunAt??1/0)-(o.nextRunAt??1/0)),tr=!!(u.config?.box.configured&&Sr(u.instances,r.modelSelection.instanceId)?.snapshot.state==="available"),Ke=u.routineRuns.find(t=>t.botId===r.id&&["queued","running","waiting"].includes(t.status));a.useEffect(()=>{if(M!=="computer")return;let t=!0;if(ne(null),yt(null),N("checking"),et(null),ce(null),kt(null),_e(null),jt(null),Yt(null),I(null),!(!Qe||!me)){if(r.computer===void 0){N("auto-unavailable");return}if(r.computer==="off"){N("off");return}if(r.computer==="browser"){N("browser");return}if(r.computer==="local"){Me||I(new O("computer.err.localEngine")),N(Le&&Ce&&Me?"local":"local-unavailable"),ne({botId:r.id,threadId:r.threadId,computer:r.computer,cloudBackend:T});return}if(r.computer==="vm"){if(!tn){I(new O("computer.err.vmEngine")),N("vm-unavailable");return}let o;return F(L("local-computer")).then(l=>{if(!t)return;const b=l;if(ne({botId:r.id,threadId:r.threadId,computer:r.computer,cloudBackend:T}),_e(b),b.ready)Be.current=0,N("vm");else if(b.container==="running"&&b.imageMatches&&b.managed&&b.network==="loopback"&&b.security==="hardened"&&b.persistence==="durable"&&!b.desktopReady&&Be.current<15)Be.current+=1,I(null),N("checking"),o=window.setTimeout(()=>Pe(z=>z+1),2e3);else{const z=b.mode==="per-bot"&&b.container==="missing"&&b.image&&b.create_supported;I(z||b.resumable?null:new O("computer.err.vmOpenSettings",b.problem,"computer.err.vmNotReady")),N("vm-unavailable")}}).catch(l=>{t&&(I(l.message),N("vm-unavailable"))}),()=>{t=!1,o!==void 0&&window.clearTimeout(o)}}if(r.computer==="cloud"&&!Rt){N("error");return}if(!(r.computer!=="cloud"&&!Le))return T==="vps"?(F(L("computer")).then(o=>{if(!t)return;const l=o;if(jt(l),ne({botId:r.id,threadId:r.threadId,computer:r.computer,cloudBackend:T}),!l.configured){I(new O("computer.err.vpsAlias")),N("vps-unconfigured");return}if(l.ready){ae(l.container??null),N("ready");return}if(l.managed&&l.container!=="missing"&&!l.imageMatches){I(l.problem),N("vps-incompatible");return}if(Y)return N("starting"),F(`/api/bots/${r.id}/computer/provision`,{method:"POST"}).then(b=>{t&&(ae(b.container??null),b.ready?(ne({botId:r.id,threadId:r.threadId,computer:r.computer,cloudBackend:T}),N("ready")):(I(b.problem??new O("computer.err.vpsNotReady")),N("error")))});ae(l.container??null),I(r.autoStartVps?new O("computer.err.vpsAuto",l.problem,"computer.err.vpsNoContainer"):new O("computer.err.vpsManual",l.problem,"computer.err.vpsNoContainer")),N(l.container==="stopped"?"vps-stopped":"vps-unconfigured")}).catch(o=>{t&&(I(o.message),N("error"))}),()=>{t=!1}):(F(L("computer")).then(o=>{if(!t)return;const l=Jr({computer:x==="cloud"?"cloud":void 0,configured:!!o.configured,boatState:typeof o.box?.state=="string"?o.box.state:null,canUseCloud:Rt,autoLocal:!1,teamComputer:typeof o.teamComputer?.id=="string"&&typeof o.teamComputer?.name=="string",busy:s.busy});if(ne({botId:r.id,threadId:r.threadId,computer:r.computer,cloudBackend:T}),!o.configured&&r.computer==="cloud"&&!o.teamComputer){N("unconfigured");return}if(l==="team-boat"){yt({id:o.teamComputer.id,name:o.teamComputer.name,botId:r.id,section:r.section?.trim()??""}),ae(typeof o.box?.state=="string"?o.box.state:o.configured?"missing":"unavailable"),I(typeof o.problem=="string"?o.problem:null),N("team-boat");return}if(l==="attach-ready-boat"||r.computer==="cloud"&&l==="show-ready-boat"){ae(typeof o.box?.state=="string"?o.box.state:null),N("ready");return}ae(typeof o.box?.state=="string"?o.box.state:null),N(l)}).catch(o=>{t&&(I(o.message),N("error"))}),()=>{t=!1})}},[r.id,r.threadId,r.computer,r.section,r.autoStartVps,r.vpsAlias,T,Qt,Le,Wt,te,Me,rt?.driverKind,tn,Rt,u.config?.vps?.sshAlias,M,Qe,me,Y,x,L]),a.useEffect(()=>{if(c!=="busy-boat")return;let t=!0;const o=()=>{if(!s.busy&&x==="cloud"){Pe(b=>b+1);return}F(L("computer"),{background:!0}).then(b=>{if(!t)return;const z=typeof b.box?.state=="string"?b.box.state:null;ae(z),ms(z)&&N("ready")}).catch(()=>{})},l=window.setInterval(o,5e3);return()=>{t=!1,window.clearInterval(l)}},[c,L,s.busy,x]);const q=u.computerControl[r.id]??{held:!1,helpReason:null},ot=a.useCallback(async(t,o)=>{const l=En.parse(await F(`/api/bots/${r.id}/computer/control`,{method:"POST",body:JSON.stringify({action:t,...o?{controlLeaseId:o}:{}})}));return m({type:"computerControl",botId:r.id,held:l.held===!0,helpReason:l.helpReason,help:l.help}),l},[r.id,m]),ee=U?c==="vm"&&H?.viewer_url&&H.target_key?Rr({key:H.target_key}):W&&T==="vps"?`vps/${r.id}`:null:null,le=Js({botId:r.id,session:`${p}:${M}`,held:q.held,request:ot,viewerClose:ee?.startsWith("vps/")?L("computer/viewer-close"):null}),pe=le.here&&!!ee;a.useEffect(()=>{ee&&_n()},[ee]);const ze=Bt(),Te=a.useRef(0),Et=a.useRef(r.busy);a.useEffect(()=>{Et.current=r.busy},[r.busy]),a.useEffect(()=>{if(Te.current=0,!!W)return Qr({screens:!0,onFrame:t=>{t.kind!=="screen"||t.botId!==r.id||t.threadId!==r.threadId||(Te.current=Date.now(),et({png:t.png,mime:t.mime??"image/png"}),ce(null),Re(!1))}})},[W,r.id,r.threadId]),a.useEffect(()=>{if(M!=="computer"||!W||tt||pe||!ze||R||ie)return;let t=!1,o=-1/0,l=null,b=null;const z=new AbortController;ce(null),Re(!0);const se=async()=>{if(t||z.signal.aborted||Date.now()-o<(l??(Et.current?4e3:3e4))||Et.current&&Date.now()-Te.current<1e4)return;t=!0,l=null;const X=Date.now();try{const{png:Z,format:Ae}=await F(L("computer/screenshot"),{method:"POST",signal:AbortSignal.any([z.signal,AbortSignal.timeout(9e4)])});if(!z.signal.aborted&&Te.current<=X){if(typeof Z!="string"||!Z.trim())throw new O("computer.err.emptyFrame");et({png:Z,mime:Ae==="jpeg"?"image/jpeg":"image/png"}),ce(null),Re(!1),b=null}}catch(Z){if(!z.signal.aborted&&Te.current<=X)if(Z instanceof bs&&Cr(Z)){l=1e3,b??=Date.now();const Ae=Date.now()-b>=1e4;ce(Ae?Z:null),Re(!Ae)}else b=null,Re(!1),ce(Z instanceof Error&&Z.name==="TimeoutError"?new O("computer.err.frameTimeout"):Z instanceof Error?Z:new O("computer.err.screenUnavailable"))}finally{t=!1,o=Date.now()}};se();const ue=setInterval(se,1e3);return()=>{z.abort(),clearInterval(ue)}},[M,W,L,T,tt,pe,ze,R,ie,qt]),a.useEffect(()=>{if(M!=="computer"||c!=="vm"||!U||tt||pe||!ze)return;const t=new AbortController;let o=!1,l=-1/0,b=null,z=!0;const se=async()=>{if(!(o||t.signal.aborted)&&!(Date.now()-l<(b??(r.busy?3e3:3e4)))){o=!0,b=null;try{const{image:X}=await F(L("local-computer/screenshot"),{method:"POST",signal:t.signal});!t.signal.aborted&&typeof X=="string"&&(kt(X),ce(null))}catch(X){t.signal.aborted||(b=5e3,z?I(X instanceof Error?X.message:String(X)):ce(X instanceof Error?X:new O("computer.err.screenUnavailable")))}finally{o=!1,z=!1,l=Date.now()}}};se();const ue=window.setInterval(()=>{se()},r.busy?3e3:3e4);return()=>{t.abort(),window.clearInterval(ue)}},[M,c,U,L,tt,pe,ze,r.busy,I,ce,kt]);const[rn,Pt]=a.useState(0);a.useEffect(()=>{if(M!=="computer"||c!=="local"||!U||!window.ogb||te||!ze)return;let t=!0;Pt(0);const o=async()=>{try{const b=await window.ogb.screenFrame();t&&b?Yt(b):t&&Pt(z=>z+1)}catch{t&&Pt(b=>b+1)}};o();const l=setInterval(o,r.busy?3e3:3e4);return()=>{t=!1,clearInterval(l)}},[M,c,U,te,ze,r.busy,r.id,r.threadId]);const ge=U?c==="vm"?Kn:c==="local"&&!te?Un:W||r.computer==="cloud"&&c==="starting"?wt&&`data:${wt.mime};base64,${wt.png}`:null:null,nr=!!(ge&&(ee||W)),de=q.help??null,rr=de?u.bots.find(t=>t.id===de.botId)?.name??r.name:r.name;a.useEffect(()=>{let t=!0;return F(`/api/bots/${r.id}/computer/control`).then(o=>{if(!t)return;const l=En.parse(o);m({type:"computerControl",botId:r.id,held:l.held===!0,helpReason:l.helpReason,help:l.help})}).catch(()=>{}),()=>{t=!1}},[r.id]);const sn=a.useCallback(async()=>!0,[]),an=a.useCallback(async t=>es({action:t,syncNativeBrowser:M!=="browser",requestControl:ot,setNativeBrowserControl:sn}),[M,ot,sn]),sr=a.useCallback(async t=>{Ee(!0),I(null);try{return await an(t),!0}catch(o){return I(o instanceof Error?o.message:String(o)),!1}finally{Ee(!1)}},[an]),it=!!(de&&de.place!=="browser"&&de.place!=="local"&&(W||c==="vm"||we)),on=t=>de&&e.jsx(ys,{help:de,askerName:rr,takeControl:t&&{onClick:t,disabled:ie||R==="join",pending:R==="join"},onError:I}),ar=async()=>{const t=new AbortController;V.current=t;const o=()=>!t.signal.aborted&&C.current===p;oe("join"),Ee(!0),I(null);try{await Zs({botId:r.id,title:n("computer.viewerTitle",{name:r.name}),held:q.held,request:ot,join:l=>F(L("computer/join"),{method:"POST",signal:AbortSignal.any([t.signal,l])}),current:o})}catch(l){o()&&I(l instanceof Error?l:String(l))}finally{V.current===t&&(V.current=null,oe(null),Ee(!1))}},zt=R==="join"||c==="vm"&&!ee,ve=async(t=!1)=>{if(!ee)return W?ar():void 0;if(le.here)return le.setExpanded(t||le.expanded);Ee(!0),I(null);try{await le.take(t)}catch(o){I(o instanceof Error?o:String(o))}finally{Ee(!1)}},ln=async()=>{I(null),window.ogb?.desktopViewer?.close(r.id),await le.handBack().catch(t=>I(t instanceof Error?t:String(t)))},Tt=t=>{oe(t),I(null),F(`/api/bots/${r.id}/computer/${t}`,{method:"POST"}).then(o=>{t==="provision"&&(ae(o.container??null),o.ready?(r.computer==="cloud"&&ne({botId:r.id,threadId:r.threadId,computer:r.computer,cloudBackend:T}),N("ready")):(I(o.problem??new O("computer.err.vpsNotReady")),N("error"))),t==="sleep"&&(ne(null),ae(T==="vps"?"stopped":"archived"),N(T==="vps"?"vps-stopped":Y?"cloud-asleep":"show-sleeping-boat"))}).catch(o=>{I(o.message)}).finally(()=>oe(null))},or=()=>{oe("provision"),I(null),N("starting"),F(`/api/bots/${r.id}/computer/provision`,{method:"POST"}).then(t=>{ae(t.state??null),ne({botId:r.id,threadId:r.threadId,computer:r.computer,cloudBackend:T}),N("ready")}).catch(t=>{if(Ir(t)){N("busy-boat");return}I(t.message),N("error")}).finally(()=>oe(null))},At=async t=>{if((t==="vm-recreate"||t==="vm-delete")&&!window.confirm(t==="vm-delete"?n("computer.confirm.deleteVm",{name:r.name}):n("computer.confirm.replaceVm",{name:r.name}))||ke.current)return;const o=new AbortController;ke.current=o,oe(t),I(null),Be.current=0;try{if((t==="vm-recreate"||t==="vm-delete")&&await F(`/api/bots/${r.id}/local-computer/remove`,{method:"POST",body:"{}",signal:o.signal}),t!=="vm-delete"){const l=t==="vm-start"&&H?.mode!=="per-bot"?"/api/local-computer/start":`/api/bots/${r.id}/local-computer/${t==="vm-start"?"start":"run"}`,b=await F(l,{method:"POST",body:"{}",signal:o.signal}),z=await Ss(b,()=>F(L("local-computer"),{signal:o.signal}),o.signal);if(z.container==="stopped"&&z.capacity_limited){_e(z),N("vm-unavailable");return}if(!z.ready)throw new Error(z.problem??n("computer.err.vmNotReady"));_e(z),N("vm")}else _e(l=>l&&{...l,container:"missing",ready:!1}),N("vm-unavailable")}catch(l){if(o.signal.aborted)return;I(l instanceof Error?l.message:String(l)),N("vm-unavailable")}finally{ke.current===o&&!o.signal.aborted&&(ke.current=null,oe(null),Pe(l=>l+1))}},ir=async()=>{if(window.confirm(n("computer.confirm.replaceVps",{name:r.name}))){oe("vps-replace"),I(null);try{await F(`/api/bots/${r.id}/computer/remove`,{method:"POST",body:"{}"});const t=await F(`/api/bots/${r.id}/computer/provision`,{method:"POST",body:"{}"});jt(t),ae(t.container??null),t.ready&&r.computer==="cloud"&&ne({botId:r.id,threadId:r.threadId,computer:r.computer,cloudBackend:T}),N(t.ready?"ready":"error"),t.ready||I(t.problem??new O("computer.err.vpsReplaceNotReady"))}catch(t){I(t instanceof Error?t.message:String(t)),N("error")}finally{oe(null),Pe(t=>t+1)}}},cn=()=>{window.sessionStorage.setItem("openmausbot.settings.section","computer"),m({type:"toggleAppSettings",open:!0})},dn=()=>m(ws("vps")),un=U&&(c==="vps-unconfigured"||c==="vps-stopped"||c==="vps-incompatible"),pn=U&&Y&&(c==="vps-stopped"||c==="vps-unconfigured"&&!!Xt?.configured),mn=U&&Y&&c==="vps-incompatible"&&!!Xt?.managed,Dt=Jt||u.config?.browserEngine?.installable===!0,[xn,bn]=a.useState(!1),fn=async()=>{if(!xn){bn(!0),I(null);try{if(!wn(u.config)){const t=await F("/api/config",{method:"PATCH",body:JSON.stringify({features:{browser:!0}})});m({type:"configStatus",config:t})}s.browser===!1&&m({type:"updateBot",botId:s.id,patch:{browser:!0}})}catch(t){I(t instanceof Error?t.message:n("settings.experimental.error"))}finally{bn(!1)}}},lr=()=>{I(null),m({type:"updateBot",botId:s.id,patch:{browser:!1}})},hn=e.jsxs("div",{"data-testid":"browser-switch-row",className:"mb-3 flex items-center gap-3 rounded-xl bg-card px-3 py-2.5",children:[e.jsx(Ft,{size:15,className:"shrink-0 text-ink-secondary","aria-hidden":"true"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-[13px] font-medium text-ink",children:n("computer.browserSwitch.title",{name:r.name})}),!Dt&&e.jsx("div",{className:"text-[12px] text-ink-secondary",children:kn(u.config)})]}),e.jsx(zn,{checked:fe,disabled:xn||!fe&&!Dt,"aria-label":n("computer.browserSwitch.title",{name:r.name}),onClick:()=>fe?lr():void fn()})]}),cr=u.config?.managedPolicy,Lt=ts(Ve,s.busy===!0),dr=!U||x!=="cloud"||T!=="box"?void 0:c==="starting"?"starting":c==="busy-boat"?Lt.spinner?"starting":Lt.line==="computer.cloud.asleep"?"asleep":"none":c==="ready"?"on":Ve==="archived"||Ve==="stopped"?"asleep":void 0,Ue=(t,o)=>fs({...hs({bot:r,place:t,seat:Fn,config:u.config,instances:u.instances,local:{ready:Wt,reason:Ut??n("computer.unavailableLocal")},...t==="cloud"?{computer:dr}:{},...t==="auto"&&we?{teamComputer:we.name}:{}}),...o?{refusal:o}:{}}),Mt=r.computer==="cloud"&&T==="box"&&c==="error"&&nt&&!(nt instanceof O)?ns({message:be??"",status:Number(nt.status??0)||void 0},u.config?.box?.included===!0):void 0,re=Ue("cloud",Mt),je=Ue("auto"),ur=rs(G),He=Ps(u.config,G).map(([t,o,l,b])=>{const z=zs(t,s.computer,G),se=Ts(t,s.cloudBackend,cr),ue=t===null?je:t==="cloud"?re:Ue(t),X=!!se||jn(ue),Z=!se&&ss(ue),Ae=se??(Z?ue.line:t==="browser"?n("computer.browserOnlyTitle"):void 0);return{mode:t,labelKey:o,descriptionKey:l,Icon:b,simpleLabel:as(t??void 0,G.host.platform),selected:z,managedBy:se,disabled:X,unavailableTitle:Ae,view:ue,issue:Z}}),lt=He.find(({selected:t})=>t)?.view??je,pr=t=>{if(t==="start"||t==="wake")return or();if(t==="try-again")return Pe(o=>o+1);if(t==="turn-on-browser")return void fn();if(t==="open-vm-settings")return cn();js(t,{botId:s.id,threadId:s.threadId},m)},mr=t=>!!t&&t!=="watch"&&t!=="open-computer-panel"&&(t!=="start"&&t!=="wake"||Y&&!s.busy),qe=(t,o="mt-1 rounded-lg bg-control px-3 py-1.5 text-[12px] text-ink hover:bg-raised-hover")=>t.action&&mr(t.action.id)?e.jsx("button",{type:"button","data-testid":"place-action",onClick:()=>pr(t.action.id),className:o,children:t.action.label}):null,gn=t=>{t===null&&s.computer===void 0||t===s.computer||(t==="local"&&ks(s)==="auto"?gt(r.id):Ie(t==="browser"?{computer:t,browser:!0}:{computer:t}))},xr=()=>{s.computer==="local"&&ur&&Ie({computer:null}),m({type:"updateTask",botId:s.id,threadId:s.threadId,patch:{surface:null}})},Ot=w&&s.computer!=="off"&&w!==s.computer?w:void 0,br=t=>K("flex shrink-0 items-center gap-1.5 rounded-full px-3 py-1 text-[13px] transition-colors @max-[28rem]/paneltabs:[&>svg]:hidden @max-[22rem]/paneltabs:px-2",t?"bg-raised text-ink shadow-sm":"text-ink-secondary hover:text-ink"),vn=t=>{t==="browser"&&I(null),st(t)},fr={checking:n("computer.phase.checking"),starting:T==="vps"?n("computer.phase.starting"):re.line,"busy-boat":re.line,unconfigured:re.line,"auto-unavailable":je.line,"team-boat":je.line,"show-ready-boat":n("computer.phase.showReadyBoat"),"show-sleeping-boat":n("computer.phase.showSleepingBoat"),"show-pending-boat":n("computer.phase.showPendingBoat"),"cloud-new":re.line,"cloud-asleep":re.line,"vps-unconfigured":n("computer.phase.vpsUnconfigured"),"vps-incompatible":n("computer.phase.vpsIncompatible"),"vps-stopped":n("computer.phase.vpsStopped"),"local-unavailable":Ut??n("computer.phase.localUnavailable"),"vm-unavailable":n("computer.phase.vmUnavailable"),browser:Ue("browser").line,off:Ue("off").line,error:r.computer==="cloud"&&(Mt||jn(re))?re.line:n("computer.phase.error")};return e.jsxs(e.Fragment,{children:[e.jsxs("aside",{className:K("animate-panel-in relative flex h-full shrink-0 flex-col border-l border-hairline/40 bg-panel","max-md:absolute max-md:inset-0 max-md:z-40 max-md:w-full!"),ref:Ct,"data-computer-panel":!0,style:{width:S},children:[e.jsx("div",{ref:f,role:"separator","aria-orientation":"vertical","aria-label":n("computer.resizeAria"),"aria-valuemin":bt,"aria-valuemax":ft,"aria-valuenow":v??void 0,tabIndex:0,onKeyDown:k,onPointerDown:j,onPointerMove:y,onPointerUp:P,onPointerCancel:P,className:"absolute inset-y-0 left-0 z-10 w-1.5 cursor-col-resize hover:bg-accent/40 focus-visible:bg-accent/60 max-md:hidden"}),e.jsx("div",{...d,className:"@container/paneltabs ml-1.5 py-3 pl-2.5 pr-4",children:e.jsxs("div",{className:"relative flex min-h-7 items-center justify-center",children:[Q&&e.jsx("button",{onClick:()=>{Nn(Ct.current,r.id),m({type:"toggleComputer",open:!1}),m({type:"toggleSettings",open:!0,section:"access"})},className:"absolute left-0 top-1/2 -translate-y-1/2 rounded-md p-1 text-ink-secondary hover:bg-control hover:text-ink",title:n("computer.botSettings"),children:e.jsx(os,{size:18})}),e.jsx("div",{className:"mx-9 flex min-w-0 touch-pan-x gap-0.5 overflow-x-auto whitespace-nowrap rounded-full bg-inset p-1 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden","data-tour":"computer-tabs","data-testid":"computer-tabs",role:"tablist","aria-label":n("computer.tabsAria"),onWheel:ua,onKeyDown:t=>pa(t,Zt,vn),children:Zt.map(t=>{const{Icon:o,label:l,tour:b}=ca[t],z=_?t==="computer"&&vs(x)?"computer-tab-live":t==="browser"&&x==="browser"?"browser-tab-live":void 0:void 0;return e.jsxs("button",{type:"button","data-tour":b,...da(t,t===M),title:n(l),onClick:()=>vn(t),className:br(t===M),children:[e.jsx(o,{size:13})," ",n(l),z&&e.jsx("span",{className:"size-1.5 animate-pulse rounded-full bg-success",role:"img","aria-label":n("place.live"),"data-testid":z})]},t)})}),e.jsx("button",{"data-computer-panel-close":!0,onClick:()=>{Nn(Ct.current,r.id),m({type:"toggleComputer",open:!1})},className:"absolute right-0 top-1/2 -translate-y-1/2 rounded-md p-1 text-ink-secondary hover:bg-control hover:text-ink","aria-label":n("computer.close"),title:n("computer.close"),children:e.jsx(gr,{size:18})})]})}),M==="routines"?e.jsx("div",{...Se("routines"),className:K("min-h-0 flex-1 overflow-y-auto px-4 pb-4",Ne),children:e.jsx(Cs,{bot:r,routines:nn,runs:u.routineRuns,defaultRunOn:tr?"cloud":"maus"},r.id)}):M==="browser"&&fe?e.jsxs("div",{...Se("browser"),className:K("flex min-h-0 flex-1 flex-col px-4 pb-4",Ne),children:[hn,de?.place==="browser"&&e.jsx("div",{className:"-mt-1 mb-3",children:on()}),e.jsx(Es,{bot:r,signIn:Zn,page:Qn}),be&&e.jsx("div",{role:"alert",className:"mt-2 rounded-lg border border-danger/30 bg-danger/10 px-3 py-2 text-[12px] text-danger",children:be})]}):M==="browser"?e.jsxs("div",{...Se("browser"),className:K("flex-1 overflow-y-auto px-5 pb-5",Ne),"data-testid":"browser-off",children:[hn,e.jsxs("div",{className:"mt-2 flex flex-col items-center gap-3 rounded-xl bg-card px-6 py-8 text-center",children:[e.jsx(Ft,{size:22,className:"text-ink-secondary","aria-hidden":"true"}),e.jsx("div",{className:"text-[14px] font-medium text-ink",children:n("computer.browserOff.title")}),e.jsx("p",{className:"text-[12px] leading-5 text-ink-secondary",children:Dt?n("computer.browserOff.body",{name:r.name}):kn(u.config)}),be&&e.jsx("div",{role:"alert",className:"w-full rounded-lg border border-danger/30 bg-danger/10 px-3 py-2 text-[12px] text-danger",children:be})]})]}):M==="data"?e.jsx("div",{...Se("data"),className:K("flex min-h-0 flex-1 flex-col overflow-hidden",Ne),children:e.jsx(a.Suspense,{fallback:e.jsx("div",{className:"flex flex-1 items-center justify-center text-[13px] text-ink-secondary",role:"status",children:n("data.loading")}),children:e.jsx(ha,{bot:r,requestedCard:qn},r.id)})}):M==="files"?e.jsx("div",{...Se("files"),className:K("flex min-h-0 flex-1 flex-col",Ne),children:e.jsx(Is,{bot:r})}):M==="android"&&St?e.jsx("div",{...Se("android"),className:K("flex-1 overflow-y-auto px-4 pt-2",Ne),children:e.jsx(qs,{status:Nt})}):e.jsxs("div",{...Se("computer"),className:K("flex-1 overflow-y-auto px-5 pb-5",Ne),children:[e.jsxs("div",{className:"mb-1.5 mt-2 flex items-center justify-between text-[13px] text-ink-secondary",children:[e.jsx("span",{children:n("computer.screenOf",{name:r.name})}),we&&e.jsx("span",{className:"text-[11px]",children:je.short}),c==="local"&&e.jsx("span",{className:"text-[11px]",children:n("computer.badge.local")}),pe&&e.jsxs("span",{className:"flex items-center gap-1.5 text-[11px] font-medium text-ink",children:[e.jsx("span",{className:"size-1.5 rounded-full bg-success"}),n("computer.inControl")]}),c==="vm"&&!pe&&e.jsx("span",{className:"text-[11px]",children:n("vm.dest.vm")}),(c==="show-ready-boat"||c==="show-sleeping-boat"||c==="show-pending-boat")&&e.jsx("span",{className:"text-[11px]",children:n("computer.badge.autoBoat")}),U&&r.computer==="cloud"&&T==="vps"&&(c==="ready"||c==="starting")&&!pe&&e.jsx("span",{className:"text-[11px]",children:n("computer.badge.vps")})]}),e.jsx("div",{className:K("relative flex aspect-[16/10] w-full items-center justify-center overflow-hidden rounded-xl bg-card",pe&&"ring-2 ring-accent"),children:pe&&ee?e.jsx(a.Suspense,{fallback:e.jsx(A,{size:18,className:"animate-spin text-ink-secondary"}),children:e.jsx(ga,{target:ee,threadId:r.threadId,name:r.name,poster:ge,expanded:le.expanded,onExpandedChange:le.setExpanded,onHandBack:()=>{ln()},handingBack:le.handingBack,onUnreachable:()=>{le.leave(),I(new O("computer.err.openDesktop"))}})}):W||r.computer==="cloud"&&c==="starting"?e.jsx(Ws,{src:ge,name:r.name,error:Sn($n),refreshing:Bn,retry:qt,starting:c==="starting",opening:R==="join",disabled:ie,onOpen:()=>{ve()},onRetry:t=>{Te.current=0,t&&et(null),ce(null),Re(!0),Wn(o=>o+1)}},`${r.id}:${r.threadId}:${r.computer}:${T}`):ge&&nr?e.jsxs("button",{type:"button",onClick:()=>{ve()},disabled:ie||R==="join",className:"group relative flex h-full w-full cursor-pointer items-center justify-center focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent disabled:cursor-wait","aria-label":n("computer.openLiveDesktopAria",{name:r.name}),title:n("computer.openLiveDesktop"),children:[e.jsx("img",{src:ge,alt:n("computer.screenOf",{name:r.name}),className:"h-full w-full object-contain transition group-hover:brightness-75 group-focus-visible:brightness-75"}),e.jsxs("span",{className:"pointer-events-none absolute right-2 top-2 flex items-center gap-1 rounded-md bg-black/70 px-2 py-1 text-[11px] font-medium text-white opacity-80 shadow-sm transition group-hover:opacity-100 group-focus-visible:opacity-100",children:[R==="join"?e.jsx(A,{size:12,className:"animate-spin"}):e.jsx(Ze,{size:12}),n("computer.open")]})]}):ge?e.jsx("img",{src:ge,alt:n("computer.screenOf",{name:r.name}),className:"h-full w-full object-contain",title:c==="vm"?n("computer.watchOnly"):void 0}):e.jsxs("div",{className:"flex flex-col items-center gap-2 px-6 text-center text-ink-secondary",children:[c==="checking"||c==="starting"||c==="busy-boat"&&Lt.spinner||c==="vm"||c==="local"&&!te?e.jsx(A,{size:18,className:"animate-spin"}):c==="off"?e.jsx(mt,{size:22}):e.jsx(De,{size:22}),e.jsx("span",{className:"text-[12px]",children:we?je.line:W?n("computer.waitingFrame"):c==="ready"?n("computer.autoChooseCloudOpen"):c==="vm"?n("computer.capturingVm"):c==="local"?te?n("computer.linuxReady"):rn>=3?n("computer.needsScreenPerm"):n("computer.capturingLocal"):It?n(R==="vm-start"?"vm.setup.starting":"computer.phase.vmStopped"):fr[c]}),we&&qe(je),r.computer==="cloud"&&(c==="unconfigured"||c==="error")&&re.action?.id!=="add-boat-key"&&qe(re),c==="local"&&!te&&rn>=3&&e.jsx("button",{onClick:()=>window.ogb?.permOpenSettings?.("screen"),className:"mt-1 rounded-lg bg-control px-3 py-1.5 text-[12px] text-ink hover:bg-raised-hover",children:n("computer.openSettings")}),c==="browser"&&fe&&e.jsx("button",{onClick:()=>st("browser"),className:"mt-1 rounded-lg bg-control px-3 py-1.5 text-[12px] text-ink hover:bg-raised-hover",children:n("computer.openBrowserTab")}),(c==="show-ready-boat"||c==="show-sleeping-boat"||c==="show-pending-boat")&&e.jsx("button",{type:"button",onClick:()=>Ie({computer:"cloud"}),className:"mt-1 rounded-lg bg-control px-3 py-1.5 text-[12px] text-ink hover:bg-raised-hover",children:c==="show-sleeping-boat"?n("computer.chooseCloudWake"):c==="show-ready-boat"?n("computer.chooseCloudOpen"):n("computer.chooseCloudManage")}),R===null&&(c==="cloud-new"||c==="cloud-asleep")&&qe(re),It&&R!=="vm-start"&&e.jsx("p",{className:"text-[12px]",children:n(H?.stop_reason==="idle"?"vm.stopped.idle":"vm.stopped.detail")}),c==="vm-unavailable"&&(J&&It&&H.mode!=="pool"?e.jsxs("button",{onClick:()=>{At("vm-start")},disabled:R!==null,"aria-busy":R==="vm-start",className:"mt-1 flex items-center gap-1.5 rounded-lg bg-accent px-3 py-1.5 text-[12px] font-medium text-white hover:brightness-110 disabled:opacity-50",children:[R==="vm-start"&&e.jsx(A,{size:13,className:"animate-spin"}),n(R==="vm-start"?"vm.setup.starting":"vm.setup.start")]}):J&&H?.mode==="per-bot"&&H.image&&H.create_supported?e.jsxs("button",{onClick:()=>{At(H.container==="missing"?"vm-create":"vm-recreate")},disabled:R!==null,className:"mt-1 rounded-lg bg-accent px-3 py-1.5 text-[12px] font-medium text-white hover:brightness-110 disabled:opacity-50",children:[(R==="vm-create"||R==="vm-recreate")&&e.jsx(A,{size:13,className:"mr-1.5 inline animate-spin"}),H.container==="missing"?n("computer.createVm",{name:r.name}):n("computer.replaceVm",{name:r.name})]}):e.jsx("button",{onClick:cn,className:"mt-1 rounded-lg bg-control px-3 py-1.5 text-[12px] text-ink hover:bg-raised-hover",children:n("computer.openVmSetup")})),c==="vm-unavailable"&&H?.capacity_limited&&e.jsx("p",{className:"text-[12px] text-ink-secondary",children:is("Máy ảo đã được tạo và đang dừng vì đã đủ số máy chạy cùng lúc. Dừng một máy khác rồi bấm Bật.","This desktop has been created and is stopped because the running limit is full. Stop another desktop, then start this one.")}),!Q&&un&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-[12px]",children:n("computer.simple.needsSetup",{name:r.name})}),!pn&&!mn&&e.jsx("button",{type:"button",onClick:()=>vr(!0),className:"mt-1 rounded-lg bg-control px-3 py-1.5 text-[12px] text-ink hover:bg-raised-hover",children:n("computer.simple.showAdvanced")})]}),Q&&U&&(c==="vps-unconfigured"||c==="vps-stopped")&&e.jsx("button",{onClick:dn,className:"mt-1 rounded-lg bg-control px-3 py-1.5 text-[12px] text-ink hover:bg-raised-hover",children:n("computer.openVpsSettings")}),pn&&e.jsxs("button",{onClick:()=>Tt("provision"),disabled:R==="provision",className:"mt-1 rounded-lg bg-control px-3 py-1.5 text-[12px] text-ink hover:bg-raised-hover disabled:opacity-50",children:[R==="provision"&&e.jsx(A,{size:13,className:"mr-1.5 inline animate-spin"}),c==="vps-stopped"?n("computer.startVps"):n("computer.prepareVps")]}),mn&&e.jsxs("button",{onClick:()=>{ir()},disabled:R==="vps-replace",className:"mt-1 rounded-lg bg-accent px-3 py-1.5 text-[12px] font-medium text-white hover:brightness-110 disabled:opacity-50",children:[R==="vps-replace"&&e.jsx(A,{size:13,className:"mr-1.5 inline animate-spin"}),n("computer.replaceVps")]})]})}),be&&!Mt&&e.jsx("div",{className:"mt-2 rounded-lg border border-danger/30 bg-danger/10 px-3 py-2 text-[12px] text-danger",children:be}),(Yn||c==="unconfigured"&&re.action?.id==="add-boat-key")&&e.jsx("div",{"data-boat-key":!0,className:"mt-3 rounded-xl bg-card py-1.5",children:e.jsx(ls,{id:"box",via:"computer_panel",onSaved:t=>{Gn(!0),t&&Pe(o=>o+1)}})}),Q&&c==="vps-unconfigured"&&e.jsxs("div",{className:"mt-3 rounded-xl bg-card p-4",children:[e.jsx("div",{className:"mb-3 text-[13px] text-ink-secondary",children:n("computer.vpsAliasHint")}),e.jsx("button",{onClick:dn,className:"rounded-lg bg-control px-3 py-2 text-[13px] text-ink hover:bg-raised-hover",children:n("computer.openVpsSettings")})]}),Q&&c==="vm"&&H?.mode==="per-bot"&&window.ogb?.desktopWorkspace&&i&&e.jsxs("button",{type:"button",onClick:()=>i(r.id),disabled:R!==null,className:"mt-3 flex w-full items-center justify-center gap-2 rounded-lg border border-accent/30 bg-accent/10 py-2 text-[13px] font-medium text-ink hover:bg-accent/15 disabled:opacity-50",title:n("computer.twoDesktopsTitle"),children:[e.jsx(Ms,{size:14}),n("computer.twoDesktops")]}),de&&de.place!=="browser"&&on(it&&!q.held?()=>c==="vm"||W?void ve():void sr("take"):void 0),(W||c==="vm"||we)&&q.held&&e.jsxs("div",{className:"mt-3 rounded-xl border border-accent/25 bg-accent/10 p-4",children:[e.jsxs("div",{className:"text-[13px] leading-relaxed text-ink",children:[n("computer.youHaveWheel"),W&&!ee&&` ${n(Q?"computer.useOpenDesktop":"computer.simple.useFullScreen")}`]}),e.jsxs("button",{onClick:()=>{ln()},disabled:ie||le.handingBack,className:"mt-2 flex w-full items-center justify-center gap-2 rounded-lg bg-accent py-2 text-[13px] font-medium text-white hover:brightness-110 disabled:opacity-50",children:[e.jsx(Ye,{size:14}),n("computer.handBack")]})]}),Q&&c==="vm"&&(q.held||!it)&&e.jsxs("button",{onClick:()=>{ve(q.held)},disabled:ie||!ee,className:"mt-3 flex w-full items-center justify-center gap-2 rounded-lg bg-control py-2 text-[13px] text-ink hover:bg-raised-hover disabled:opacity-50",title:q.held?n("computer.openLiveDesktop"):n("computer.takeControlTitle"),children:[ie?e.jsx(A,{size:14,className:"animate-spin"}):q.held?e.jsx(Ze,{size:14}):e.jsx(Ye,{size:14}),n(q.held?"computer.fullScreen":"computer.takeControl")]}),Q&&J&&c==="vm"&&H?.mode==="per-bot"&&e.jsxs("button",{onClick:()=>{At("vm-delete")},disabled:R!==null||s.busy,className:"mt-2 flex w-full items-center justify-center gap-2 rounded-lg border border-danger/30 py-2 text-[13px] text-danger hover:bg-danger/10 disabled:opacity-50",title:s.busy?n("computer.deleteVmBlocked"):n("computer.deleteVmTitle",{name:r.name}),children:[R==="vm-delete"?e.jsx(A,{size:14,className:"animate-spin"}):e.jsx(mt,{size:14}),n("computer.deleteVm")]}),!Q&&(W||c==="vm")&&e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2","data-testid":"computer-actions",children:[!q.held&&!it&&e.jsxs("button",{type:"button",onClick:()=>{ve()},disabled:ie||zt,className:"flex flex-auto items-center justify-center gap-2 whitespace-nowrap rounded-lg bg-accent px-3 py-2 text-[13px] font-medium text-accent-ink hover:brightness-110 disabled:opacity-50",title:n("computer.takeControlTitle"),children:[R==="join"?e.jsx(A,{size:14,className:"animate-spin"}):e.jsx(Ye,{size:14}),n("computer.takeControl")]}),e.jsx(Qs,{held:q.held,frame:ge,name:r.name,onTakeControl:t=>{ve(t)},disabled:q.held&&zt,takeDisabled:ie||zt,error:be}),W&&Y&&(T==="vps"||Ve!=="archived")&&e.jsxs("button",{type:"button",onClick:()=>Tt("sleep"),disabled:R==="sleep"||s.busy,className:"flex flex-auto items-center justify-center gap-2 whitespace-nowrap rounded-lg bg-control px-3 py-2 text-[13px] text-ink hover:bg-raised-hover disabled:opacity-50",title:n("computer.sleepTitle"),children:[R==="sleep"?e.jsx(A,{size:14,className:"animate-spin"}):e.jsx(In,{size:14}),n("vm.cloud.sleep")]})]}),Q&&W&&e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[!q.held&&!it&&e.jsxs("button",{onClick:()=>{ve()},disabled:ie||R==="join",className:"flex flex-auto items-center justify-center gap-2 whitespace-nowrap rounded-lg bg-control px-3 py-2 text-[13px] text-ink hover:bg-raised-hover disabled:opacity-50",title:n("computer.takeControlTitle"),children:[R==="join"?e.jsx(A,{size:14,className:"animate-spin"}):e.jsx(Ye,{size:14}),n("computer.takeControl")]}),q.held&&e.jsxs("button",{onClick:()=>{ve(!0)},disabled:R==="join",className:"flex flex-auto items-center justify-center gap-2 whitespace-nowrap rounded-lg bg-control px-3 py-2 text-[13px] text-ink hover:bg-raised-hover disabled:opacity-50",children:[R==="join"?e.jsx(A,{size:14,className:"animate-spin"}):ee?e.jsx(Ze,{size:14}):e.jsx(De,{size:14}),n(ee?"computer.fullScreen":"computer.openLiveDesktop")]}),Y&&(T==="vps"||Ve!=="archived")&&e.jsxs("button",{onClick:()=>Tt("sleep"),disabled:R==="sleep"||s.busy,className:"flex flex-auto items-center justify-center gap-2 whitespace-nowrap rounded-lg bg-control px-3 py-2 text-[13px] text-ink hover:bg-raised-hover disabled:opacity-50",title:n("computer.sleepTitle"),children:[R==="sleep"?e.jsx(A,{size:14,className:"animate-spin"}):e.jsx(In,{size:14}),n("vm.cloud.sleep")]})]}),c!=="team-boat"&&(r.computer!==void 0||U)&&e.jsxs(e.Fragment,{children:[e.jsx(ra,{}),e.jsx(ia,{}),e.jsx(Ns,{}),e.jsx(la,{})]}),Q?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mt-4 rounded-xl bg-card p-4",children:[e.jsx("div",{className:"text-[15px] font-medium text-ink",children:n("computer.worksOn")}),e.jsx("p",{className:"mt-1 text-[12px] leading-5 text-ink-secondary",children:n(u.config?.cloudHome?"computer.worksOnHintCloudHome":"computer.worksOnHint")}),e.jsx(As,{options:He,onSelect:gn}),w&&e.jsx("p",{className:"mt-2 text-[12px] leading-5 text-ink-secondary","data-testid":"place-pinned-note",children:n("place.pinnedNote",{place:n(Vt(w))})}),e.jsxs("div",{className:"mt-3 border-t border-hairline/40 pt-3 text-[12px] leading-5 text-ink-secondary","aria-live":"polite","data-testid":"place-line",children:[lt.line,qe(lt,"mt-1 block font-medium text-accent hover:underline")]}),s.computer==="cloud"&&e.jsx(Ln,{compact:!0,value:T,onChange:t=>Ie({cloudBackend:t})})]}),e.jsxs("button",{type:"button",onClick:()=>st("routines"),className:"mt-4 flex w-full items-start gap-3 rounded-xl bg-card p-4 text-left hover:bg-raised",children:[e.jsx(Tn,{size:17,className:"mt-0.5 shrink-0 text-accent"}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsxs("span",{className:"block text-[14px] font-medium text-ink",children:[n("computer.tab.routines")," ",e.jsx("span",{className:"ml-1 text-[11px] text-ink-secondary",children:nn.length})]}),e.jsx("span",{className:K("mt-1 block truncate text-[12px]",Ke?ds(Ke):"text-ink-secondary"),children:Ke?`${Ke.routineName} · ${cs(Ke)}`:n("computer.routines.openTitle")})]}),e.jsx(Ds,{size:14,className:"shrink-0 text-ink-secondary rtl:-scale-x-100","aria-hidden":"true"})]})]}):e.jsxs("div",{className:"mt-4 rounded-xl bg-card p-4","data-testid":"where-works",children:[e.jsx("div",{className:"text-[15px] font-medium text-ink",children:n("computer.simple.whereWorks",{name:r.name})}),e.jsx("div",{role:"group","aria-label":n("computer.destinationAria"),className:"mt-3 grid grid-cols-3 gap-2",children:He.map(({mode:t,Icon:o,selected:l,disabled:b,unavailableTitle:z,simpleLabel:se,issue:ue,view:X})=>e.jsxs("button",{type:"button",disabled:b,title:z,"aria-pressed":l,onClick:()=>gn(t),className:K("flex min-w-0 flex-col items-center gap-1.5 rounded-lg border px-1.5 py-2.5 text-center transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-2 focus-visible:ring-offset-card",l?"border-accent/60 bg-accent/10 text-ink":"border-hairline/50 bg-panel/30 text-ink-secondary",b?"cursor-not-allowed opacity-50":"hover:border-accent/40 hover:bg-control/60"),children:[e.jsx(o,{size:16,className:K("shrink-0",l?"text-accent":"text-ink-secondary"),"aria-hidden":"true"}),e.jsx("span",{className:"w-full truncate text-[12px] font-medium leading-4",children:se}),ue&&e.jsx("span",{className:"w-full truncate text-[11px] leading-3 text-ink-secondary",children:X.short})]},t??"auto"))}),e.jsxs("div",{className:"mt-3 text-[12px] leading-5 text-ink-secondary","data-testid":"place-line",children:[lt.line,qe(lt,"mt-1 block font-medium text-accent hover:underline")]}),Ot&&e.jsxs("div",{className:"mt-2 flex items-center gap-2",children:[e.jsx("p",{className:"min-w-0 flex-1 text-[12px] leading-5 text-ink-secondary","data-testid":"place-pinned-note",children:n("place.pinnedNoteSimple",{place:He.find(({mode:t})=>t===Ot)?.simpleLabel??n(Vt(Ot))})}),e.jsx("button",{type:"button",disabled:!!r.busy,title:r.busy?n("place.busy"):void 0,onClick:xr,className:"shrink-0 rounded-md px-2 py-0.5 text-[12px] font-medium leading-5 text-accent-text transition-colors hover:bg-control focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent disabled:cursor-not-allowed disabled:opacity-45 disabled:hover:bg-transparent","data-testid":"place-unpin",children:n("place.unpinSimple",{place:He.find(({selected:t})=>t)?.simpleLabel??n(Vt(s.computer??"auto"))})})]}),un&&e.jsx(Ks,{bot:r,backend:T,onBackend:t=>Ie({cloudBackend:t}),onAutoStart:()=>m({type:"updateBot",botId:r.id,patch:{autoStartVps:!r.autoStartVps}})})]})]})]}),e.jsx(us,{open:Kt!==null,onCancel:()=>gt(null),onConfirm:()=>{const t=Kt;gt(null),t&&(t===r.id&&(ne(null),N("checking")),m({type:"updateBot",botId:t,patch:{computer:"local",acknowledgeLocalAuto:!0}}))}})]})}export{Oa as ComputerPanel};