dsh-notch 0.3.1
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/BASELINE.md +13 -0
- package/DESIGN.md +34 -0
- package/LICENSE +21 -0
- package/README.en.md +136 -0
- package/README.md +145 -0
- package/cordis.yml +5 -0
- package/docs/motion-audit.md +65 -0
- package/docs/motion-continuity.md +77 -0
- package/docs/releases/v0.3.0.md +20 -0
- package/dshx.yml +14 -0
- package/macos/Package.swift +17 -0
- package/macos/STATUS-MOTION.md +49 -0
- package/macos/Sources/Client.swift +139 -0
- package/macos/Sources/IdleRobot.swift +423 -0
- package/macos/Sources/NotchMarkdown.swift +266 -0
- package/macos/Sources/Panel.swift +153 -0
- package/macos/Sources/Resources/Idle/balance.json +1 -0
- package/macos/Sources/Resources/Idle/blink.json +1 -0
- package/macos/Sources/Resources/Idle/cube-in.json +1 -0
- package/macos/Sources/Resources/Idle/dance.json +1 -0
- package/macos/Sources/Resources/Idle/hop.json +1 -0
- package/macos/Sources/Resources/Idle/nod.json +1 -0
- package/macos/Sources/Resources/Idle/satellite-in.json +1 -0
- package/macos/Sources/Resources/Idle/satellite-out.json +1 -0
- package/macos/Sources/Resources/Idle/scan.json +1 -0
- package/macos/Sources/Resources/Idle/sleep.json +1 -0
- package/macos/Sources/Resources/Idle/sneeze.json +1 -0
- package/macos/Sources/Resources/Idle/stretch.json +1 -0
- package/macos/Sources/Resources/Idle/tilt.json +1 -0
- package/macos/Sources/ReviewStudio.swift +337 -0
- package/macos/Sources/RootView.swift +1093 -0
- package/macos/Sources/StatusOrbit.swift +642 -0
- package/macos/Sources/main.swift +153 -0
- package/macos/Tests/ExpandedHeightProbe.swift +108 -0
- package/macos/Tests/GeometryProbe.swift +98 -0
- package/macos/Tests/IdleProbe.swift +294 -0
- package/macos/Tests/MotionProbe.swift +106 -0
- package/macos/Tests/OutcomeProbe.swift +133 -0
- package/macos/Tests/ScrollbarProbe.swift +91 -0
- package/macos/Tests/expanded-height.sh +13 -0
- package/macos/Tests/geometry.sh +14 -0
- package/macos/Tests/idle.sh +14 -0
- package/macos/Tests/motion.sh +14 -0
- package/macos/Tests/outcome.sh +14 -0
- package/macos/Tests/scrollbar.sh +13 -0
- package/package.json +46 -0
- package/src/board.ts +299 -0
- package/src/browse-sync.ts +59 -0
- package/src/dsh-notch.ts +60 -0
- package/src/http.ts +215 -0
- package/src/session-state.ts +31 -0
- package/src/store.ts +49 -0
- package/src/types.ts +65 -0
- package/tests/answer-lifecycle.test.mjs +23 -0
- package/tests/board.test.mjs +7 -0
- package/tests/browse-sync.test.mjs +20 -0
- package/tests/mirror.test.mjs +4 -0
- package/tests/peer-range.test.mjs +21 -0
- package/tests/session-state.test.mjs +54 -0
- package/tests/unread-hold.test.mjs +90 -0
- package/tools/desktop-shell/README.md +56 -0
- package/tools/desktop-shell/child-log.mjs +6 -0
- package/tools/desktop-shell/child-log.test.mjs +14 -0
- package/tools/desktop-shell/package-recovery.py +78 -0
- package/tools/desktop-shell/recovery-probe.cjs +50 -0
- package/tools/desktop-shell/renderer-recovery.mjs +95 -0
- package/tools/desktop-shell/renderer-recovery.test.mjs +24 -0
- package/tools/diagnostics/completion-watch.py +101 -0
- package/tools/diagnostics/completion-watch.test.py +17 -0
- package/tools/diagnostics/renderer-diagnostics.mjs +56 -0
- package/tools/diagnostics/renderer-diagnostics.test.mjs +32 -0
- package/tools/idle/LICENSE.open-bot-motion +21 -0
- package/tools/idle/export.mjs +40 -0
- package/tools/idle/index.html +4 -0
- package/tools/idle/motions.js +83 -0
- package/tools/idle/original.js +1673 -0
- package/tools/idle/renderer.js +1673 -0
- package/tools/recording/Client.swift +76 -0
- package/tools/recording/DemoCatalog.swift +174 -0
- package/tools/recording/README.md +23 -0
- package/tools/recording/build.sh +41 -0
- package/tools/recording/main.swift +100 -0
- package/tools/review/ReviewStudio.swift +236 -0
- package/tools/review/audit.sh +19 -0
- package/tools/review/build.sh +7 -0
- package/tools/review/main.swift +158 -0
- package/tools/review/render-audit.swift +32 -0
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import {test} from 'node:test'
|
|
2
|
+
import assert from 'node:assert/strict'
|
|
3
|
+
import {EventEmitter} from 'node:events'
|
|
4
|
+
import {installRendererRecovery} from './renderer-recovery.mjs'
|
|
5
|
+
|
|
6
|
+
function fixture(options={}) {
|
|
7
|
+
const app=new EventEmitter(),window=new EventEmitter(),contents=new EventEmitter(),rows=[],failures=[];
|
|
8
|
+
let reloaded=0,destroyed=false,pid=17,loading=false,clock=0,seq=0;
|
|
9
|
+
const jobs=new Map();
|
|
10
|
+
window.webContents=contents;window.isDestroyed=()=>destroyed;
|
|
11
|
+
contents.isDestroyed=()=>destroyed;contents.getOSProcessId=()=>pid;
|
|
12
|
+
contents.isLoading=()=>loading;contents.reload=()=>{reloaded++;loading=true;contents.emit('did-start-loading')};
|
|
13
|
+
const scheduler={setTimeout:(fn,ms)=>{const id=++seq;jobs.set(id,{fn,at:clock+ms});return id},clearTimeout:id=>jobs.delete(id)};
|
|
14
|
+
const dispose=installRendererRecovery({app,window,write:(event,data)=>rows.push({event,...data}),onUnavailable:reason=>failures.push(reason),repaint:()=>rows.push({event:'repaint'}),now:()=>clock,scheduler,...options});
|
|
15
|
+
const tick=ms=>{const end=clock+ms;while(true){const ready=[...jobs].filter(([,j])=>j.at<=end).sort((a,b)=>a[1].at-b[1].at)[0];if(!ready)break;clock=ready[1].at;jobs.delete(ready[0]);ready[1].fn()}clock=end};
|
|
16
|
+
return {app,window,contents,rows,failures,dispose,tick,jobs,get reloads(){return reloaded},gone(reason='clean-exit'){pid=0;loading=false;contents.emit('render-process-gone',{}, {reason,exitCode:0,url:'private-token'})},loaded(){pid=18;loading=false;contents.emit('did-finish-load')},destroy(){destroyed=true;window.emit('closed')}}
|
|
17
|
+
}
|
|
18
|
+
test('unexpected clean exit reloads original contents and completes recovery',()=>{const f=fixture();f.gone();f.tick(300);assert.equal(f.reloads,1);f.loaded();assert.equal(f.rows.at(-1).event,'renderer-recovery-complete');assert.ok(f.rows.some(r=>r.event==='repaint'));assert.ok(!JSON.stringify(f.rows).includes('private-token'));f.dispose()})
|
|
19
|
+
test('duplicate exit before scheduled reload does not consume another attempt',()=>{const f=fixture();f.gone();f.gone();f.tick(300);assert.equal(f.reloads,1);f.loaded();f.dispose()})
|
|
20
|
+
test('normal quit and closed windows never resurrect a renderer',()=>{for(const stop of [f=>f.app.emit('before-quit'),f=>f.destroy()]){const f=fixture();f.gone();stop(f);f.tick(20000);assert.equal(f.reloads,0);f.dispose()}})
|
|
21
|
+
test('crash loop is bounded, including repeated clean exits',()=>{const f=fixture();for(let i=0;i<3;i++){f.gone();f.tick(300);f.loaded()}assert.equal(f.reloads,2);assert.equal(f.failures.length,1);f.tick(60000);f.gone();f.tick(300);assert.equal(f.reloads,3);f.dispose()})
|
|
22
|
+
test('manual reload wins over queued automatic recovery',()=>{const f=fixture();f.gone();f.contents.reload();f.loaded();f.tick(20000);assert.equal(f.reloads,1);assert.equal(f.failures.length,0);f.dispose()})
|
|
23
|
+
test('load timeout is reported once; late load may still recover',()=>{const f=fixture();f.gone();f.tick(20000);assert.equal(f.reloads,1);assert.deepEqual(f.failures,['load-timeout']);f.loaded();assert.equal(f.rows.at(-1).event,'renderer-recovery-complete');f.dispose()})
|
|
24
|
+
test('disposal cancels work and removes all owned listeners',()=>{const f=fixture();f.gone();f.dispose();f.tick(20000);assert.equal(f.reloads,0);assert.equal(f.jobs.size,0);assert.equal(f.contents.listenerCount('render-process-gone'),0);assert.equal(f.app.listenerCount('before-quit'),0)})
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Read-only process/status correlation. Stops with the selected DSH app."""
|
|
3
|
+
import datetime
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
import subprocess
|
|
8
|
+
import sys
|
|
9
|
+
import time
|
|
10
|
+
import urllib.parse
|
|
11
|
+
import urllib.request
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def counts(snapshot):
|
|
15
|
+
rows = snapshot.get('rows', [])
|
|
16
|
+
result = {'doing': 0, 'done': 0, 'error': 0, 'decision': 0}
|
|
17
|
+
for row in rows:
|
|
18
|
+
if row.get('ask') or row.get('approval'):
|
|
19
|
+
result['decision'] += 1
|
|
20
|
+
elif row.get('busy'):
|
|
21
|
+
result['doing'] += 1
|
|
22
|
+
elif (row.get('lastTurn') or {}).get('failed'):
|
|
23
|
+
result['error'] += 1
|
|
24
|
+
elif row.get('unread'):
|
|
25
|
+
result['done'] += 1
|
|
26
|
+
result['sidebarFresh'] = isinstance(snapshot.get('sidebarSyncedAt'), (int, float))
|
|
27
|
+
return result
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def status(runtime):
|
|
31
|
+
file = json.loads(runtime.read_text())
|
|
32
|
+
origin = urllib.parse.urlsplit(file['origin'])
|
|
33
|
+
if origin.scheme != 'http' or origin.hostname not in ('127.0.0.1', 'localhost', '::1'):
|
|
34
|
+
raise ValueError('not loopback')
|
|
35
|
+
request = urllib.request.Request(file['origin'] + '/dsh-notch/status', headers={'Authorization': 'Bearer ' + file['token']})
|
|
36
|
+
# Never send local credentials through a machine proxy or follow redirects.
|
|
37
|
+
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
|
38
|
+
def redirect_request(self, *args, **kwargs):
|
|
39
|
+
return None
|
|
40
|
+
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect())
|
|
41
|
+
with opener.open(request, timeout=1) as response:
|
|
42
|
+
snapshot = json.load(response)
|
|
43
|
+
if snapshot.get('ok') is not True:
|
|
44
|
+
raise ValueError('invalid snapshot')
|
|
45
|
+
return counts(snapshot)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def processes(app_pid, base):
|
|
49
|
+
result = []
|
|
50
|
+
output = subprocess.check_output(['ps', '-axo', 'pid=,ppid=,rss=,comm='], text=True, timeout=2)
|
|
51
|
+
for line in output.splitlines():
|
|
52
|
+
fields = line.strip().split(None, 3)
|
|
53
|
+
if len(fields) != 4:
|
|
54
|
+
continue
|
|
55
|
+
pid, parent, rss, command = fields
|
|
56
|
+
if command.startswith(base) or (int(parent) == app_pid and command.endswith('/node')):
|
|
57
|
+
role = ('renderer' if 'DSH Helper (Renderer)' in command else
|
|
58
|
+
'notch' if command.endswith('/dsh-notch') else
|
|
59
|
+
'app' if int(pid) == app_pid else
|
|
60
|
+
'host' if command.endswith('/node') else 'helper')
|
|
61
|
+
result.append({'pid': int(pid), 'role': role, 'rssKB': int(rss)})
|
|
62
|
+
return result
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def main():
|
|
66
|
+
app_pid, app_path, output = int(sys.argv[1]), Path(sys.argv[2]), Path(sys.argv[3])
|
|
67
|
+
runtime = Path.home() / '.dsh/dsh-notch/runtime.json'
|
|
68
|
+
output.parent.mkdir(parents=True, exist_ok=True)
|
|
69
|
+
previous = None
|
|
70
|
+
heartbeat = 0
|
|
71
|
+
while True:
|
|
72
|
+
began = time.monotonic()
|
|
73
|
+
try:
|
|
74
|
+
rows = processes(app_pid, str(app_path / 'Contents') + '/')
|
|
75
|
+
alive = any(row['pid'] == app_pid and row['role'] == 'app' for row in rows)
|
|
76
|
+
try:
|
|
77
|
+
board = status(runtime) if alive else {'unavailable': 'app-ended'}
|
|
78
|
+
except Exception as error:
|
|
79
|
+
board = {'unavailable': type(error).__name__}
|
|
80
|
+
signature = ([(r['pid'], r['role']) for r in rows], board)
|
|
81
|
+
if signature != previous or began - heartbeat >= 30:
|
|
82
|
+
event = {'at': datetime.datetime.now(datetime.timezone.utc).isoformat(),
|
|
83
|
+
'event': 'state-change' if signature != previous else 'heartbeat',
|
|
84
|
+
'appPid': app_pid, 'processes': rows, 'notch': board,
|
|
85
|
+
'sampleDurationMs': round((time.monotonic()-began)*1000),
|
|
86
|
+
'exitReason': 'unavailable-to-external-observer'}
|
|
87
|
+
if output.exists() and output.stat().st_size >= 1024 * 1024:
|
|
88
|
+
os.replace(output, str(output) + '.1')
|
|
89
|
+
with output.open('a') as file:
|
|
90
|
+
file.write(json.dumps(event) + '\n')
|
|
91
|
+
os.chmod(output, 0o600)
|
|
92
|
+
previous, heartbeat = signature, began
|
|
93
|
+
if not alive:
|
|
94
|
+
return
|
|
95
|
+
except (OSError, subprocess.SubprocessError):
|
|
96
|
+
pass
|
|
97
|
+
time.sleep(max(.1, 1 - (time.monotonic() - began)))
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
if __name__ == '__main__':
|
|
101
|
+
main()
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import importlib.util
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
import json
|
|
4
|
+
import unittest
|
|
5
|
+
spec=importlib.util.spec_from_file_location('watch',Path(__file__).with_name('completion-watch.py'))
|
|
6
|
+
watch=importlib.util.module_from_spec(spec);spec.loader.exec_module(watch)
|
|
7
|
+
class Tests(unittest.TestCase):
|
|
8
|
+
def test_counts_match_native_precedence_and_redact(self):
|
|
9
|
+
snapshot={'rows':[{'title':'secret','id':'secret','unread':True} for _ in range(5)]+[
|
|
10
|
+
{'busy':True,'unread':True}, {'lastTurn':{'failed':True},'unread':True},
|
|
11
|
+
{'ask':{'id':'secret'},'busy':True}], 'sidebarSyncedAt':123,'token':'secret'}
|
|
12
|
+
result=watch.counts(snapshot)
|
|
13
|
+
self.assertEqual(result,{'doing':1,'done':5,'error':1,'decision':1,'sidebarFresh':True})
|
|
14
|
+
self.assertNotIn('secret',json.dumps(result))
|
|
15
|
+
def test_expired_mirror_recorded_separately(self):
|
|
16
|
+
self.assertEqual(watch.counts({'rows':[]})['sidebarFresh'],False)
|
|
17
|
+
if __name__=='__main__':unittest.main()
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import {appendFileSync, mkdirSync, renameSync, statSync} from 'node:fs'
|
|
2
|
+
import {dirname} from 'node:path'
|
|
3
|
+
import {freemem,totalmem} from 'node:os'
|
|
4
|
+
|
|
5
|
+
// Deliberately excludes URLs, page text, tokens and arbitrary error messages.
|
|
6
|
+
export function createDiagnosticLog(path, {maxBytes=1024*1024}={}) {
|
|
7
|
+
return (event, data={}) => {
|
|
8
|
+
try {
|
|
9
|
+
mkdirSync(dirname(path),{recursive:true,mode:0o700})
|
|
10
|
+
try {if(statSync(path).size>=maxBytes)renameSync(path,path+'.1')} catch {}
|
|
11
|
+
appendFileSync(path,JSON.stringify({at:new Date().toISOString(),event,...data})+'\n',{mode:0o600})
|
|
12
|
+
} catch {} // Diagnostic failure must never break the shell.
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
export function installRendererDiagnostics({app,contents,window,powerMonitor,write,related=()=>({}),intervalMs=30000}) {
|
|
16
|
+
const disposers=[]
|
|
17
|
+
const on=(emitter,event,fn)=>{emitter.on(event,fn);disposers.push(()=>emitter.removeListener(event,fn))}
|
|
18
|
+
let lastRendererPid=null, loadedAt=null
|
|
19
|
+
const read=(object,method)=>{try{return object?.[method]?.()}catch{return undefined}}
|
|
20
|
+
const snapshot=()=>{
|
|
21
|
+
let processes=[]
|
|
22
|
+
try {processes=app.getAppMetrics().map(p=>({pid:p.pid,type:p.type,cpu:p.cpu?.percentCPUUsage,rssKB:p.memory?.workingSetSize,peakKB:p.memory?.peakWorkingSetSize}))}catch{}
|
|
23
|
+
let rendererPid=null
|
|
24
|
+
try{rendererPid=contents.getOSProcessId()}catch{}
|
|
25
|
+
if(rendererPid>0)lastRendererPid=rendererPid
|
|
26
|
+
return {appPid:process.pid,contentsId:contents.id,rendererPid,lastRendererPid,
|
|
27
|
+
pageAgeMs:loadedAt===null?null:Date.now()-loadedAt,
|
|
28
|
+
systemIdleSeconds:read(powerMonitor,'getSystemIdleTime'),
|
|
29
|
+
windowVisible:read(window,'isVisible'),windowMinimized:read(window,'isMinimized'),
|
|
30
|
+
windowFocused:read(window,'isFocused'),appHidden:read(app,'isHidden'),
|
|
31
|
+
loading:read(contents,'isLoading'),backgroundThrottling:read(contents,'getBackgroundThrottling'),
|
|
32
|
+
processes,freeMemoryBytes:freemem(),totalMemoryBytes:totalmem(),...related()}
|
|
33
|
+
}
|
|
34
|
+
const record=(event,data={})=>{try{write(event,{...snapshot(),...data})}catch{}}
|
|
35
|
+
on(contents,'render-process-gone',(_event,details)=>record('renderer-exited',{reason:details.reason,exitCode:details.exitCode}))
|
|
36
|
+
on(contents,'unresponsive',()=>record('renderer-unresponsive'))
|
|
37
|
+
on(contents,'responsive',()=>record('renderer-responsive'))
|
|
38
|
+
on(contents,'did-start-loading',()=>record('page-loading'))
|
|
39
|
+
on(contents,'did-finish-load',()=>{loadedAt=Date.now();record('page-loaded')})
|
|
40
|
+
on(contents,'did-fail-load',(_event,errorCode,_description,_url,isMainFrame)=>record('page-load-failed',{errorCode,isMainFrame}))
|
|
41
|
+
on(app,'child-process-gone',(_event,details)=>record('child-exited',{type:details.type,reason:details.reason,exitCode:details.exitCode}))
|
|
42
|
+
// No URLs, navigation arguments, input text or session content are recorded.
|
|
43
|
+
for(const event of ['render-view-deleted','render-view-ready','dom-ready','will-prevent-unload'])
|
|
44
|
+
on(contents,event,()=>record(event))
|
|
45
|
+
if(window)for(const event of ['show','hide','minimize','restore','focus','blur','resize','close','closed'])
|
|
46
|
+
on(window,event,()=>record('window-'+event))
|
|
47
|
+
if(powerMonitor)for(const event of ['suspend','resume','lock-screen','unlock-screen'])
|
|
48
|
+
on(powerMonitor,event,()=>record('system-'+event))
|
|
49
|
+
on(app,'before-quit',()=>record('app-before-quit'))
|
|
50
|
+
const timer=setInterval(()=>record('heartbeat'),intervalMs);timer.unref?.()
|
|
51
|
+
let disposed=false
|
|
52
|
+
function dispose(){if(disposed)return;disposed=true;clearInterval(timer);for(const fn of disposers)fn()}
|
|
53
|
+
on(contents,'destroyed',()=>{record('contents-destroyed');dispose()})
|
|
54
|
+
record('diagnostics-attached')
|
|
55
|
+
return dispose
|
|
56
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import {test} from 'node:test';import assert from 'node:assert/strict';import {EventEmitter} from 'node:events';
|
|
2
|
+
import {mkdtempSync,readFileSync,rmSync,existsSync} from 'node:fs';import {tmpdir} from 'node:os';
|
|
3
|
+
import {createDiagnosticLog,installRendererDiagnostics} from './renderer-diagnostics.mjs';
|
|
4
|
+
function fixture(){const app=new EventEmitter(),contents=new EventEmitter();app.getAppMetrics=()=>[{pid:7,type:'Tab',memory:{workingSetSize:123}}];contents.id=3;contents.getOSProcessId=()=>7;return {app,contents}}
|
|
5
|
+
test('renderer termination retains reason and exit code, strips secrets',()=>{const f=fixture(),rows=[];const dispose=installRendererDiagnostics({...f,write:(event,data)=>rows.push({event,...data})});f.contents.emit('render-process-gone',{}, {reason:'oom',exitCode:137,url:'secret',message:'secret'});const row=rows.at(-1);assert.equal(row.event,'renderer-exited');assert.equal(row.reason,'oom');assert.equal(row.exitCode,137);assert.equal(row.rendererPid,7);assert.ok(!JSON.stringify(rows).includes('secret'));dispose();assert.equal(f.contents.listenerCount('render-process-gone'),0)})
|
|
6
|
+
test('secondary process and loading events exclude URLs and messages',()=>{const f=fixture(),rows=[];const dispose=installRendererDiagnostics({...f,write:(e,d)=>rows.push({e,...d})});f.contents.emit('did-fail-load',{},-2,'secret','token-url',true);f.app.emit('child-process-gone',{}, {type:'GPU',reason:'crashed',exitCode:1,name:'secret'});assert.equal(rows.at(-1).type,'GPU');assert.ok(!JSON.stringify(rows).includes('secret'));assert.ok(!JSON.stringify(rows).includes('token-url'));dispose()})
|
|
7
|
+
test('diagnostic errors cannot break shell, destruction cleans up',()=>{const f=fixture();installRendererDiagnostics({...f,write:()=>{throw Error('disk full')}});assert.doesNotThrow(()=>f.contents.emit('render-process-gone',{}, {reason:'crashed',exitCode:1}));f.contents.emit('destroyed');assert.equal(f.app.listenerCount('child-process-gone'),0)})
|
|
8
|
+
test('rotates log at limit',()=>{const dir=mkdtempSync(tmpdir()+'/notch-diag-');try{const path=dir+'/events.jsonl',write=createDiagnosticLog(path,{maxBytes:1});write('one');write('two');assert.ok(existsSync(path+'.1'));assert.equal(JSON.parse(readFileSync(path,'utf8')).event,'two')}finally{rmSync(dir,{recursive:true,force:true})}})
|
|
9
|
+
test('idle renderer loss preserves departed PID and window state without private event arguments',()=>{
|
|
10
|
+
const f=fixture(),window=new EventEmitter(),powerMonitor=new EventEmitter(),rows=[];
|
|
11
|
+
window.isVisible=()=>true;window.isMinimized=()=>false;window.isFocused=()=>false;
|
|
12
|
+
powerMonitor.getSystemIdleTime=()=>7200;
|
|
13
|
+
const dispose=installRendererDiagnostics({...f,window,powerMonitor,write:(event,data)=>rows.push({event,...data})});
|
|
14
|
+
f.contents.emit('did-finish-load');
|
|
15
|
+
f.contents.getOSProcessId=()=>0;
|
|
16
|
+
f.contents.emit('render-process-gone',{}, {reason:'clean-exit',exitCode:0});
|
|
17
|
+
const row=rows.at(-1);
|
|
18
|
+
assert.equal(row.rendererPid,0);assert.equal(row.lastRendererPid,7);
|
|
19
|
+
assert.equal(row.systemIdleSeconds,7200);assert.equal(row.windowFocused,false);
|
|
20
|
+
assert.ok(row.pageAgeMs>=0);
|
|
21
|
+
powerMonitor.emit('suspend','private');window.emit('hide','private');
|
|
22
|
+
assert.equal(rows.at(-2).event,'system-suspend');assert.equal(rows.at(-1).event,'window-hide');
|
|
23
|
+
assert.ok(!JSON.stringify(rows).includes('private'));
|
|
24
|
+
dispose();assert.equal(window.listenerCount('hide'),0);assert.equal(powerMonitor.listenerCount('suspend'),0);
|
|
25
|
+
});
|
|
26
|
+
test('unsupported or destroyed window and power APIs do not break remaining evidence',()=>{
|
|
27
|
+
const f=fixture(),window=new EventEmitter(),powerMonitor=new EventEmitter(),rows=[];
|
|
28
|
+
window.isVisible=()=>{throw Error('destroyed')};powerMonitor.getSystemIdleTime=()=>{throw Error('unsupported')};
|
|
29
|
+
const dispose=installRendererDiagnostics({...f,window,powerMonitor,write:(event,data)=>rows.push({event,...data})});
|
|
30
|
+
f.contents.emit('render-process-gone',{}, {reason:'killed',exitCode:15});
|
|
31
|
+
assert.equal(rows.at(-1).reason,'killed');assert.equal(rows.at(-1).systemIdleSeconds,undefined);dispose();
|
|
32
|
+
});
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Open Bot Motion Contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import {homedir} from 'node:os';
|
|
2
|
+
import {fileURLToPath,pathToFileURL} from 'node:url';
|
|
3
|
+
const {launchPinnedChromium}=await import(pathToFileURL(homedir()+'/.codex/playwright-runtime/runtime.mjs'));
|
|
4
|
+
import {writeFile,mkdir} from 'node:fs/promises';
|
|
5
|
+
const out=fileURLToPath(new URL('../../macos/Sources/Resources/Idle',import.meta.url));await mkdir(out,{recursive:true});
|
|
6
|
+
const b=await launchPinnedChromium();const p=await b.newPage();await p.goto(new URL('./index.html',import.meta.url).href);
|
|
7
|
+
await p.evaluate(()=>window.capture=true);
|
|
8
|
+
for(const id of (process.argv.slice(2).length?process.argv.slice(2):['blink','scan','tilt','nod','stretch','hop','balance','sneeze','sleep','dance','satellite-out','satellite-in','cube-in'])){
|
|
9
|
+
const data=await p.evaluate(id=>{
|
|
10
|
+
const fps=30,duration=id==='dance'?20.783:id==='satellite-out'?.8:id==='satellite-in'?.82:id==='cube-in'?1.05:id==='sleep'?9:7,frames=[],proj=new OpenBotMotion.SvgProjector({viewportSize:280});
|
|
11
|
+
const path=document.createElementNS('http://www.w3.org/2000/svg','path');
|
|
12
|
+
for(let i=0;i<Math.ceil(duration*fps);i++){
|
|
13
|
+
const pose=poseFor(id,i/fps).bot,res=proj.projectRoundedCube(pose);path.setAttribute('d',res.bodyPath);const len=path.getTotalLength();
|
|
14
|
+
// SVG hull start vertices change with rotation. Sample a fixed angular grid
|
|
15
|
+
// around the bounds center, so index k always represents the same direction.
|
|
16
|
+
const outline=Array.from({length:768},(_,k)=>path.getPointAtLength(k*len/768));
|
|
17
|
+
const cx=(Math.min(...outline.map(p=>p.x))+Math.max(...outline.map(p=>p.x)))/2;
|
|
18
|
+
const cy=(Math.min(...outline.map(p=>p.y))+Math.max(...outline.map(p=>p.y)))/2;
|
|
19
|
+
const points=Array.from({length:192},(_,k)=>{
|
|
20
|
+
const angle=2*Math.PI*k/192,dx=Math.cos(angle),dy=Math.sin(angle);
|
|
21
|
+
let radius=Infinity;
|
|
22
|
+
for(let j=0;j<outline.length;j++) {
|
|
23
|
+
const a=outline[j],b=outline[(j+1)%outline.length];
|
|
24
|
+
const ex=b.x-a.x,ey=b.y-a.y,den=dx*ey-dy*ex;
|
|
25
|
+
if(Math.abs(den)<1e-10) continue;
|
|
26
|
+
const ax=a.x-cx,ay=a.y-cy;
|
|
27
|
+
const r=(ax*ey-ay*ex)/den,u=(ax*dy-ay*dx)/den;
|
|
28
|
+
if(r>=0 && u>=-1e-8 && u<=1+1e-8) radius=Math.min(radius,r);
|
|
29
|
+
}
|
|
30
|
+
if(!Number.isFinite(radius)) throw new Error('Missing contour intersection');
|
|
31
|
+
return [Math.round((cx+dx*radius)*1000)/1000,Math.round((cy+dy*radius)*1000)/1000];
|
|
32
|
+
});
|
|
33
|
+
const eyeSource=res.eyes.length===2?res.eyes:[{cx:-12,cy:0,w:1,h:1,rx:.5,angle:0,opacity:0},{cx:12,cy:0,w:1,h:1,rx:.5,angle:0,opacity:0}];
|
|
34
|
+
const eyes=eyeSource.map(e=>({x:e.cx,y:e.cy,w:e.w,h:e.h,r:e.rx,angle:e.angle,opacity:e.opacity??1}));
|
|
35
|
+
frames.push({points,eyes,body:pose.bodyColor,eye:pose.eyeColor});
|
|
36
|
+
}
|
|
37
|
+
return {fps,duration,frames};
|
|
38
|
+
},id);await writeFile(`${out}/${id}.json`,JSON.stringify(data));console.log(id,data.frames.length);
|
|
39
|
+
}
|
|
40
|
+
await b.close();
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
<!doctype html><meta charset="utf-8"><title>Notch · 九个基础待机动作</title>
|
|
2
|
+
<style>*{box-sizing:border-box}body{margin:0;background:#ededf0;color:#24242a;font-family:-apple-system,BlinkMacSystemFont,sans-serif}main{width:660px;padding:24px}h1{font-size:22px;margin:0 0 8px}p{font-size:13px;color:#7d7d84;margin:0 0 20px}#grid{display:grid;grid-template-columns:repeat(3,1fr);gap:12px}article{background:black;border-radius:20px;height:192px;display:flex;align-items:center;flex-direction:column}label{font-size:13px;color:#c6c6ce;margin-top:-8px}label span{color:#73737e;font-size:11px;margin-right:5px}.bot{width:166px;height:166px}footer{font-size:12px;color:#8b8b94;margin-top:16px}#dance{margin-top:30px;display:flex;gap:12px}#dance article{width:300px;height:220px}#dance label{margin-top:10px}</style>
|
|
3
|
+
<main><section id="nine"><h1>九个基础动作,各有一点小性格</h1><p>同步展示便于比较;正式待机每次只触发一个动作。</p><div id="grid"></div><footer>保留双眼的统一形状,通过视线、身体和节奏表达情绪。</footer></section><section id="dance"><article><div data-motion="dance-old"></div><label>之前:0.65 倍速</label></article><article><div data-motion="dance"></div><label>原库:原速 · 原弹跳 · 原色彩</label></article></section></main>
|
|
4
|
+
<script src="renderer.js"></script><script src="motions.js"></script>
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
const clamp=x=>Math.max(0,Math.min(1,x));
|
|
2
|
+
const ease=x=>{x=clamp(x);return x*x*x*(x*(x*6-15)+10)};
|
|
3
|
+
const pulse=(t,a,b,c,d)=>ease((t-a)/(b-a))*(1-ease((t-c)/(d-c)));
|
|
4
|
+
const neutral=()=>({visible:true,scale:1,scaleX:1,scaleY:1,x:0,y:0,yaw:0,pitch:0,roll:0,eyeShiftX:0,eyeShiftY:0,eyeShiftYL:0,eyeShiftYR:0,eyeGap:.24,eyeScaleXL:1,eyeScaleXR:1,eyeScaleYL:1,eyeScaleYR:1,eyeSlantL:0,eyeSlantR:0,squint:0,bodyColor:0xe5e5e7,eyeColor:0x171719});
|
|
5
|
+
window.poseFor=(id,time)=>{
|
|
6
|
+
if(id==='cube-in') {
|
|
7
|
+
const result=OpenBotMotion.getBot5State(2.22+Math.min(time,1.05));
|
|
8
|
+
result.bot.visible=true;result.bot.scale=Math.max(.015,result.bot.scale);
|
|
9
|
+
result.bot.bodyColor=0xe5e5e7;result.bot.eyeColor=0x171719;
|
|
10
|
+
// Rear-facing phases retain two invisible eye slots for native interpolation.
|
|
11
|
+
return result;
|
|
12
|
+
}
|
|
13
|
+
if(id==='satellite-out'||id==='satellite-in') {
|
|
14
|
+
const t=id==='satellite-out'?2+Math.min(time,.8):7.04+Math.min(time,.82);
|
|
15
|
+
const result=OpenBotMotion.getBot7State(t);
|
|
16
|
+
result.bot.bodyColor=0xe5e5e7;result.bot.eyeColor=0x171719;
|
|
17
|
+
if(id==='satellite-out') {
|
|
18
|
+
// #7 supplies anticipation; add a real backward revolution before collapse.
|
|
19
|
+
const turn=ease((time-.20)/.38);
|
|
20
|
+
result.bot.pitch=-Math.PI*2*turn;
|
|
21
|
+
result.bot.yaw=.26*Math.sin(Math.PI*turn);
|
|
22
|
+
result.bot.scale=1-.48*ease((time-.40)/.22);
|
|
23
|
+
result.bot.y+=.065*Math.sin(Math.PI*turn);
|
|
24
|
+
result.bot.showEyes=true;
|
|
25
|
+
}
|
|
26
|
+
// Keep topology stable even while #7 hides its eyes.
|
|
27
|
+
if(result.bot.showEyes===false){result.bot.showEyes=true;result.bot.eyeScaleY=.01;}
|
|
28
|
+
return result;
|
|
29
|
+
}
|
|
30
|
+
if(id==='dance')return OpenBotMotion.getBot3State(time);
|
|
31
|
+
if(id==='dance-old')return OpenBotMotion.getBot3State(time*.65);
|
|
32
|
+
const t=time%(id==='sleep'?9:7),p=neutral();
|
|
33
|
+
const close=v=>{p.eyeScaleYL=1-.94*v;p.eyeScaleYR=1-.94*v};
|
|
34
|
+
switch(id){
|
|
35
|
+
case 'blink': {
|
|
36
|
+
close(pulse(t,1.1,1.22,1.31,1.52)+pulse(t,1.8,1.94,2.01,2.2));
|
|
37
|
+
const wake=pulse(t,2.35,2.7,3.1,3.9);p.eyeScaleYL+=.16*wake;p.eyeScaleYR+=.16*wake;p.y=.018*wake;break;
|
|
38
|
+
}
|
|
39
|
+
case 'scan': {
|
|
40
|
+
const left=pulse(t,.8,1.25,1.8,2.3),right=pulse(t,2.5,3,3.6,4.2);
|
|
41
|
+
p.eyeShiftX=.18*(right-left);p.yaw=.22*(pulse(t,1,1.5,1.8,2.5)*-1+pulse(t,2.7,3.2,3.6,4.4));break;
|
|
42
|
+
}
|
|
43
|
+
case 'tilt': {
|
|
44
|
+
const first=pulse(t,1,1.7,2.4,3),second=pulse(t,3.2,3.8,4.15,4.9);
|
|
45
|
+
p.roll=-.27*first+.14*second;p.eyeShiftY=.035*first;p.pitch=-.08*first;close(.38*pulse(t,4.8,4.92,5.01,5.18));break;
|
|
46
|
+
}
|
|
47
|
+
case 'nod': {
|
|
48
|
+
const hello=pulse(t,.8,1.2,1.45,1.85)+.65*pulse(t,2.0,2.3,2.5,2.95);
|
|
49
|
+
p.pitch=.3*hello;p.y=-.045*hello;p.scaleY=1-.07*hello;p.scaleX=1+.025*hello;close(.35*hello);break;
|
|
50
|
+
}
|
|
51
|
+
case 'stretch': {
|
|
52
|
+
const prep=pulse(t,.8,1.2,1.4,1.8),up=pulse(t,1.5,2.3,3.3,4.35);
|
|
53
|
+
p.scaleY=1-.16*prep+.22*up;p.scaleX=1+.1*prep-.12*up;p.y=.025*up;close(.72*up);p.roll=.035*Math.sin(t*4)*up;break;
|
|
54
|
+
}
|
|
55
|
+
case 'hop': {
|
|
56
|
+
const prep=pulse(t,.8,1.15,1.3,1.55);p.scaleY-=.23*prep;p.scaleX+=.16*prep;
|
|
57
|
+
if(t>=1.5&&t<2.35){const u=(t-1.5)/.85;p.y=.32*Math.sin(Math.PI*u);p.scaleY+=.12*Math.sin(Math.PI*u);p.scaleX-=.07*Math.sin(Math.PI*u);}
|
|
58
|
+
const land=pulse(t,2.3,2.46,2.51,2.84);p.scaleY-=.20*land;p.scaleX+=.14*land;
|
|
59
|
+
if(t>=2.8&&t<3.25)p.y=.065*Math.sin(Math.PI*(t-2.8)/.45);
|
|
60
|
+
const settle=pulse(t,3.2,3.3,3.33,3.6);p.scaleY-=.05*settle;p.scaleX+=.03*settle;break;
|
|
61
|
+
}
|
|
62
|
+
case 'balance': {
|
|
63
|
+
const w=pulse(t,.7,1.3,3.8,4.7);p.roll=.24*Math.sin((t-.7)*3.5)*w;p.x=.05*Math.sin((t-.7)*3.5)*w;p.eyeShiftX=-.10*Math.sin((t-.7)*3.5)*w;break;
|
|
64
|
+
}
|
|
65
|
+
case 'sneeze': {
|
|
66
|
+
const inhale=pulse(t,.7,1.5,1.75,2.15);p.scaleY+=.13*inhale;p.scaleX-=.065*inhale;p.pitch=-.15*inhale;close(.6*inhale);
|
|
67
|
+
const sneeze=pulse(t,1.9,2.05,2.13,2.4);p.scaleY-=.30*sneeze;p.scaleX+=.18*sneeze;p.pitch+=.40*sneeze;p.y-=.035*sneeze;close(Math.max(.6*inhale,sneeze));
|
|
68
|
+
p.roll=.045*Math.sin((t-2.4)*12)*pulse(t,2.4,2.55,2.7,3.2);
|
|
69
|
+
const surprise=pulse(t,3.3,3.6,3.95,4.6);p.eyeScaleYL+=.15*surprise;p.eyeScaleYR+=.15*surprise;break;
|
|
70
|
+
}
|
|
71
|
+
case 'sleep': {
|
|
72
|
+
const drowse=pulse(t,.6,1.7,5.7,6.2);close(drowse);p.scaleY-=.10*drowse;p.scaleX+=.035*drowse;p.roll=.12*drowse;p.y=-.035*drowse;
|
|
73
|
+
const droop=pulse(t,2.4,3.1,5.4,6.0);p.pitch=.2*droop;p.y-=.025*droop;
|
|
74
|
+
const wake=pulse(t,5.95,6.2,6.32,6.9);p.y+=.05*wake;p.scaleY+=.06*wake;p.eyeScaleYL+=.22*wake;p.eyeScaleYR+=.22*wake;break;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return {botId:1,type:'bot1',label:id,bot:p,dots:[]};
|
|
78
|
+
};
|
|
79
|
+
const items=[['blink','01','眨眼回神'],['scan','02','左右巡视'],['tilt','03','歪头琢磨'],['nod','04','点头招呼'],['stretch','05','伸个懒腰'],['hop','06','果冻小跳'],['balance','07','摇摇平衡'],['sneeze','08','憋个喷嚏'],['sleep','09','打盹惊醒']];
|
|
80
|
+
for(const [id,n,label] of items){const card=document.createElement('article');card.innerHTML=`<div class="bot" data-motion="${id}"></div><label><span>${n}</span> ${label}</label>`;document.querySelector('#grid').append(card)}
|
|
81
|
+
const bots=[...document.querySelectorAll('[data-motion]')].map(el=>OpenBotMotion.mount(el,{bot:1,size:166,autoplay:false,loop:false}));
|
|
82
|
+
window.frame=t=>{window.previewTime=t;bots.forEach(b=>b.seek(t));};
|
|
83
|
+
let start=performance.now();function tick(t){if(!window.capture)frame((t-start)/1000);requestAnimationFrame(tick)}requestAnimationFrame(tick);
|