sootsim 0.1.36 → 0.1.38
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.
- package/README.md +20 -5
- package/dist-cli/bin.js +15 -20
- package/dist-cli/chunks/{agent-YZB6D3DR.js → agent-CGQWOOOL.js} +2 -2
- package/dist-cli/chunks/{agent-wrapper-VHCVS22I.js → agent-wrapper-M6P53GJ2.js} +10 -10
- package/dist-cli/chunks/{assert-AIVCKKLG.js → assert-O7N2SYJZ.js} +2 -2
- package/dist-cli/chunks/auto-bootstrap-DF4KYGPS.js +2 -0
- package/dist-cli/chunks/beta-AK25X3AU.js +2 -0
- package/dist-cli/chunks/chunk-23YMXBQ2.js +1 -0
- package/dist-cli/chunks/chunk-2ABGQIW7.js +4 -0
- package/dist-cli/chunks/chunk-5HNZO5AI.js +7 -0
- package/dist-cli/chunks/chunk-5XI3AB4I.js +3 -0
- package/dist-cli/chunks/{chunk-IJMYFYDZ.js → chunk-67K3WAEZ.js} +2 -2
- package/dist-cli/chunks/chunk-6UJXRT7F.js +5 -0
- package/dist-cli/chunks/chunk-ARH3T5NK.js +66 -0
- package/dist-cli/chunks/{chunk-VFDRZNPN.js → chunk-B4VH67D3.js} +1 -1
- package/dist-cli/chunks/chunk-BEY2QVU5.js +3 -0
- package/dist-cli/chunks/chunk-CB4PUMI2.js +1 -0
- package/dist-cli/chunks/chunk-CHMHTTI7.js +11 -0
- package/dist-cli/chunks/chunk-E473YTRQ.js +2 -0
- package/dist-cli/chunks/chunk-FCOCFEBU.js +27 -0
- package/dist-cli/chunks/chunk-FRE5TY3C.js +1 -0
- package/dist-cli/chunks/chunk-FX3PPKSJ.js +2 -0
- package/dist-cli/chunks/{chunk-27P763IZ.js → chunk-FXY5FWVY.js} +2 -2
- package/dist-cli/chunks/{chunk-A5BRCXYE.js → chunk-G23GIRBM.js} +1 -1
- package/dist-cli/chunks/chunk-G62Q2MQI.js +1 -0
- package/dist-cli/chunks/chunk-GWQUPWVO.js +2 -0
- package/dist-cli/chunks/{chunk-EWSQSALM.js → chunk-H6CG42HE.js} +4 -4
- package/dist-cli/chunks/chunk-HNAGYNWN.js +16 -0
- package/dist-cli/chunks/{chunk-KAXZHEKM.js → chunk-IE2WYVJF.js} +1 -1
- package/dist-cli/chunks/chunk-IKVIHHWE.js +2 -0
- package/dist-cli/chunks/chunk-JJVZMGRM.js +2 -0
- package/dist-cli/chunks/{chunk-HWCKZXNJ.js → chunk-LNRBXCUI.js} +2 -2
- package/dist-cli/chunks/{chunk-CYCXOAVZ.js → chunk-MTPWS4JK.js} +4 -4
- package/dist-cli/chunks/{chunk-G7XQD4KC.js → chunk-NKYTISAN.js} +2 -2
- package/dist-cli/chunks/chunk-NSZBULGG.js +348 -0
- package/dist-cli/chunks/chunk-P32FCOS3.js +4 -0
- package/dist-cli/chunks/chunk-P722XCFT.js +3 -0
- package/dist-cli/chunks/chunk-PFRPXFSL.js +117 -0
- package/dist-cli/chunks/chunk-QD22CQLH.js +5 -0
- package/dist-cli/chunks/chunk-QI4VLQ3A.js +5 -0
- package/dist-cli/chunks/{chunk-OXN2PEB7.js → chunk-SKNHJDYO.js} +3 -3
- package/dist-cli/chunks/{chunk-YIO6S3R5.js → chunk-T442FYM5.js} +1 -1
- package/dist-cli/chunks/chunk-TR554AIH.js +17 -0
- package/dist-cli/chunks/chunk-UD5ILFN5.js +3 -0
- package/dist-cli/chunks/{chunk-LHDWH7VS.js → chunk-VIEK76DX.js} +1 -1
- package/dist-cli/chunks/chunk-VVUEWU2P.js +64 -0
- package/dist-cli/chunks/{chunk-RMW5BO3S.js → chunk-Z2PBRNJP.js} +2 -2
- package/dist-cli/chunks/chunk-ZEVZN3S4.js +2 -0
- package/dist-cli/chunks/{compat-Y2O2U7FL.js → compat-DNQWSPFQ.js} +2 -2
- package/dist-cli/chunks/{config-SRBOFUCI.js → config-ABR5BGUO.js} +2 -2
- package/dist-cli/chunks/control-DEHRU4XZ.js +2 -0
- package/dist-cli/chunks/cpu-profile-Y5YDH6X2.js +22 -0
- package/dist-cli/chunks/daemon-2Z4DAJT6.js +83 -0
- package/dist-cli/chunks/{debug-BIDMW2PE.js → debug-R36UPOJP.js} +4 -4
- package/dist-cli/chunks/demo-app-registry-DMMWYL7G.js +2 -0
- package/dist-cli/chunks/detox-FQJWEWLT.js +49 -0
- package/dist-cli/chunks/device-SXKLDZEC.js +16 -0
- package/dist-cli/chunks/diagnose-M7RKNI2H.js +41 -0
- package/dist-cli/chunks/drivers-NSCX5CRA.js +2 -0
- package/dist-cli/chunks/electron-YUAKGT4H.js +18 -0
- package/dist-cli/chunks/flow-UQSRNEZD.js +2 -0
- package/dist-cli/chunks/hints-SDD7L3VS.js +2 -0
- package/dist-cli/chunks/home-paths-QMCX2227.js +2 -0
- package/dist-cli/chunks/inspect-6FPPW7GS.js +1101 -0
- package/dist-cli/chunks/install-TTH3PM3B.js +2 -0
- package/dist-cli/chunks/{install-desktop-2MYEI4FM.js → install-desktop-EKMYRDQH.js} +3 -3
- package/dist-cli/chunks/{keys-7PNASIQR.js → keys-ODG3TDUP.js} +2 -2
- package/dist-cli/chunks/{launch-JNS47LAQ.js → launch-7HUL745I.js} +3 -3
- package/dist-cli/chunks/{login-YWZWUHBS.js → login-BJKQMJYT.js} +4 -4
- package/dist-cli/chunks/{logout-O6SXMSBP.js → logout-7NG3KGJD.js} +2 -2
- package/dist-cli/chunks/maestro-VFEUWV3Q.js +80 -0
- package/dist-cli/chunks/{preview-WGKJO5FS.js → preview-WZ6XNOBC.js} +2 -2
- package/dist-cli/chunks/profile-DXFEZOHB.js +22 -0
- package/dist-cli/chunks/react-QP7PL5CZ.js +30 -0
- package/dist-cli/chunks/{record-QPWLYH5R.js → record-AFE25EMH.js} +5 -5
- package/dist-cli/chunks/{runtime-KEMO2MSB.js → runtime-GFWS3QLZ.js} +3 -3
- package/dist-cli/chunks/screenshot-U6VFOVFW.js +28 -0
- package/dist-cli/chunks/screenshot-mode-HNGV3AFC.js +17 -0
- package/dist-cli/chunks/screenshots-GYMRDUJR.js +70 -0
- package/dist-cli/chunks/server-3Q22YYM6.js +35 -0
- package/dist-cli/chunks/setup-repo-NNDWIGZR.js +2 -0
- package/dist-cli/chunks/{skills-MO7BFNVM.js → skills-FT76ZVAV.js} +2 -2
- package/dist-cli/chunks/start-N573LFCF.js +23 -0
- package/dist-cli/chunks/store-6NTDGLPH.js +2 -0
- package/dist-cli/chunks/telemetry-SNZBIRGL.js +2 -0
- package/dist-cli/chunks/{test-XUI3KNNQ.js → test-AJPY2Q6W.js} +3 -3
- package/dist-cli/chunks/three-mode-JZZVOMTG.js +39 -0
- package/dist-cli/chunks/timeline-GTSCF5P6.js +22 -0
- package/dist-cli/chunks/upload-UHTVCGGR.js +2 -0
- package/dist-cli/chunks/what-happened-N3AQ6I7O.js +15 -0
- package/dist-cli/chunks/whoami-FOIMN6UC.js +2 -0
- package/dist-lib/agent-daemon-client.cjs +4 -1
- package/dist-lib/agent-events.cjs +1 -1
- package/dist-lib/agent-sessions.cjs +41 -39
- package/dist-lib/attached-projects.cjs +30 -28
- package/dist-lib/auth/shared-session.cjs +35 -27
- package/dist-lib/backend-origin.cjs +1 -1
- package/dist-lib/bridge-constants.cjs +1 -1
- package/dist-lib/cli-constants.cjs +1 -1
- package/dist-lib/config.cjs +6 -2
- package/dist-lib/dev-bundle-resolution.cjs +5 -50
- package/dist-lib/home-paths.cjs +94 -38
- package/dist-lib/host/bridge-host.cjs +2144 -1330
- package/dist-lib/host/fetch-proxy-handler.cjs +248 -0
- package/dist-lib/index.cjs +21 -21
- package/dist-lib/metro.cjs +21 -21
- package/dist-lib/profiles.cjs +246 -0
- package/dist-lib/render-mode.cjs +1 -1
- package/dist-lib/vite-base.cjs +3410 -1632
- package/dist-lib/vite.cjs +1 -1
- package/package.json +7 -1
- package/dist-cli/chunks/auto-bootstrap-MLNTX23H.js +0 -2
- package/dist-cli/chunks/chunk-3UIWOHC2.js +0 -62
- package/dist-cli/chunks/chunk-5KGFHWVR.js +0 -1
- package/dist-cli/chunks/chunk-5QIUJNT3.js +0 -5
- package/dist-cli/chunks/chunk-6GGMKFWJ.js +0 -4
- package/dist-cli/chunks/chunk-6Z275LCY.js +0 -2
- package/dist-cli/chunks/chunk-75LBYBKW.js +0 -11
- package/dist-cli/chunks/chunk-DFN3GGH7.js +0 -5
- package/dist-cli/chunks/chunk-EBEHZJRG.js +0 -117
- package/dist-cli/chunks/chunk-EJLNUMMP.js +0 -3
- package/dist-cli/chunks/chunk-FE7UI3MT.js +0 -4
- package/dist-cli/chunks/chunk-G663654J.js +0 -1
- package/dist-cli/chunks/chunk-GW7XY5KC.js +0 -2
- package/dist-cli/chunks/chunk-H2QO4TDV.js +0 -22
- package/dist-cli/chunks/chunk-HWFHBMAQ.js +0 -27
- package/dist-cli/chunks/chunk-J7CTD37P.js +0 -1
- package/dist-cli/chunks/chunk-N32NCVL2.js +0 -3
- package/dist-cli/chunks/chunk-NIZBR7EK.js +0 -2
- package/dist-cli/chunks/chunk-NYY36OKU.js +0 -308
- package/dist-cli/chunks/chunk-PJL25JQV.js +0 -5
- package/dist-cli/chunks/chunk-SHO54NET.js +0 -2
- package/dist-cli/chunks/chunk-SMVJOWSV.js +0 -16
- package/dist-cli/chunks/chunk-TC6V7YFC.js +0 -3
- package/dist-cli/chunks/chunk-YLIIVTTQ.js +0 -3
- package/dist-cli/chunks/chunk-YR7BGGYE.js +0 -2
- package/dist-cli/chunks/chunk-ZEW3RF5Q.js +0 -1
- package/dist-cli/chunks/control-PL2V2O6S.js +0 -2
- package/dist-cli/chunks/daemon-IZC32PZW.js +0 -50
- package/dist-cli/chunks/demo-app-registry-5JFOUU3D.js +0 -2
- package/dist-cli/chunks/detox-B3FDOIS3.js +0 -49
- package/dist-cli/chunks/device-ZZSI363W.js +0 -16
- package/dist-cli/chunks/drivers-S4NGK4DB.js +0 -2
- package/dist-cli/chunks/electron-5YFHXEOI.js +0 -15
- package/dist-cli/chunks/flow-JJBO6TFY.js +0 -2
- package/dist-cli/chunks/hints-G5HBBV2O.js +0 -2
- package/dist-cli/chunks/home-paths-VWC3FWA3.js +0 -2
- package/dist-cli/chunks/inspect-POOPWUQI.js +0 -1034
- package/dist-cli/chunks/install-MP6FHXNZ.js +0 -2
- package/dist-cli/chunks/install-dev-desktop-SKH3KEHY.js +0 -100
- package/dist-cli/chunks/maestro-CW6XVUKV.js +0 -75
- package/dist-cli/chunks/profile-SUOBRPIC.js +0 -22
- package/dist-cli/chunks/screenshot-JTY46V7G.js +0 -26
- package/dist-cli/chunks/screenshot-mode-7OYBBX6D.js +0 -17
- package/dist-cli/chunks/screenshots-QISKC4GD.js +0 -70
- package/dist-cli/chunks/server-YSFJAKAV.js +0 -34
- package/dist-cli/chunks/setup-repo-LFB3HBEO.js +0 -2
- package/dist-cli/chunks/store-6MFL53I4.js +0 -2
- package/dist-cli/chunks/telemetry-CN42GMVC.js +0 -2
- package/dist-cli/chunks/upload-6FUT7AX5.js +0 -2
- package/dist-cli/chunks/whoami-TQFHY42N.js +0 -2
|
@@ -0,0 +1,348 @@
|
|
|
1
|
+
/*! sootsim v0.1.38 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
|
|
2
|
+
import{a as ye}from"./chunk-QD22CQLH.js";import{a as be}from"./chunk-H6CG42HE.js";import{a as ve}from"./chunk-FCOCFEBU.js";import{a as V,b as A,c as me,d as q,f as pe,g as fe}from"./chunk-LNRBXCUI.js";import{e as he,k as ge}from"./chunk-CHMHTTI7.js";import{b as ue}from"./chunk-SKNHJDYO.js";import{a as we}from"./chunk-QI4VLQ3A.js";import{a as Se}from"./chunk-ARH3T5NK.js";import{f as ne}from"./chunk-ZEVZN3S4.js";import{a as ae,b as H}from"./chunk-67K3WAEZ.js";import{c as z,d as ce,e as de}from"./chunk-TR554AIH.js";import{c as le}from"./chunk-2ABGQIW7.js";import*as $ from"fs";import{tmpdir as $e}from"os";import*as g from"path";import*as w from"fs";import*as f from"path";var U=1e4,B=393,C=852,xe="__sootsimCliPerf",Oe="maestroCopiedText",G=new Map;function m(o){return new Promise(e=>setTimeout(e,o))}function Ne(o){return o?f.basename(o)===".maestro"?f.dirname(o):o:process.cwd()}function De(o,e,t){let r=e.endsWith(".png")?e:`${e}.png`;if(f.isAbsolute(r))return r;if(t.mode==="flow"&&/[\\/]/.test(r)){let i=r.startsWith("./")||r.startsWith("../")?t.flowDir??process.cwd():Ne(t.flowDir);return f.resolve(i,r)}return f.join(o,r)}function Re(o){if(typeof o=="string")return{path:o,withFrame:!1};let e=o.path?.trim()||o.name?.trim();if(!e)throw new Error("takeScreenshot object form requires path or name");return{path:e,withFrame:o.withFrame===!0}}function Y(o){let[e,t]=o.split(",").map(i=>i.trim()),r=(i,n)=>i.endsWith("%")?Number.parseFloat(i)/100*n:Number.parseFloat(i);return{x:r(e,B),y:r(t,C)}}function X(o){return typeof o=="string"?o.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g,(e,t)=>{if(G.has(t))return G.get(t);let r=process.env[t];if(r===void 0)throw new Error(`missing environment variable for flow placeholder: ${t}`);return r}):Array.isArray(o)?o.map(e=>X(e)):o&&typeof o=="object"?Object.fromEntries(Object.entries(o).map(([e,t])=>[e,X(t)])):o}function Ve(o){let e=o.split(/^---$/m),t=e.length>1?e[e.length-1]:o,r=X(A.parse(t));return Array.isArray(r)?r:[]}var W=class{constructor(e,t){this.bridge=e;this.opts=t}stepDelay=0;firstLaunchDone=!1;profilingEnabled=!1;recordingEnabled=!1;recordingAccessChecked=!1;recordingStartedAtMs=null;lastRecordingDurationMs=null;simRouteHint=null;lastFailedStep=null;get simId(){return this.opts.simId}setSimRouteHint(e){this.simRouteHint=this.normalizeSimRoute(e)}normalizeSimRoute(e){if(!e)return null;try{let t=new URL(e);t.searchParams.delete("inspectOpen");let r=t.searchParams.toString();return`${t.origin}${t.pathname}${r?`?${r}`:""}`}catch{return e}}async refreshSimId(){if(this.opts.simId)try{let e=await this.bridge.listSims(),t=e.find(a=>a.id===this.opts.simId);if(t&&(this.simRouteHint=this.normalizeSimRoute(t.url||t.origin)),e.find(a=>a.id===this.opts.simId&&a.readyState==="open")||!this.simRouteHint)return;let i=this.simRouteHint&&e.find(a=>a.readyState==="open"&&this.normalizeSimRoute(a.url||a.origin)===this.simRouteHint);if(!i)return;let n=e.find(a=>a.isPrimary&&a.readyState==="open"),s=e.find(a=>a.readyState==="open"),l=i??n??s;l&&(this.opts.simId=l.id,console.log(` [flow] sim rotated to ${l.id}`))}catch{}}async evaluate(e){return this.bridge.send({type:"evaluate",simId:this.opts.simId,code:e})}async callTest(e,...t){return this.bridge.send({type:"call",simId:this.opts.simId,path:`__sootsimTest.${e}`,args:t})}async waitForTree(e=U){let t=Date.now()+e,r=null;for(;Date.now()<t;){try{let i=await this.evaluate(`(async () => {
|
|
3
|
+
const test = window.__sootsimTest
|
|
4
|
+
if (!test) return { count: 0, loading: true }
|
|
5
|
+
const count = (await test.getNodeCount?.()) || 0
|
|
6
|
+
const external = globalThis.__sootsimExternalAppState
|
|
7
|
+
if (external?.error) {
|
|
8
|
+
return { count, loading: false, error: String(external.error) }
|
|
9
|
+
}
|
|
10
|
+
if (external) {
|
|
11
|
+
return {
|
|
12
|
+
count,
|
|
13
|
+
loading: !external.ready,
|
|
14
|
+
error: null,
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
const loadingNode = await test.findByText?.('loading')
|
|
18
|
+
const capturingNode = await test.findByText?.('capturing')
|
|
19
|
+
const openingAppNode = await test.findByText?.('opening app')
|
|
20
|
+
const isLoading = !!loadingNode || !!capturingNode || !!openingAppNode || count < 5
|
|
21
|
+
return { count, loading: isLoading, error: null }
|
|
22
|
+
})()`);if(i?.error)throw new Error(`app failed to load: ${i.error}`);if(i&&i.count>10&&!i.loading)return}catch(i){r=i instanceof Error?i:new Error(String(i)),await this.refreshSimId()}await m(500)}throw r?.message.startsWith("app failed to load:")?r:new Error(`app not ready after ${e}ms`)}async ensureRecordingStarted(){if(!this.opts.recordingOutputDir)throw new Error("recording output directory not configured");this.recordingAccessChecked||(await ve("flow --video",{originOverride:this.opts.billingOriginOverride,allowGitHubAuth:this.opts.allowGitHubRecording}),this.recordingAccessChecked=!0);let e=Date.now(),t=await this.evaluate(`(() => {
|
|
23
|
+
const rec = window.__sootsimRecorder
|
|
24
|
+
if (!rec) return { ok: false, error: 'recorder unavailable on this page' }
|
|
25
|
+
if (rec.state() === 'recording') return { ok: true, format: 'webm' }
|
|
26
|
+
return rec.start({ format: 'webm', fps: 24 })
|
|
27
|
+
})()`);if(!t?.ok)throw new Error(t?.error||"recording unavailable on this page");this.recordingStartedAtMs||(this.recordingStartedAtMs=e)}async startRecording(){this.recordingEnabled=!0,await this.ensureRecordingStarted()}prepareRecording(){this.recordingEnabled=!0}getLastRecordingDurationMs(){return this.lastRecordingDurationMs}async stopRecording(){if(!this.recordingEnabled||!this.opts.recordingOutputDir)return null;this.recordingEnabled=!1;let e=Date.now(),t=await this.evaluate("window.__sootsimRecorder.stop()");if(!t?.ok)throw this.recordingStartedAtMs=null,new Error(t?.error||"recording stop failed");this.lastRecordingDurationMs=this.recordingStartedAtMs?Math.max(1,e-this.recordingStartedAtMs):null,this.recordingStartedAtMs=null;let r=[],i=0;for(;;){let s=await this.evaluate(`window.__sootsimRecorder.getBlobBase64({ offset: ${i}, chunk: 2097152 })`);if(!s||(r.push(Buffer.from(s.data,"base64")),i=s.offset,s.done))break}if(r.length===0)throw new Error("recording requested but no video buffer was produced");w.mkdirSync(this.opts.recordingOutputDir,{recursive:!0});let n=f.join(this.opts.recordingOutputDir,`sootsim-${Date.now()}.webm`);return w.writeFileSync(n,Buffer.concat(r)),n}async findElement(e){return this.evaluate(`(async () => {
|
|
28
|
+
const test = window.__sootsimTest
|
|
29
|
+
if (!test) return null
|
|
30
|
+
let node = null
|
|
31
|
+
if (${JSON.stringify(!!e.text)}) node = await test.findByText(${JSON.stringify(e.text||"")})
|
|
32
|
+
if (!node && ${JSON.stringify(!!e.id)}) {
|
|
33
|
+
node = (await test.findByTestId(${JSON.stringify(e.id||"")})) || (await test.findById(${JSON.stringify(e.id||"")}))
|
|
34
|
+
}
|
|
35
|
+
if (!node || !node.absolutePosition || !node.layout) return null
|
|
36
|
+
return {
|
|
37
|
+
nodeId: typeof node.nodeId === 'number' ? node.nodeId : null,
|
|
38
|
+
id: node.id || null,
|
|
39
|
+
testID: node.testID || null,
|
|
40
|
+
text: node.text || null,
|
|
41
|
+
absolutePosition: node.absolutePosition,
|
|
42
|
+
layout: node.layout,
|
|
43
|
+
isTextInput: !!node.isTextInput,
|
|
44
|
+
}
|
|
45
|
+
})()`)}async resolveTapTarget(e){return this.evaluate(`(async () => {
|
|
46
|
+
const test = window.__sootsimTest
|
|
47
|
+
if (!test?.resolveTapTarget) return null
|
|
48
|
+
return await test.resolveTapTarget(${e})
|
|
49
|
+
})()`)}async activatePressTarget(e){return this.evaluate(`(async () => {
|
|
50
|
+
const test = window.__sootsimTest
|
|
51
|
+
if (!test) return null
|
|
52
|
+
const node = ${e.id?`(await test.findByTestId?.(${JSON.stringify(e.id)})) || (await test.findById?.(${JSON.stringify(e.id)}))`:`await test.findByText?.(${JSON.stringify(e.text||"")})`}
|
|
53
|
+
let point = null
|
|
54
|
+
if (node?.absolutePosition && node?.layout) {
|
|
55
|
+
point = {
|
|
56
|
+
x: node.absolutePosition.x + node.layout.width / 2,
|
|
57
|
+
y: node.absolutePosition.y + node.layout.height / 2,
|
|
58
|
+
}
|
|
59
|
+
if (typeof node.nodeId === 'number' && test.resolveTapTarget) {
|
|
60
|
+
const resolved = await test.resolveTapTarget(node.nodeId)
|
|
61
|
+
if (
|
|
62
|
+
resolved &&
|
|
63
|
+
Number.isFinite(resolved.cx) &&
|
|
64
|
+
Number.isFinite(resolved.cy)
|
|
65
|
+
) {
|
|
66
|
+
point = { x: resolved.cx, y: resolved.cy }
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
${e.id?`const direct = await test.activatePressById?.(${JSON.stringify(e.id)})`:`const direct = await test.activatePressByText?.(${JSON.stringify(e.text||"")})`}
|
|
71
|
+
if (direct?.ok && point) {
|
|
72
|
+
window.dispatchEvent(
|
|
73
|
+
new CustomEvent('sootsim:agentAction', {
|
|
74
|
+
detail: { type: 'tap', x: point.x, y: point.y },
|
|
75
|
+
}),
|
|
76
|
+
)
|
|
77
|
+
}
|
|
78
|
+
return direct || null
|
|
79
|
+
})()`)}async activatePressAt(e,t){return this.evaluate(`(async () => {
|
|
80
|
+
const test = window.__sootsimTest
|
|
81
|
+
if (!test?.activatePressAt) return null
|
|
82
|
+
const direct = await test.activatePressAt(${e}, ${t})
|
|
83
|
+
if (direct?.ok) {
|
|
84
|
+
window.dispatchEvent(
|
|
85
|
+
new CustomEvent('sootsim:agentAction', {
|
|
86
|
+
detail: { type: 'tap', x: ${e}, y: ${t} },
|
|
87
|
+
}),
|
|
88
|
+
)
|
|
89
|
+
}
|
|
90
|
+
return direct
|
|
91
|
+
})()`)}async tap(e,t){return await this.bridge.send({type:"tap",simId:this.opts.simId,x:e,y:t})}async tapOn(e){let t=typeof e=="string"?{text:e}:e;if(t.point){let a=Y(t.point);(await this.activatePressAt(a.x,a.y))?.ok||await this.tap(a.x,a.y),await m(300);return}let r=5e3,i=150,n=Date.now()+r,s=await this.findElement({text:t.text,id:t.id});for(;!s&&Date.now()<n;)await m(i),s=await this.findElement({text:t.text,id:t.id});if(s&&!s.isTextInput&&(await this.activatePressTarget(t))?.ok){await m(300);return}if(s){let a=typeof s.nodeId=="number"?await this.resolveTapTarget(s.nodeId):null,p=a?.cx??s.absolutePosition.x+s.layout.width/2,h=a?.cy??s.absolutePosition.y+s.layout.height/2;if((await this.tap(p,h))?.hit!==!1){await m(300);return}}if((await this.activatePressTarget(t))?.ok){await m(300);return}throw new Error(`tapOn: element not found: ${JSON.stringify(t)}`)}async tapAtCoords(e,t){await this.tap(e,t),await m(300)}async doubleTapAtCoords(e,t,r=80){let i=Math.max(0,Math.round(r));if(!await this.evaluate(`(async () => {
|
|
92
|
+
const interact = window.__sootsimInteract
|
|
93
|
+
if (interact?.doubleTap) {
|
|
94
|
+
return !!(await interact.doubleTap(${e}, ${t}, ${i}))
|
|
95
|
+
}
|
|
96
|
+
if (!interact?.tap) return false
|
|
97
|
+
const first = await interact.tap(${e}, ${t})
|
|
98
|
+
if (!first || first.hit === false) return false
|
|
99
|
+
await new Promise((resolve) => setTimeout(resolve, ${i}))
|
|
100
|
+
const second = await interact.tap(${e}, ${t})
|
|
101
|
+
return !!second && second.hit !== false
|
|
102
|
+
})()`))throw new Error(`doubleTapAtCoords failed at (${e}, ${t})`);await m(300)}async assertVisible(e){let t=typeof e=="string"?{text:e}:e;for(let r=0;r<15;r++){if(await this.isElementVisible(t))return;await m(200)}throw new Error(`assertVisible: ${JSON.stringify(t)} not found or off-screen`)}async assertNotVisible(e){let t=typeof e=="string"?{text:e}:e;if(await this.isElementVisible(t))throw new Error(`assertNotVisible: ${JSON.stringify(t)} IS visible`)}async isElementVisible(e){let t=await this.findElement(e);return!!(t&&t.absolutePosition.y+t.layout.height>0&&t.absolutePosition.y<C)}async inputText(e){await this.bridge.send({type:"keyboard",simId:this.opts.simId,action:"type",text:e}),await m(200)}async pressKey(e){await this.bridge.send({type:"keyboard",simId:this.opts.simId,action:"press",text:e}),await m(120)}async dispatchKey(e){await this.bridge.send({type:"keyboard",simId:this.opts.simId,action:"dispatchKey",text:e}),await m(120)}async hideKeyboard(){try{await this.callTest("blurFocusedTextInput")}catch{}await this.bridge.send({type:"keyboard",simId:this.opts.simId,action:"dismiss"});let e=Date.now()+3e3;for(;Date.now()<e;){let t=await this.evaluate(`(() => {
|
|
103
|
+
const keyboard =
|
|
104
|
+
window.__sootsimKeyboard ??
|
|
105
|
+
window.SootSim?.bridges?.keyboard ??
|
|
106
|
+
null
|
|
107
|
+
const test = window.__sootsimTest
|
|
108
|
+
return {
|
|
109
|
+
visible: !!keyboard?.isVisible?.(),
|
|
110
|
+
focused: !!test?.isTextInputFocused?.(),
|
|
111
|
+
}
|
|
112
|
+
})()`);if(!t?.visible&&!t?.focused){await m(80);return}await m(80)}}async eraseText(e){for(let t=0;t<e;t++)await this.pressKey("Backspace");await m(100)}async waitFor(e){let t=Date.now()+(e.timeout||U);for(;Date.now()<t;){if(await this.findElement(e))return;await m(200)}throw new Error(`waitFor: ${JSON.stringify(e)} not found after ${e.timeout||U}ms`)}async takeScreenshot(e){await m(250);let t=Re(e),r=De(this.opts.screenshotDir,t.path,{mode:this.opts.screenshotPathMode??"dir",flowDir:this.opts.flowDir});w.mkdirSync(f.dirname(r),{recursive:!0});let n=(await this.bridge.send({type:"screenshot",simId:this.opts.simId})).replace(/^data:image\/png;base64,/,""),s=Buffer.from(n,"base64");if(t.withFrame){let l=await this.readCurrentDeviceModel();if(!l)throw new Error("could not read current device model for framed screenshot");let a=await be(s,l);w.writeFileSync(r,a),console.log(`[flow] screenshot: ${r} (frame: ${l})`);return}w.writeFileSync(r,s),console.log(`[flow] screenshot: ${r}`)}async readCurrentDeviceModel(){let e=await this.bridge.send({type:"call",simId:this.opts.simId,path:"SootSim.bridges.settings.get",args:[]}),t=e&&typeof e.deviceModel=="string"?e.deviceModel:null;return!t||!(t in ne)?null:t}async captureFailureScreenshot(e){w.mkdirSync(f.dirname(e),{recursive:!0});let r=(await this.bridge.send({type:"screenshot",simId:this.opts.simId})).replace(/^data:image\/png;base64,/,"");w.writeFileSync(e,Buffer.from(r,"base64"))}async captureFailureBundle(e,t){w.mkdirSync(e,{recursive:!0});let r=(p,h)=>{try{w.writeFileSync(f.join(e,p),h)}catch{}},i=async p=>{try{return await this.bridge.send({type:"evaluate",simId:this.opts.simId,code:p})}catch{return null}};r("error.json",JSON.stringify({message:t.error.message,stack:t.error.stack,stepIndex:t.stepIndex,stepKind:t.stepKind,stepTarget:t.stepTarget,capturedAt:new Date().toISOString()},null,2));try{let h=(await this.bridge.send({type:"screenshot",simId:this.opts.simId})).replace(/^data:image\/png;base64,/,"");r("screenshot.png",Buffer.from(h,"base64"))}catch{}let n=await i(`(async () => {
|
|
113
|
+
const t = window.__sootsimTest
|
|
114
|
+
const mainShell = window.SootSim?.bridges?.mainShell
|
|
115
|
+
if (!t) return { error: 'no test bridge' }
|
|
116
|
+
let shell = null
|
|
117
|
+
try {
|
|
118
|
+
shell = typeof mainShell?.getState === 'function' ? await mainShell.getState() : null
|
|
119
|
+
} catch {}
|
|
120
|
+
const all = await t.queryAll({ pruneHidden: true })
|
|
121
|
+
return { shell, nodes: all, url: location.href, title: document.title }
|
|
122
|
+
})()`);n&&r("describe.json",JSON.stringify(n,null,2));let s=await i("(async () => await window.__sootsimTest?.dumpAccessibilityTree?.(20))()");typeof s=="string"&&r("a11y.txt",s);let l=await i("(async () => await window.__sootsimTest?.dumpTree?.(15))()");typeof l=="string"&&r("tree.txt",l);let a=await i(`(() => {
|
|
123
|
+
const c = window.__sootsimConsole
|
|
124
|
+
return {
|
|
125
|
+
errors: c?.getErrors?.() ?? [],
|
|
126
|
+
warnings: c?.getWarnings?.() ?? [],
|
|
127
|
+
requests: (window.__sootsimGetFailedRequests?.() ?? []),
|
|
128
|
+
}
|
|
129
|
+
})()`);return a&&r("console.json",JSON.stringify(a,null,2)),e}async swipe(e="UP",t=300){let r=B/2,i=C/2,n=200,s=r,l=i,a=r,p=i;switch(e.toUpperCase()){case"UP":l+=n,p-=n;break;case"DOWN":l-=n,p+=n;break;case"LEFT":s+=n,a-=n;break;case"RIGHT":s-=n,a+=n;break}let h=Math.max(10,Math.round(t/16));await this.drag(s,l,a,p,h,16)}async drag(e,t,r,i,n=12,s=16){if(!(await this.evaluate(`(async () => {
|
|
130
|
+
const interact = window.__sootsimInteract
|
|
131
|
+
if (!interact?.drag) return { ok: false }
|
|
132
|
+
const value = await interact.drag(${e}, ${t}, ${r}, ${i}, ${Math.max(1,Math.round(n))}, ${Math.max(0,Math.round(s))})
|
|
133
|
+
return { ok: !!value, value }
|
|
134
|
+
})()`))?.ok)throw new Error("drag failed");await m(300)}async swipeCoords(e,t,r=300){let i=Y(e),n=Y(t),s=Math.max(10,Math.round(r/16));await this.drag(i.x,i.y,n.x,n.y,s,16)}async swipeFrom(e,t="UP",r=300){let i=await this.findElement(e);if(!i)throw new Error(`swipeFrom: element not found: ${JSON.stringify(e)}`);let n=i.absolutePosition.x+i.layout.width/2,s=i.absolutePosition.y+i.layout.height/2,l=180,a=n,p=s;switch(t.toUpperCase()){case"UP":p-=l;break;case"DOWN":p+=l;break;case"LEFT":a-=l;break;case"RIGHT":a+=l;break}let h=Math.max(10,Math.round(r/16));await this.drag(n,s,a,p,h,16)}async scrollTo(e,t,r){let i=await this.callTest("scrollTo",e,t,r,!1);if(!i?.ok)throw new Error(`scrollTo failed: ${i?.reason||"unknown error"}`);await m(250)}async pinch(e){let t=await this.evaluate(`(async () => {
|
|
135
|
+
const interact = window.__sootsimInteract
|
|
136
|
+
if (!interact?.pinch) return { ok: false, reason: 'no interact.pinch' }
|
|
137
|
+
const ok = await interact.pinch(
|
|
138
|
+
${e.from[0]}, ${e.from[1]}, ${e.from[2]}, ${e.from[3]},
|
|
139
|
+
${e.to[0]}, ${e.to[1]}, ${e.to[2]}, ${e.to[3]},
|
|
140
|
+
${e.steps||12}, ${e.stepMs||16}
|
|
141
|
+
)
|
|
142
|
+
return { ok: !!ok, reason: ok ? null : 'pinch returned false' }
|
|
143
|
+
})()`);if(!t?.ok)throw new Error(`pinch failed: ${t?.reason||"unknown error"}`);await m(250)}async dumpTree(e=6){let t=await this.bridge.send({type:"tree",simId:this.opts.simId,depth:e});return console.log("[flow] tree:"),console.log(typeof t=="string"?t:JSON.stringify(t,null,2)),typeof t=="string"?t:JSON.stringify(t)}async assertTreeContains(e){if(!(await this.dumpTree(8)).includes(e))throw new Error(`assertTreeContains: "${e}" not in tree`)}async waitForAnimationToEnd(e=2e3){await m(e)}async back(){try{await this.tapOn("\u2039")}catch{await this.tapOn("<")}}async scrollUntilVisible(e){let t=Date.now()+(e.timeout||15e3),r=e.direction?.toUpperCase()||"DOWN",i=r==="DOWN"?"UP":r==="UP"?"DOWN":r;for(;Date.now()<t;){let n=await this.findElement({text:e.element});if(n&&n.absolutePosition.y>=0&&n.absolutePosition.y+n.layout.height>0&&n.absolutePosition.y<C-50){if(e.centerElement){let s=C/2,l=n.absolutePosition.y-s;if(Math.abs(l)>100){let a=Math.min(150,Math.abs(l)*.5),p=l>0?s-a:s+a;await this.drag(B/2,s,B/2,p,10,16)}}return}await this.swipe(i,250),await m(500)}throw new Error(`scrollUntilVisible: "${e.element}" not found`)}async extendedWaitUntil(e){let t=Date.now()+(e.timeout||U);for(;Date.now()<t;){let r=e.visible?await this.isElementVisible(typeof e.visible=="string"?{text:e.visible}:e.visible):!0,i=e.notVisible?!await this.isElementVisible(typeof e.notVisible=="string"?{text:e.notVisible}:e.notVisible):!0;if(r&&i)return;await m(200)}throw new Error("extendedWaitUntil timed out")}async launchApp(e){await this.refreshSimId();let t=!!(e&&typeof e=="object"&&e.clearState);if(t&&await this.evaluate(`(async () => {
|
|
144
|
+
await (${V})
|
|
145
|
+
try {
|
|
146
|
+
const regs = await navigator.serviceWorker?.getRegistrations?.()
|
|
147
|
+
await Promise.all((regs || []).map((reg) => reg.unregister()))
|
|
148
|
+
} catch {}
|
|
149
|
+
})()`),!this.firstLaunchDone&&!t)this.firstLaunchDone=!0,await this.waitForTree(3e4);else if(this.firstLaunchDone=!0,await this.evaluate("window.location.reload()").catch(()=>{}),await m(500),await this.refreshSimId(),await this.waitForTree(12e4),this.opts.onAfterLaunch)try{await this.opts.onAfterLaunch()}catch(r){console.warn(` warn: onAfterLaunch hook threw: ${r instanceof Error?r.message:r}`)}this.profilingEnabled&&await this.startProfile(),this.recordingEnabled&&(await this.waitForVisualSettle(),await this.ensureRecordingStarted())}async waitForVisualSettle(){try{await this.evaluate(`new Promise((resolve) => {
|
|
150
|
+
requestAnimationFrame(() => {
|
|
151
|
+
requestAnimationFrame(() => {
|
|
152
|
+
requestAnimationFrame(() => {
|
|
153
|
+
setTimeout(resolve, 180)
|
|
154
|
+
})
|
|
155
|
+
})
|
|
156
|
+
})
|
|
157
|
+
})`)}catch{await m(180)}}async startProfile(){await this.evaluate(`((sessionKey) => {
|
|
158
|
+
const host = window.__sootsimRenderHost
|
|
159
|
+
if (host?.startPerfSession) {
|
|
160
|
+
host.startPerfSession(sessionKey)
|
|
161
|
+
window[sessionKey] = {
|
|
162
|
+
active: true,
|
|
163
|
+
mode: 'render-worker',
|
|
164
|
+
startedAt: performance.now(),
|
|
165
|
+
}
|
|
166
|
+
return
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const perf = window.__sootsimPerf
|
|
170
|
+
const a11y = window.__sootsimA11y
|
|
171
|
+
perf?.enableFrameStats?.()
|
|
172
|
+
perf?.resetFrameStats?.()
|
|
173
|
+
a11y?.resetProfile?.()
|
|
174
|
+
window[sessionKey] = {
|
|
175
|
+
active: true,
|
|
176
|
+
mode: 'main-thread',
|
|
177
|
+
startedAt: performance.now(),
|
|
178
|
+
}
|
|
179
|
+
})(${JSON.stringify(xe)})`),this.profilingEnabled=!0}async stopProfile(){let e=await this.evaluate(`(async (sessionKey) => {
|
|
180
|
+
const host = window.__sootsimRenderHost
|
|
181
|
+
if (host?.stopPerfSession) {
|
|
182
|
+
const stopped = await host.stopPerfSession(sessionKey)
|
|
183
|
+
if (!stopped || !Array.isArray(stopped.samples)) {
|
|
184
|
+
return { error: 'no render-worker perf samples available' }
|
|
185
|
+
}
|
|
186
|
+
const samples = stopped.samples
|
|
187
|
+
const frameTimes = samples.map((sample) => Number(sample?.[1]) || 0).filter((value) => value > 0)
|
|
188
|
+
const sorted = [...frameTimes].sort((a, b) => a - b)
|
|
189
|
+
const worstFrames = samples
|
|
190
|
+
.slice()
|
|
191
|
+
.sort((a, b) => (Number(b?.[1]) || 0) - (Number(a?.[1]) || 0))
|
|
192
|
+
.slice(0, 10)
|
|
193
|
+
.map((sample) => [
|
|
194
|
+
Number(sample?.[0]) || 0,
|
|
195
|
+
Number(sample?.[1]) || 0,
|
|
196
|
+
Number(sample?.[2]) || 0,
|
|
197
|
+
Number(sample?.[3]) || 0,
|
|
198
|
+
Number(sample?.[4]) || 0,
|
|
199
|
+
])
|
|
200
|
+
|
|
201
|
+
return {
|
|
202
|
+
mode: 'render-worker',
|
|
203
|
+
frames: Number(stopped.frameCount) || frameTimes.length,
|
|
204
|
+
totalMs: Number(stopped.totalMs) || frameTimes.reduce((sum, value) => sum + value, 0),
|
|
205
|
+
avgMs: Number(stopped.avgMs) || (frameTimes.length ? frameTimes.reduce((sum, value) => sum + value, 0) / frameTimes.length : 0),
|
|
206
|
+
maxMs: Number(stopped.maxMs) || (sorted[sorted.length - 1] || 0),
|
|
207
|
+
layoutTotalMs: Number(stopped.layoutTotalMs) || samples.reduce((sum, sample) => sum + (Number(sample?.[2]) || 0), 0),
|
|
208
|
+
renderTotalMs: Number(stopped.renderTotalMs) || samples.reduce((sum, sample) => sum + (Number(sample?.[3]) || 0), 0),
|
|
209
|
+
copyTotalMs: Number(stopped.copyTotalMs) || samples.reduce((sum, sample) => sum + (Number(sample?.[4]) || 0), 0),
|
|
210
|
+
layoutAvgMs: Number(stopped.layoutAvgMs) || 0,
|
|
211
|
+
renderAvgMs: Number(stopped.renderAvgMs) || 0,
|
|
212
|
+
copyAvgMs: Number(stopped.copyAvgMs) || 0,
|
|
213
|
+
p50: sorted[Math.floor(sorted.length * 0.5)] || 0,
|
|
214
|
+
p95: sorted[Math.floor(sorted.length * 0.95)] || 0,
|
|
215
|
+
p99: sorted[Math.floor(sorted.length * 0.99)] || 0,
|
|
216
|
+
jankFrames: frameTimes.filter((value) => value > 16.67).length,
|
|
217
|
+
sampleCount: frameTimes.length,
|
|
218
|
+
worstFrames,
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
const perf = window.__sootsimPerf
|
|
223
|
+
const a11y = window.__sootsimA11y
|
|
224
|
+
if (!perf && !a11y) return { error: 'no perf globals available' }
|
|
225
|
+
|
|
226
|
+
const frameStats = perf?.getFrameStats?.() || {}
|
|
227
|
+
const profile = a11y?.profile?.() || {}
|
|
228
|
+
const recent = Array.isArray(frameStats.recentFrames) ? frameStats.recentFrames : []
|
|
229
|
+
const sorted = [...recent].sort((a, b) => a - b)
|
|
230
|
+
perf?.disableFrameStats?.()
|
|
231
|
+
|
|
232
|
+
return {
|
|
233
|
+
mode: 'main-thread',
|
|
234
|
+
frames: frameStats.frames || profile.syncCount || 0,
|
|
235
|
+
totalMs: frameStats.totalMs || 0,
|
|
236
|
+
avgMs: frameStats.totalMs && frameStats.frames ? frameStats.totalMs / frameStats.frames : profile.avgSyncMs || 0,
|
|
237
|
+
maxMs: frameStats.maxMs || profile.maxSyncMs || 0,
|
|
238
|
+
layoutTotalMs: frameStats.layoutTotalMs || 0,
|
|
239
|
+
p50: sorted[Math.floor(sorted.length * 0.5)] || 0,
|
|
240
|
+
p95: sorted[Math.floor(sorted.length * 0.95)] || 0,
|
|
241
|
+
p99: sorted[Math.floor(sorted.length * 0.99)] || 0,
|
|
242
|
+
jankFrames: recent.filter((value) => value > 16.67).length,
|
|
243
|
+
sampleCount: recent.length,
|
|
244
|
+
worstFrames: recent.slice().sort((a, b) => b - a).slice(0, 10),
|
|
245
|
+
}
|
|
246
|
+
})(${JSON.stringify(xe)})`);if(this.profilingEnabled=!1,e?.error)throw new Error(e.error);return e}async stopApp(){await this.evaluate(`(async () => {
|
|
247
|
+
try { await (${V}) } catch {}
|
|
248
|
+
try {
|
|
249
|
+
const regs = await navigator.serviceWorker?.getRegistrations?.()
|
|
250
|
+
await Promise.all((regs || []).map((reg) => reg.unregister()))
|
|
251
|
+
} catch {}
|
|
252
|
+
})()`)}async clearState(){await this.evaluate(`(async () => {
|
|
253
|
+
await (${V})
|
|
254
|
+
})()`)}clearKeychain(){console.warn("[flow] clearKeychain: sootsim has no keychain surface \u2014 no-op (warning)")}async copyTextFrom(e){let t=typeof e=="string"?{id:e}:e,r=await this.findElement(t);if(!r)throw new Error(`copyTextFrom: element not found: ${JSON.stringify(t)}`);let i=r.text??r.testID??"";G.set(Oe,i),console.log(`[flow] copied text: ${JSON.stringify(i)}`)}async evalScript(e){let r=await this.evaluate(`(async () => {
|
|
255
|
+
try {
|
|
256
|
+
return { ok: true, value: await (async () => { ${e} })() }
|
|
257
|
+
} catch (err) {
|
|
258
|
+
return { ok: false, error: err && err.message ? err.message : String(err) }
|
|
259
|
+
}
|
|
260
|
+
})()`);if(!r.ok)throw new Error(`evalScript failed: ${r.error}`);r.value!==void 0&&console.log("[flow] evalScript ->",r.value)}async openLink(e){let t=typeof e=="string"?e:e.link;if(!t)throw new Error("openLink: missing link");await this.evaluate(`window.location.href = ${JSON.stringify(t)}`),await m(300),await this.refreshSimId(),await this.waitForTree(3e4)}async evaluateWhen(e){if(e.visible!==void 0){let t=typeof e.visible=="string"?{text:e.visible}:e.visible;return!!await this.findElement(t)}if(e.notVisible!==void 0){let t=typeof e.notVisible=="string"?{text:e.notVisible}:e.notVisible;return!await this.findElement(t)}return e.platform!==void 0?e.platform.toLowerCase()==="ios":e.true!==void 0?e.true.toLowerCase()!=="false":!0}isOptional(e){if(e.optional===!0)return!0;let r=Object.entries(e).find(([n])=>n!=="when"&&n!=="optional"),i=r?r[1]:void 0;return!!(i&&typeof i=="object"&&"optional"in i&&i.optional)}async runStep(e,t){let r=Object.keys(e).find(i=>i!=="when")||Object.keys(e)[0];if(console.log(`[flow] step ${t+1}: ${r}`),e.when&&!await this.evaluateWhen(e.when)){console.log("[flow] (when: predicate false, skipped)");return}try{let i=!!(e.extendedWaitUntil||e.waitFor||e.scrollUntilVisible||e.launchApp||e.runFlow),n=1e4,s=this.runStepInner(e);if(i)await s;else{let a=null,p=new Promise((h,y)=>{a=setTimeout(()=>{y(new Error(`step watchdog: ${r} made no progress in ${n}ms \u2014 bridge or bundle probably hung`))},n)});try{await Promise.race([s,p])}finally{a&&clearTimeout(a)}}let l=!!(e.assertVisible||e.assertNotVisible||e.extendedWaitUntil||e.waitFor);this.stepDelay>0&&!l&&await m(this.stepDelay)}catch(i){if(this.isOptional(e)){console.log(`[flow] (optional, skipped: ${i.message.slice(0,80)})`);return}throw this.lastFailedStep={index:t,kind:r,target:e[r]},i}}async runStepInner(e){if(e.tapOn)await this.tapOn(e.tapOn);else if(e.scrollUntilVisible)await this.scrollUntilVisible(e.scrollUntilVisible);else if(e.extendedWaitUntil)await this.extendedWaitUntil(e.extendedWaitUntil);else if(e.assertVisible)await this.assertVisible(e.assertVisible);else if(e.assertNotVisible)await this.assertNotVisible(e.assertNotVisible);else if(e.inputText)await this.inputText(e.inputText);else if(e.pressKey)await this.pressKey(e.pressKey);else if(e.dispatchKey)await this.dispatchKey(e.dispatchKey);else if(e.waitFor)await this.waitFor(e.waitFor);else if(e.takeScreenshot)await this.takeScreenshot(e.takeScreenshot);else if(e.swipe)e.swipe.start&&e.swipe.end?await this.swipeCoords(e.swipe.start,e.swipe.end,e.swipe.duration):e.swipe.from?await this.swipeFrom(e.swipe.from,e.swipe.direction,e.swipe.duration):await this.swipe(e.swipe.direction,e.swipe.duration);else if(e.scroll)await this.swipe(e.scroll.direction==="DOWN"?"UP":"DOWN");else if(e.scrollTo)await this.scrollTo(e.scrollTo.id,e.scrollTo.x,e.scrollTo.y);else if(e.pinch)await this.pinch(e.pinch);else if(e.waitForAnimationToEnd)await this.waitForAnimationToEnd(typeof e.waitForAnimationToEnd=="number"?e.waitForAnimationToEnd:2e3);else if(e.back)await this.back();else if(e.hideKeyboard)await this.hideKeyboard();else if(e.launchApp)await this.launchApp(e.launchApp);else if(typeof e.wait=="number")await m(e.wait);else if(e.dumpTree)await this.dumpTree(e.dumpTree);else if(e.tapAtCoords)await this.tapAtCoords(e.tapAtCoords.x,e.tapAtCoords.y);else if(e.doubleTapAtCoords)await this.doubleTapAtCoords(e.doubleTapAtCoords.x,e.doubleTapAtCoords.y,e.doubleTapAtCoords.gapMs);else if(e.assertTreeContains)await this.assertTreeContains(e.assertTreeContains);else if(typeof e.eraseText=="number")await this.eraseText(e.eraseText);else if(e.repeat)for(let t=0;t<e.repeat.times;t++)for(let r=0;r<e.repeat.commands.length;r++)await this.runStep(e.repeat.commands[r],r);else if(e.stopApp!==void 0)await this.stopApp();else if(e.clearState!==void 0)await this.clearState();else if(e.clearKeychain!==void 0)this.clearKeychain();else if(e.copyTextFrom!==void 0)await this.copyTextFrom(e.copyTextFrom);else if(typeof e.evalScript=="string")await this.evalScript(e.evalScript);else if(e.openLink!==void 0)await this.openLink(e.openLink);else if(e.runFlow){let t=e.runFlow,r=typeof t=="string"?t:t.file,i=typeof t=="string"?void 0:t.when;if(i&&!await this.evaluateWhen(i)){console.log(`[flow] runFlow skipped (when predicate false): ${r}`);return}let n=f.resolve(this.opts.flowDir,r),s=w.readFileSync(n,"utf8"),l=this.opts.flowDir;this.opts.flowDir=f.dirname(n),await this.runFlow(Ve(s)),this.opts.flowDir=l}else throw new Error(`unsupported flow step: ${JSON.stringify(e)}`)}async runFlow(e){let t=[],r=[],i=[];for(let s of e){let l=Object.keys(s);if(l.length===1&&l[0]==="onFlowStart"&&Array.isArray(s.onFlowStart)){t.push(...s.onFlowStart);continue}if(l.length===1&&l[0]==="onFlowComplete"&&Array.isArray(s.onFlowComplete)){r.push(...s.onFlowComplete);continue}i.push(s)}if(t.length>0){console.log(`[flow] onFlowStart (${t.length} steps)`);for(let s=0;s<t.length;s++)await this.runStep(t[s],s)}let n=null;try{await this.runFlowBody(i)}catch(s){n=s instanceof Error?s:new Error(String(s))}if(r.length>0){console.log(`[flow] onFlowComplete (${r.length} steps)`);for(let s=0;s<r.length;s++)try{await this.runStep(r[s],s)}catch(l){console.warn(`[flow] onFlowComplete step ${s+1} failed: ${l instanceof Error?l.message:l}`)}}if(n)throw n}async runFlowBody(e){for(let t=0;t<e.length;t++){let r=e[t],i=typeof r.wait=="number"?r.wait:0,n=typeof r.waitFor?.timeout=="number"?r.waitFor.timeout:0,s=Math.max(6e4,i+15e3,n+15e3);if(r.runFlow){await this.runStep(r,t);continue}await Promise.race([this.runStep(r,t),new Promise((l,a)=>setTimeout(()=>a(new Error(`step ${t+1} (${Object.keys(r)[0]}) exceeded ${s}ms deadline`)),s))])}}};function ke(o){let e={},t=o,r=o.match(/^---\n([\s\S]*?)\n---\n?/);if(r){try{e=A.parse(r[1])??{}}catch(s){console.warn(` warn: could not parse frontmatter: ${s.message}`)}t=o.slice(r[0].length);let n=A.parse(t);return{frontmatter:e,steps:Array.isArray(n)?n:[]}}if(/\n---\s*\n/.test(o))try{let n=A.parseAllDocuments(o);if(n.length>=2){let s=n[0].toJS(),l=n[n.length-1].toJS();return{frontmatter:s&&typeof s=="object"?s:{},steps:Array.isArray(l)?l:[]}}}catch(n){console.warn(` warn: could not parse multi-doc flow: ${n.message}`)}let i=A.parse(t);return{frontmatter:e,steps:Array.isArray(i)?i:[]}}async function Ue(){let o=await ye(),e=o.find(r=>r.patched);if(e)return`http://localhost:${e.port}/__soot/`;let t=o[0];return t?`http://localhost:${t.port}/__soot/`:null}async function Me(o){(o.length===0||o.includes("--help")||o.includes("-h"))&&(console.log(`
|
|
261
|
+
sootsim flow \u2014 run flows or manage a draft
|
|
262
|
+
|
|
263
|
+
usage:
|
|
264
|
+
sootsim flow <flow.yaml> [options]
|
|
265
|
+
sootsim flow start
|
|
266
|
+
sootsim flow keep
|
|
267
|
+
sootsim flow end [--output <path>] [--validate] [--video]
|
|
268
|
+
sootsim flow validate <path>
|
|
269
|
+
|
|
270
|
+
options:
|
|
271
|
+
--record record a webm artifact while the flow runs
|
|
272
|
+
--profile capture perf stats while the flow runs
|
|
273
|
+
--out <dir> output directory (default: /tmp/sootsim-recordings)
|
|
274
|
+
--device <model> override the flow frontmatter device for this run
|
|
275
|
+
--slow <ms> delay between steps for natural pacing
|
|
276
|
+
--tail-wait <ms> hold the recording open after the last step so the
|
|
277
|
+
final UI state is captured (default 2000ms when --record
|
|
278
|
+
is on, 0 otherwise)
|
|
279
|
+
--url <url> load this target before running the flow
|
|
280
|
+
--screenshot-paths <mode>
|
|
281
|
+
screenshot path mode: dir (default) or flow
|
|
282
|
+
--replace <m>=<f> replace a Metro module with a local file for this run
|
|
283
|
+
--new open a fresh sim before running the flow
|
|
284
|
+
--driver <id> when paired with --new, launch through a specific
|
|
285
|
+
driver from the registry (e.g. playwright for
|
|
286
|
+
hermetic CI runs); see 'sootsim list --drivers'
|
|
287
|
+
--headless pass headless=true to the launch driver (useful
|
|
288
|
+
with --driver playwright)
|
|
289
|
+
--electron prefer opening the target in the desktop companion
|
|
290
|
+
--sim <id> target a specific current sim
|
|
291
|
+
--validate replay the drafted flow before clearing it
|
|
292
|
+
--video replay and record the drafted flow before clearing it
|
|
293
|
+
--preview record events+video, upload, and print /preview/<id>
|
|
294
|
+
--preview-open open the uploaded preview link after a successful run
|
|
295
|
+
--preview-origin <url>
|
|
296
|
+
upload target for --preview (default: auto)
|
|
297
|
+
--preview-public-origin <url>
|
|
298
|
+
public link origin for --preview (default: sootsim.com
|
|
299
|
+
for prod uploads)
|
|
300
|
+
|
|
301
|
+
frontmatter (top of flow.yaml between --- markers):
|
|
302
|
+
app: 8081 load this target before the flow starts
|
|
303
|
+
device: iphone-14 set the live device model for this flow run
|
|
304
|
+
electron: true prefer the desktop companion sim for this flow
|
|
305
|
+
|
|
306
|
+
default runtime:
|
|
307
|
+
bridge-backed flow playback against the current sim
|
|
308
|
+
if no current sim exists, flow opens the discovered target first
|
|
309
|
+
recording and profiling both run on the same bridge-backed path
|
|
310
|
+
|
|
311
|
+
examples:
|
|
312
|
+
sootsim flow login.yaml
|
|
313
|
+
sootsim flow demo.yaml --url 8081 --record --slow 500 --out ./recordings
|
|
314
|
+
sootsim flow demo.yaml --sim a2
|
|
315
|
+
sootsim flow start
|
|
316
|
+
sootsim flow keep
|
|
317
|
+
sootsim flow end --output ./flows/draft.yaml
|
|
318
|
+
sootsim flow end --output ./flows/draft.yaml --validate
|
|
319
|
+
sootsim flow end --output ./flows/draft.yaml --video
|
|
320
|
+
sootsim flow validate ./flows/draft.yaml
|
|
321
|
+
|
|
322
|
+
flow extension:
|
|
323
|
+
takeScreenshot: hero
|
|
324
|
+
takeScreenshot:
|
|
325
|
+
path: marketing/hero
|
|
326
|
+
withFrame: true
|
|
327
|
+
`),process.exit(0));let e=o[0];$.existsSync(e)||(console.error(` error: ${e} not found`),process.exit(1));let t=d=>o.find((c,v)=>o[v-1]===d),r=o.includes("--profile"),i=o.includes("--new"),n=t("--out")||"/tmp/sootsim-recordings",s=t("--screenshots")||"/tmp/sootsim-flow",l=t("--screenshot-paths")==="flow"?"flow":"dir",a=t("--device")?.trim()||"",p=o.includes("--slow")?+(t("--slow")||"500"):0,h=o.includes("--electron"),y=o.includes("--preview"),j=await Se(t("--preview-origin")),Z=t("--preview-public-origin"),Ae=o.includes("--preview-open"),Ee=o.flatMap((d,c)=>o[c-1]==="--replace"?["--replace",d]:[]),x=o.includes("--record")||y,Q=o.includes("--tail-wait")?Math.max(0,+(t("--tail-wait")||"2000")):x?2e3:0,Pe=$.readFileSync(e,"utf8"),{frontmatter:k,steps:E}=ke(Pe);E.length===0&&(console.error(" error: flow file must contain a YAML array of steps"),process.exit(1));let P=a||k.device||"",O=h||k.electron===!0,L=k.app===void 0||k.app===null?"":typeof k.app=="number"?String(k.app):k.app,ee={stripBooleanFlags:["--record","--profile","--electron","--new","--preview","--preview-open","--headless"],stripValueFlags:["--out","--device","--slow","--tail-wait","--url","--replace","--screenshots","--screenshot-paths","--preview-origin","--preview-public-origin","--driver"]},S=z(o,ee),Ie=t("--url")||"";O&&!we()&&(console.error(" error: desktop companion not found. install or build it first with `bun run build:electron`"),process.exit(1));let te=O?"desktop companion":"bridge",_e=L?` | target: ${L}`:"";console.log(`
|
|
328
|
+
sootsim flow \u2014 ${g.basename(e)}
|
|
329
|
+
${E.length} steps | ${te}${_e}${x?" | recording":""}${r?" | profiling":""}${p?` | ${p}ms delay`:""}
|
|
330
|
+
`),y&&ae({event:"preview_flow_started",properties:{flowName:g.basename(e),stepCount:E.length,mode:te,electron:O,record:x,profile:r,previewOrigin:j}});let F=Ie||L||"",K=i||O&&S.simIdSource!=="flag",re=!1;if(!F&&!K&&S.simIdSource==="none"){let d=de(S);try{let c=await d.listSims(),v=c.find(R=>R.isPrimary&&R.readyState==="open"),D=c.find(R=>R.readyState==="open"),se=v??D;se&&(re=!0,console.log(` reusing active sim: ${se.id}`))}catch{}finally{d.close()}}if(!F&&!re&&(K||S.simIdSource==="none")){let d=await Ue();d||(console.error(" error: no current sim and no sootsim target found"),await H(),process.exit(1)),F=d}if(F&&P){let d=new URL(await he(F));d.searchParams.set("device",P),F=d.toString()}if(F){let d=[F];d.push(...Ee),K&&d.push("--new"),S.simIdSource==="flag"&&S.simId&&d.push("--sim",S.simId);let c=t("--driver");c&&d.push("--driver",c),o.includes("--headless")&&d.push("--headless"),await ge(d,{port:S.wsPort,timeoutMs:S.commandTimeoutMs})}let I=z(o,ee),ie=I.simIdSource==="flag"?I.simId:le()||I.simId,T=ce(I.wsPort,{commandTimeoutMs:I.commandTimeoutMs,simId:ie,fallbackOnMissingSimId:!1}),u,oe=async()=>{if(!P)return!1;let d=await T.send({type:"evaluate",simId:u.simId,code:"window.location.href"});if(typeof d=="string"&&d.length>0){let c=new URL(d);c.searchParams.set("device",P),u.setSimRouteHint(c.toString())}return!!await T.send({type:"call",simId:u.simId,path:"SootSim.bridges.settings.set",args:["deviceModel",P]})};u=new W(T,{screenshotDir:s,flowDir:g.dirname(g.resolve(e)),screenshotPathMode:l,simId:ie,recordingOutputDir:x?n:void 0,billingOriginOverride:y?j:void 0,allowGitHubRecording:y,onAfterLaunch:async()=>{await oe()&&await u.waitForTree(12e4),y&&await T.send({type:"evaluate",simId:u.simId,code:`(() => {
|
|
331
|
+
const r = window.SootSim?.bridges?.eventRecorder ?? window.__sootsimEventRecorder
|
|
332
|
+
return r?.start?.() ?? false
|
|
333
|
+
})()`})}}),p&&(u.stepDelay=p);let M=null,b=null,_=null,J=null,N=0,Ce=!!E[0]?.launchApp;try{await u.waitForTree(12e4),await oe()&&await u.waitForTree(12e4),x&&(Ce?u.prepareRecording():await u.startRecording()),r&&await u.startProfile(),y&&(await T.send({type:"evaluate",simId:u.simId,code:`(() => {
|
|
334
|
+
const r = window.SootSim?.bridges?.eventRecorder ?? window.__sootsimEventRecorder
|
|
335
|
+
return r?.start?.() ?? false
|
|
336
|
+
})()`})||console.warn(" warn: eventRecorder.start() returned false \u2014 preview will upload bundle without replay events")),await u.runFlow(E),r&&(M=await u.stopProfile()),x&&Q>0&&await new Promise(c=>setTimeout(c,Q)),x&&(b=await u.stopRecording(),_=u.getLastRecordingDurationMs()),y&&(J=await T.send({type:"evaluate",simId:u.simId,code:`(() => {
|
|
337
|
+
const r = window.SootSim?.bridges?.eventRecorder ?? window.__sootsimEventRecorder
|
|
338
|
+
return r?.stop?.() ?? []
|
|
339
|
+
})()`}),console.log(` captured ${J.length} replay events`)),console.log(`
|
|
340
|
+
+ completed (${E.length} steps)`),M&&Te(M),b&&console.log(` video: ${b}`),console.log()}catch(d){if(r&&!M)try{M=await u.stopProfile()}catch{}if(x&&!b)try{b=await u.stopRecording(),_=u.getLastRecordingDurationMs()}catch(c){console.warn(` recording stop failed: ${c?.message||String(c)}`)}console.error(`
|
|
341
|
+
x failed: ${d.message}
|
|
342
|
+
`),M&&(console.log(" partial profile:"),Te(M)),b&&console.log(` partial video: ${b}`);try{let c=u.lastFailedStep,v=c?`step-${String(c.index+1).padStart(2,"0")}-${c.kind}`:"unstaged",D=g.join(s,v);await u.captureFailureBundle(D,{error:d,stepIndex:c?.index,stepKind:c?.kind,stepTarget:c?.target}),console.log(` failure bundle: ${D}`),console.log(" (contents: screenshot.png, describe.json, a11y.txt, tree.txt, console.json, error.json)")}catch(c){try{let v=g.join(s,"error.png");await u.captureFailureScreenshot(v),console.log(` error screenshot: ${v}`)}catch{}console.log(` (failure bundle capture failed: ${c instanceof Error?c.message:String(c)})`)}await ue(T,{errorsCommand:`sootsim get errors 5${u.simId?` --sim ${u.simId}`:""}`,warningsCommand:`sootsim get warnings 5${u.simId?` --sim ${u.simId}`:""}`,requestsCommand:`sootsim get requests 5${u.simId?` --sim ${u.simId}`:""}`}),N=1}finally{T.close()}if(N===0&&y)try{let d=await Be(J??[]),c=["--origin",j,"--events",d];Z&&c.push("--public-origin",Z),b&&c.push("--video",b),b&&_&&Number.isFinite(_)&&c.push("--video-duration-ms",String(Math.round(_))),u.simId&&c.push("--sim",u.simId),Ae&&c.push("--open"),console.log(`
|
|
343
|
+
preparing preview upload\u2026`);let{runUpload:v}=await import("./upload-UHTVCGGR.js");await v(c,{})}catch(d){console.error(` preview upload failed: ${d?.message||d}`),N=1}return await H(),N}async function Be(o){let{gzipSync:e}=await import("zlib"),t=o.map(n=>JSON.stringify(n)).join(`
|
|
344
|
+
`)+(o.length?`
|
|
345
|
+
`:""),r=e(Buffer.from(t,"utf8")),i=g.join($e(),`sootsim-events-${Date.now()}.jsonl.gz`);return $.writeFileSync(i,r),console.log(` events: ${o.length} written to ${i} (${r.length} bytes gz)`),i}async function We(o){let e=o[0],t=r=>o.find((i,n)=>o[n-1]===r);switch(e){case"start":{let{path:r,state:i}=me();console.log(" flow draft started"),console.log(` session: ${r}`),console.log(` steps: ${i.steps.length}`);return}case"keep":case"good":{let r=pe();if(r.active||(console.error(" no active flow draft \u2014 run `sootsim flow start` first"),process.exit(1)),!r.kept){console.log(" no pending action to keep");return}console.log(` kept: ${r.candidate.summary}`),console.log(` steps: ${r.stepCount}`);return}case"end":{let r=t("--output")||(o[1]&&!o[1].startsWith("-")?o[1]:void 0),i=o.includes("--validate")||o.includes("--video"),n=o.includes("--video"),s=fe(r||(i?Le():void 0));if(s.active||(console.error(" no active flow draft \u2014 run `sootsim flow start` first"),process.exit(1)),i){let l=Ke(o,s.outputPath),a=await Me(l);if(a!==0){console.error(`
|
|
346
|
+
validation failed \u2014 draft preserved so you can keep iterating`),process.exitCode=a;return}q(),console.log(` flow draft validated (${s.stepCount} step${s.stepCount===1?"":"s"})`),s.outputPath&&console.log(` saved: ${s.outputPath}`),n&&console.log(" video: recorded during validation run");return}if(q(),console.log(` flow draft ended (${s.stepCount} step${s.stepCount===1?"":"s"})`),s.outputPath){console.log(` saved: ${s.outputPath}`),console.log(` next: sootsim flow ${s.outputPath} --record`);return}console.log(""),process.stdout.write(s.yaml);return}case"validate":{let r=o[1];(!r||r.startsWith("-"))&&(console.error(" usage: sootsim flow validate <path>"),process.exit(1));let i=je(r);if(i.length>0){console.error(` x ${r} failed validation:`);for(let n of i)console.error(` - ${n}`);process.exit(1)}console.log(` + ${r} looks valid`);return}}}var Fe=new Set(["tapOn","inputText","pressKey","dispatchKey","hideKeyboard","swipe","pinch","scroll","scrollUntilVisible"]);function je(o){let e=[];if(!$.existsSync(o))return[`file not found: ${o}`];let t;try{t=$.readFileSync(o,"utf8")}catch(n){return[`cannot read file: ${n.message}`]}if(t.trim().length===0)return["file is empty"];let r;try{r=ke(t)}catch(n){return[`yaml parse error: ${n.message}`]}if(!Array.isArray(r.steps)||r.steps.length===0)return e.push("flow body must be a non-empty YAML array of steps"),e;let i=0;for(let n=0;n<r.steps.length;n++){let s=r.steps[n];s&&typeof s=="object"?Object.keys(s).some(a=>Fe.has(a))&&(i+=1):typeof s=="string"&&Fe.has(s)&&(i+=1)}return i===0&&e.push("no interaction steps found (expected at least one tapOn / inputText / pressKey / swipe / scroll)"),e}async function ct(o){let e=o[0];if(e==="start"||e==="keep"||e==="good"||e==="end"||e==="validate")return await We(o),0;let t=await Me(o);return t!==0&&(process.exitCode=t),t}function Te(o){let e=o.avgMs>0?(1e3/o.avgMs).toFixed(1):"?",t=o.sampleCount>0?(o.jankFrames/o.sampleCount*100).toFixed(1):"0";console.log(`
|
|
347
|
+
profile:`),console.log(` frames: ${o.frames}`),console.log(` total: ${o.totalMs.toFixed(1)}ms`),console.log(` avg: ${o.avgMs.toFixed(2)}ms (${e} fps)`),console.log(` max: ${o.maxMs.toFixed(2)}ms`),o.layoutAvgMs!==void 0&&console.log(` breakdown: layout ${o.layoutAvgMs.toFixed(2)}ms | render ${o.renderAvgMs?.toFixed(2)||"0.00"}ms | copy ${o.copyAvgMs?.toFixed(2)||"0.00"}ms`),console.log(` p95: ${o.p95.toFixed(2)}ms`),console.log(` p99: ${o.p99.toFixed(2)}ms`),console.log(` jank: ${o.jankFrames}/${o.sampleCount} (${t}%) >16.67ms`);let r=Array.isArray(o.worstFrames)?o.worstFrames:[];if(r.length!==0){if(console.log(`
|
|
348
|
+
worst frames:`),o.mode==="render-worker"){console.log(" total layout render copy t+");for(let i of r){let[n,s,l,a,p]=i;console.log(` ${s.toFixed(2).padStart(7)} ${l.toFixed(2).padStart(7)} ${a.toFixed(2).padStart(7)} ${p.toFixed(2).padStart(7)} ${String(n).padStart(5)}`)}return}console.log(` ${r.map(i=>i.toFixed(2)).join(", ")}`)}}function Le(){return g.join($e(),`sootsim-flow-draft-${Date.now()}.yaml`)}function Ke(o,e){if(!e)throw new Error("validated flow draft requires an output path");let t=[e];for(let r=1;r<o.length;r++){let i=o[r];if(!(i==="--validate"||i==="--video")){if(i==="--output"){r+=1;continue}r===1&&!i.startsWith("-")||t.push(i)}}return!t.includes("--record")&&o.includes("--video")&&t.push("--record"),t}export{ke as a,Ue as b,Me as c,ct as d};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
/*! sootsim v0.1.38 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
|
|
2
|
+
import{a as R}from"./chunk-IE2WYVJF.js";import{l as D}from"./chunk-6UJXRT7F.js";import{a as T}from"./chunk-VIEK76DX.js";function Y(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.type=="string"&&typeof t.ts=="number"}function I(e){let t=e.trim();if(!t)return null;try{let r=JSON.parse(t);return Y(r)?r:null}catch{return null}}import{randomBytes as G,createHash as q}from"node:crypto";import m from"node:fs";import y from"node:path";var N=null;function _(){if(N)return N;let e=process.env.SOOTSIM_USER_DATA_DIR;return e||D()}function h(){return _()}function U(){return y.join(_(),"attached-projects.json")}function $(){return{version:1,attachedProjects:[],previewAttachments:[],agentSessions:[]}}function S(){let e=U(),t;try{t=m.readFileSync(e,"utf8")}catch(r){if(r.code==="ENOENT")return $();throw r}try{let r=JSON.parse(t);if(!r||typeof r!="object")throw new Error("not an object");return{version:1,attachedProjects:Array.isArray(r.attachedProjects)?r.attachedProjects:[],previewAttachments:Array.isArray(r.previewAttachments)?r.previewAttachments:[],agentSessions:Array.isArray(r.agentSessions)?r.agentSessions:[]}}catch(r){let n=`${e}.corrupt-${Date.now()}`;try{m.renameSync(e,n),console.warn(`[sootsim] attached-projects.json was unparseable; quarantined to ${n}. original error: ${r.message}`)}catch{}return $()}}function X(e){let t=U();m.mkdirSync(y.dirname(t),{recursive:!0});let r=`${t}.tmp-${process.pid}-${Date.now()}`,n=m.openSync(r,"w",384);try{m.writeFileSync(n,JSON.stringify(e,null,2)),m.fsyncSync(n)}finally{m.closeSync(n)}m.renameSync(r,t)}function w(e){let t=S();return e(t),X(t),t}function B(e){return q("sha256").update(y.resolve(e)).digest("hex").slice(0,16)}function K(){return`s_${G(10).toString("hex")}`}function ge(e){let t=y.resolve(e.cwd),r=B(t),n;return w(o=>{let s=o.attachedProjects.find(c=>c.id===r);if(s){let c={...s,...e,id:r,cwd:t,sourceRoots:e.sourceRoots??s.sourceRoots,knownBundleUrls:e.knownBundleUrls??s.knownBundleUrls,pinnedSourceResolutions:e.pinnedSourceResolutions??s.pinnedSourceResolutions,telemetry:e.telemetry??s.telemetry,updatedAt:Date.now(),createdAt:s.createdAt},g=o.attachedProjects.indexOf(s);o.attachedProjects[g]=c,n=c;return}let a=Date.now(),d={id:r,name:e.name??y.basename(t),cwd:t,repoRoot:e.repoRoot,sourceRoots:e.sourceRoots??[t],framework:e.framework??"unknown",bundleId:e.bundleId,knownBundleUrls:e.knownBundleUrls??[],preferredProvider:e.preferredProvider??"codex",preferredTransport:e.preferredTransport??"tmux",editorOpenCommand:e.editorOpenCommand,moshiWebhookToken:e.moshiWebhookToken,pinnedSourceResolutions:e.pinnedSourceResolutions??{},isolateDiscovery:e.isolateDiscovery,git:e.git,telemetry:e.telemetry??{lastOpened:0,runsCompleted:0},createdAt:a,updatedAt:a};o.attachedProjects.push(d),n=d}),n}function F(e){return S().attachedProjects.find(t=>t.id===e)??null}function ye(){return S().attachedProjects}var Q=336*60*60*1e3;function he(e,t={}){w(r=>{let n=r.attachedProjects.find(s=>s.id===e);if(!n)return;let o=t.ts??Date.now();if(n.telemetry.runsCompleted=(n.telemetry.runsCompleted??0)+1,typeof t.usd=="number"&&Number.isFinite(t.usd)&&t.usd>=0){let s=n.telemetry.costHistory??[],a=o-Q,d=s.filter(c=>c.ts>=a);d.push({ts:o,usd:t.usd}),n.telemetry.costHistory=d}n.updatedAt=o})}function Se(e,t=Date.now()){let r=t-6048e5,n=e.telemetry.costHistory??[],o=0;for(let s of n)s.ts>=r&&(o+=s.usd);return o}function we(e){w(t=>{t.attachedProjects=t.attachedProjects.filter(r=>r.id!==e),t.agentSessions=t.agentSessions.filter(r=>r.projectId!==e),t.previewAttachments=t.previewAttachments.filter(r=>r.projectId!==e)})}function M(e){let t;return w(r=>{if(e.id){let a=r.agentSessions.find(d=>d.id===e.id);if(a){let d={...a,...e,lastSeenAt:Date.now()},c=r.agentSessions.indexOf(a);r.agentSessions[c]=d,t=d;return}}let n=r.attachedProjects.find(a=>a.id===e.projectId);if(!n)throw new Error(`upsertSession: no AttachedProject with id=${e.projectId}`);let o=Date.now(),s={id:e.id??K(),projectId:e.projectId,provider:e.provider,transport:e.transport??n.preferredTransport,cwd:e.cwd??n.cwd,claudeSessionUuid:e.claudeSessionUuid,tmuxSessionName:e.tmuxSessionName,wrapperPid:e.wrapperPid,status:e.status??"idle",needsAttention:e.needsAttention??!1,lastPrompt:e.lastPrompt,lastSummary:e.lastSummary,lastTurnFiles:e.lastTurnFiles,currentlyEditing:e.currentlyEditing,lastSeenAt:o,createdAt:o};r.agentSessions.push(s),t=s}),t}function k(e){return S().agentSessions.find(t=>t.id===e)??null}function C(e){let t=S().agentSessions;return e?t.filter(r=>r.projectId===e):t}function v(e,t){w(r=>{let n=r.agentSessions.find(s=>s.id===e);if(!n)return;let o=r.agentSessions.indexOf(n);r.agentSessions[o]={...n,...t,id:n.id,projectId:n.projectId,createdAt:n.createdAt,lastSeenAt:Date.now()}})}async function ve(){if(S().attachedProjects.length>0)return;let t;try{t=(await import("./demo-app-registry-DMMWYL7G.js")).APPS}catch(n){console.warn("[sootsim] seedFromDemoAppRegistry: could not load demo registry:",n.message);return}if(!Array.isArray(t))return;let r=t;w(n=>{for(let o of r){if(!m.existsSync(o.dir))continue;let s=y.resolve(o.dir),a=B(s);if(n.attachedProjects.some(c=>c.id===a))continue;let d=Date.now();n.attachedProjects.push({id:a,name:o.label,cwd:s,sourceRoots:[s],framework:o.framework,knownBundleUrls:[`http://localhost:${o.preferredPort}/index.bundle`],preferredProvider:"codex",preferredTransport:"tmux",pinnedSourceResolutions:{},telemetry:{lastOpened:0,runsCompleted:0},createdAt:d,updatedAt:d})}})}import{spawn as V,spawnSync as z}from"node:child_process";import{randomUUID as Z}from"node:crypto";import i,{constants as f}from"node:fs";import u from"node:path";import ee from"node:readline";function j(e){return u.join(h(),"sessions",e)}function W(e){return u.join(j(e),"prompt.in")}function J(e){return u.join(j(e),"events.out")}function te(e){return u.join(h(),"transcripts",`${e}.log`)}function O(e,t){if(!e)return!1;try{process.kill(e,0)}catch{return!1}return!(t&&!i.existsSync(j(t)))}function re(){if(process.env.SOOTSIM_BIN)return{cmd:process.env.SOOTSIM_BIN,prefixArgs:[]};if(process.versions.electron){let n=process.resourcesPath;if(n){let o=[u.join(n,"bin","sootsim"),u.join(n,"bin",`sootsim-${process.platform}-${process.arch}`)];for(let s of o)if(i.existsSync(s))return{cmd:s,prefixArgs:[]}}}let e=ne();if(e)return e;let t=process.argv[0],r=process.argv[1];if(r&&/\.(ts|tsx|mjs|cjs|js)$/.test(r))return{cmd:t,prefixArgs:[r]};if(!r||r.includes("/.bin/"))throw new Error("sootsim CLI not found. set SOOTSIM_BIN to the path of the sootsim binary, or build the workspace CLI via `bun run --cwd packages/sootsim build:cli`.");return{cmd:t,prefixArgs:[]}}function ne(){try{let e=se();if(!e)return null;let t=`sootsim-${process.platform}-${process.arch}`,r=u.join(e,"dist-bin",t);if(i.existsSync(r))return{cmd:r,prefixArgs:[]};let n=u.join(e,"dist-cli","bin.js");if(i.existsSync(n)){try{let o=u.join(e,"cli","commands","agent-wrapper.ts");if(i.existsSync(o)){let s=i.statSync(o).mtimeMs;i.statSync(n).mtimeMs<s&&console.warn("[sootsim] dist-cli/bin.js is older than agent-wrapper.ts \u2014 rebuild with `bun run --cwd packages/sootsim build:cli` (watch:cli:binary builds dist-bin/ instead).")}}catch{}return{cmd:process.execPath,prefixArgs:[n]}}return null}catch{return null}}function se(){try{let r=T.resolve("sootsim/package.json");return u.dirname(r)}catch{}let e=oe();if(!e)return null;let t=u.dirname(e);for(let r=0;r<8;r++){let n=u.join(t,"package.json");try{if(i.existsSync(n)&&JSON.parse(i.readFileSync(n,"utf8")).name==="sootsim")return t}catch{}let o=u.dirname(t);if(o===t)break;t=o}return null}function oe(){try{let e=import.meta.url;return!e||!e.startsWith("file://")?null:decodeURIComponent(e.slice(7))}catch{return null}}async function ie(e,t,r){let n=u.join(h(),"locks");i.mkdirSync(n,{recursive:!0});try{i.chmodSync(n,448)}catch{}let o=u.join(n,`start-${e}-${t}.lock`),s=Date.now()+4e3,a=null;for(;a===null;)try{a=i.openSync(o,f.O_WRONLY|f.O_CREAT|f.O_EXCL,384)}catch(d){if(d.code!=="EEXIST")throw d;try{let c=Number(i.readFileSync(o,"utf8").trim());if(c&&!ce(c)){i.unlinkSync(o);continue}}catch{}if(Date.now()>s)throw new Error(`another start is in progress for project=${e} provider=${t} (lock: ${o})`);await new Promise(c=>setTimeout(c,50))}try{return i.writeFileSync(a,String(process.pid)),await r()}finally{try{i.closeSync(a)}catch{}try{i.unlinkSync(o)}catch{}}}function ce(e){try{return process.kill(e,0),!0}catch{return!1}}function L(e){let t=u.dirname(e);i.mkdirSync(t,{recursive:!0});try{i.chmodSync(t,448)}catch{}if(i.existsSync(e))try{if(i.statSync(e).isFIFO()){try{i.chmodSync(e,384)}catch{}return}i.unlinkSync(e)}catch{i.unlinkSync(e)}let r=z("mkfifo",["-m","600",e]);if(r.status!==0)throw new Error(`mkfifo(${e}) failed: ${r.stderr?.toString().trim()||"unknown error"}`)}var l=class extends Error{code;constructor(t,r){super(r),this.code=t}};async function Te(e){let t=F(e.projectId);if(!t)throw new l("NO_PROJECT",`no project with id=${e.projectId}`);let r=e.provider||t.preferredProvider||"codex";return ie(t.id,r,async()=>{let n=C(t.id).find(p=>p.provider===r&&p.status!=="ended"&&O(p.wrapperPid,p.id));if(n)throw new l("ALREADY_RUNNING",`session already running for project=${t.id} provider=${r} (session ${n.id}, pid ${n.wrapperPid}). end it first with \`sootsim agent end <sessionId>\`.`);let o=r==="claude"?Z():void 0,s=M({projectId:t.id,provider:r,transport:"pty",cwd:t.cwd,status:"idle",claudeSessionUuid:o}),a=W(s.id),d=J(s.id),c=te(s.id);L(a),L(d);let g=u.dirname(c);i.mkdirSync(g,{recursive:!0});try{i.chmodSync(g,448)}catch{}let{cmd:A,prefixArgs:H}=re(),P=[...H,"agent-wrapper","--session-id",s.id,"--project-id",t.id,"--provider",r,"--cwd",t.cwd,"--prompt-in",a,"--events-out",d,"--transcript",c];e.codexBin&&P.push("--codex-bin",e.codexBin),e.claudeBin&&P.push("--claude-bin",e.claudeBin),e.freshThread&&P.push("--fresh-thread"),o&&P.push("--claude-session-uuid",o);let x=V(A,P,{detached:!0,stdio:"ignore",env:{...process.env,SOOTSIM_USER_DATA_DIR:h()}});x.unref();let E=e.readyTimeoutMs??6e3,b=await ae(d,p=>p.type==="ready"||p.type==="error",E);if(!b||b.type==="error"){if(x.pid)try{process.kill(x.pid,"SIGTERM")}catch{}try{i.rmSync(j(s.id),{recursive:!0,force:!0})}catch{}v(s.id,{status:"ended"});let p=b&&b.type==="error"?b.message:`no ready event within ${E}ms`;throw new l("WRAPPER_FAILED",p)}return v(s.id,{wrapperPid:x.pid,status:"idle"}),{session:k(s.id),wrapperPid:x.pid}})}async function De(e,t){let r=k(e);if(!r)throw new l("NO_SESSION",`no session with id=${e}`);if(!O(r.wrapperPid,e))throw v(e,{status:"ended"}),new l("NOT_ALIVE",`session wrapper is not alive (pid=${r.wrapperPid}). start a new session.`);let n=W(e);if(!i.existsSync(n))throw new l("NO_FIFO",`prompt FIFO missing: ${n}`);let o=i.openSync(n,f.O_WRONLY);try{let s=R(t);if(!s)throw new l("EMPTY_PROMPT","prompt text is empty");i.writeSync(o,s+`
|
|
3
|
+
`)}finally{i.closeSync(o)}v(e,{lastPrompt:t.displayText??t.text,status:"working"})}async function Re(e){let t=k(e);if(!t)throw new l("NO_SESSION",`no session with id=${e}`);if(O(t.wrapperPid,e))try{process.kill(t.wrapperPid,"SIGTERM")}catch{}let r=j(e),n=h();if(r.startsWith(n))try{i.rmSync(r,{recursive:!0,force:!0})}catch{}v(e,{status:"ended",wrapperPid:void 0})}function Ne(e,t){let r=J(e);if(!i.existsSync(r))throw new l("NO_FIFO",`events FIFO missing: ${r}`);let n=i.openSync(r,f.O_RDWR),o=i.createReadStream("",{fd:n,autoClose:!0}),s=ee.createInterface({input:o,crlfDelay:1/0});s.on("line",d=>{let c=I(d);c&&t(c)});let a=!1;return()=>{if(!a){a=!0;try{s.close()}catch{}try{o.destroy()}catch{}}}}async function ae(e,t,r){let n=i.openSync(e,f.O_RDWR|f.O_NONBLOCK),o=Buffer.alloc(8192),s="",a=Date.now()+r;try{for(;Date.now()<a;){let d=0;try{d=i.readSync(n,o,0,o.length,null)}catch(c){if(c.code!=="EAGAIN")throw c;d=0}if(d>0){s+=o.subarray(0,d).toString("utf8");let c;for(;(c=s.indexOf(`
|
|
4
|
+
`))>=0;){let g=s.slice(0,c);s=s.slice(c+1);let A=I(g);if(A&&t(A))return A}}else await new Promise(c=>setTimeout(c,30))}return null}finally{i.closeSync(n)}}export{I as a,h as b,ge as c,F as d,ye as e,he as f,Se as g,we as h,k as i,C as j,v as k,ve as l,j as m,W as n,J as o,te as p,O as q,re as r,l as s,Te as t,De as u,Re as v,Ne as w};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
/*! sootsim v0.1.38 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
|
|
2
|
+
import{b as d}from"./chunk-2ABGQIW7.js";import{existsSync as S,mkdirSync as h,readFileSync as b,writeFileSync as H,rmSync as m}from"fs";import{tmpdir as w}from"os";import{dirname as v,join as p}from"path";var y=new Map;function i(e,r){y.set(e,r)}var a=1;function s(){return p(w(),`sootsim-cli-hints-${d()}.json`)}function l(){return p(w(),"sootsim-cli-hints-global.json")}function u(e){if(!S(e))return{version:a,shown:{}};try{let r=JSON.parse(b(e,"utf8"));return r?.version!==a||!r?.shown?{version:a,shown:{}}:r}catch{return{version:a,shown:{}}}}function f(e,r){try{h(v(e),{recursive:!0}),H(e,JSON.stringify(r)+`
|
|
3
|
+
`)}catch{}}function F(){let e=(process.env.SOOTSIM_HINTS||"").toLowerCase();return e==="off"||e==="0"||e==="false"?"off":e==="always"||e==="verbose"?"always":"normal"}function x(e,r){let o=F();if(o==="off")return!1;if(o==="always"||r==="always")return!0;let n=Date.now();if(r==="once-per-identity"){let t=u(s());return t.shown[e]?!1:(t.shown[e]=n,f(s(),t),!0)}if(r==="once-ever"){let t=u(l());return t.shown[e]?!1:(t.shown[e]=n,f(l(),t),!0)}if(typeof r=="object"&&"cooldownMs"in r){let t=u(s()),c=t.shown[e]??0;return n-c<r.cooldownMs?!1:(t.shown[e]=n,f(s(),t),!0)}return!0}function M(e,...r){let o=y.get(e);if(!o)return process.env.SOOTSIM_HINTS_DEBUG&&console.error(` [hints] no hint registered for id "${e}"`),!1;if(!x(e,o.frequency))return!1;let n=o.render(...r);if(n==null)return!1;let t=Array.isArray(n)?n:[n],c=o.stream==="error"?console.error:console.log;for(let g of t)c(` hint: ${g}`);return!0}function O(){m(s(),{force:!0})}function k(){m(l(),{force:!0})}function T(){return Array.from(y.entries()).map(([e,r])=>({id:e,frequency:r.frequency}))}i("app-still-loading",{frequency:{cooldownMs:6e4},render:e=>`app may still be loading (${e} nodes). run \`sootsim wait ready\` first.`});i("wait-selector-for-missing-testid",{frequency:"once-per-identity",render:e=>`sootsim wait selector ${e}`,stream:"error"});i("prefer-cli-over-eval",{frequency:"once-per-identity",render:e=>e.length?["try the CLI shortcut instead:",...e.map(r=>` ${r}`)]:null,stream:"error"});i("describe-use-filters",{frequency:"once-per-identity",render:()=>["describe output is long. narrow it with:"," sootsim describe --only '*Bottom Sheet*'"," sootsim describe --testid-like 'swap-*'"," sootsim describe --subtree <testID>"]});i("subtree-root-not-found",{frequency:"always",render:e=>`no node with testID/id "${e}" \u2014 try \`sootsim find --testid ${e}\` to discover available ids.`,stream:"error"});export{M as a,O as b,k as c,T as d};
|