@deep-podder/dsh-remote-mobile 0.0.6 → 0.0.7
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/PROTOCOL.md +97 -9
- package/README.md +44 -9
- package/SECURITY.md +8 -0
- package/auth.js +16 -0
- package/bridge.js +336 -9
- package/docs/api-notes.md +12 -4
- package/docs/engineering-audit.md +252 -0
- package/docs/reference-chat-demo.md +41 -0
- package/docs/screenshots/chat-light.png +0 -0
- package/docs/screenshots/commands-dark.png +0 -0
- package/docs/screenshots/pairing-light.png +0 -0
- package/docs/screenshots/sessions-light.png +0 -0
- package/docs/verification.md +40 -4
- package/index.js +1 -1
- package/mobile/README.md +81 -35
- package/mobile/app.js +4268 -906
- package/mobile/index.html +28 -17
- package/mobile/lib/away.js +45 -0
- package/mobile/lib/constants.js +5 -0
- package/mobile/lib/errors.js +42 -0
- package/mobile/lib/format.js +94 -0
- package/mobile/lib/lock.js +21 -0
- package/mobile/manifest.webmanifest +24 -0
- package/mobile/mock-server.js +442 -17
- package/mobile/model/history.js +119 -0
- package/mobile/model/question.js +318 -0
- package/mobile/model/turns.js +57 -0
- package/mobile/styles/base.css +143 -0
- package/mobile/{styles.css → styles/components.css} +1170 -826
- package/mobile/styles/overrides.css +269 -0
- package/mobile/styles/tokens.css +169 -0
- package/mobile/sw.js +28 -4
- package/package.json +34 -20
- package/protocol.js +87 -0
- package/push-policy.js +58 -0
- package/server/frames/activity.js +110 -0
- package/server/frames/connection.js +21 -0
- package/server/frames/history.js +23 -0
- package/server/frames/interactions.js +77 -0
- package/server/frames/prompts.js +29 -0
- package/server/frames/queue.js +58 -0
- package/server/frames/sessions.js +201 -0
- package/server/frames/settings.js +38 -0
- package/server/frames/subagents.js +50 -0
- package/server.js +341 -423
package/server.js
CHANGED
|
@@ -8,12 +8,28 @@ import { homedir, networkInterfaces } from 'node:os'
|
|
|
8
8
|
import { appendFile, readFile, writeFile, rename } from 'node:fs/promises'
|
|
9
9
|
import { join } from 'node:path'
|
|
10
10
|
import { fileURLToPath } from 'node:url'
|
|
11
|
+
import { gzipSync } from 'node:zlib'
|
|
11
12
|
|
|
12
13
|
import { createAuth, equals } from './auth.js'
|
|
13
14
|
import { createPushService } from './push.js'
|
|
14
15
|
import { qrSvg } from './qr.js'
|
|
15
|
-
|
|
16
|
-
|
|
16
|
+
import { DEFAULT_PUSH_PREFS, normalizePushPrefs, pushAllowed } from './push-policy.js'
|
|
17
|
+
import {
|
|
18
|
+
HISTORY_DEFAULT_LIMIT,
|
|
19
|
+
HISTORY_MAX_LIMIT,
|
|
20
|
+
MAX_UPLOAD_BYTES,
|
|
21
|
+
} from './protocol.js'
|
|
22
|
+
import { connectionFrameMethods, connectionFrameMap } from './server/frames/connection.js'
|
|
23
|
+
import { sessionsFrameMethods, sessionsFrameMap } from './server/frames/sessions.js'
|
|
24
|
+
import { promptsFrameMethods, promptsFrameMap } from './server/frames/prompts.js'
|
|
25
|
+
import { queueFrameMethods, queueFrameMap } from './server/frames/queue.js'
|
|
26
|
+
import { activityFrameMethods, activityFrameMap } from './server/frames/activity.js'
|
|
27
|
+
import { interactionsFrameMethods, interactionsFrameMap } from './server/frames/interactions.js'
|
|
28
|
+
import { settingsFrameMethods, settingsFrameMap } from './server/frames/settings.js'
|
|
29
|
+
import { historyFrameMethods, historyFrameMap } from './server/frames/history.js'
|
|
30
|
+
import { subagentsFrameMethods, subagentsFrameMap } from './server/frames/subagents.js'
|
|
31
|
+
|
|
32
|
+
const VERSION = '0.0.7'
|
|
17
33
|
const WS_GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
|
|
18
34
|
const MAX_MESSAGE_BYTES = 1024 * 1024
|
|
19
35
|
const MAX_BODY_BYTES = 64 * 1024
|
|
@@ -36,7 +52,19 @@ const STATIC_FILES = new Map([
|
|
|
36
52
|
['/', { file: 'index.html', type: 'text/html; charset=utf-8' }],
|
|
37
53
|
['/index.html', { file: 'index.html', type: 'text/html; charset=utf-8' }],
|
|
38
54
|
['/app.js', { file: 'app.js', type: 'text/javascript; charset=utf-8' }],
|
|
39
|
-
['/
|
|
55
|
+
['/protocol.js', { file: '../protocol.js', type: 'text/javascript; charset=utf-8' }],
|
|
56
|
+
['/lib/constants.js', { file: 'lib/constants.js', type: 'text/javascript; charset=utf-8' }],
|
|
57
|
+
['/lib/errors.js', { file: 'lib/errors.js', type: 'text/javascript; charset=utf-8' }],
|
|
58
|
+
['/lib/away.js', { file: 'lib/away.js', type: 'text/javascript; charset=utf-8' }],
|
|
59
|
+
['/lib/lock.js', { file: 'lib/lock.js', type: 'text/javascript; charset=utf-8' }],
|
|
60
|
+
['/lib/format.js', { file: 'lib/format.js', type: 'text/javascript; charset=utf-8' }],
|
|
61
|
+
['/model/question.js', { file: 'model/question.js', type: 'text/javascript; charset=utf-8' }],
|
|
62
|
+
['/model/history.js', { file: 'model/history.js', type: 'text/javascript; charset=utf-8' }],
|
|
63
|
+
['/model/turns.js', { file: 'model/turns.js', type: 'text/javascript; charset=utf-8' }],
|
|
64
|
+
['/styles/tokens.css', { file: 'styles/tokens.css', type: 'text/css; charset=utf-8' }],
|
|
65
|
+
['/styles/base.css', { file: 'styles/base.css', type: 'text/css; charset=utf-8' }],
|
|
66
|
+
['/styles/components.css', { file: 'styles/components.css', type: 'text/css; charset=utf-8' }],
|
|
67
|
+
['/styles/overrides.css', { file: 'styles/overrides.css', type: 'text/css; charset=utf-8' }],
|
|
40
68
|
// Installable web app. The service worker must be served from the site root so
|
|
41
69
|
// its scope covers the whole app.
|
|
42
70
|
['/manifest.webmanifest', { file: 'manifest.webmanifest', type: 'application/manifest+json; charset=utf-8' }],
|
|
@@ -48,6 +76,42 @@ const STATIC_FILES = new Map([
|
|
|
48
76
|
['/favicon.svg', { file: 'favicon.svg', type: 'image/svg+xml' }],
|
|
49
77
|
])
|
|
50
78
|
|
|
79
|
+
/**
|
|
80
|
+
* The shell revision is derived from the served bytes, not from a manual
|
|
81
|
+
* counter. Placeholders (?v=<n>, dsh-remote-v<n>) are normalized before
|
|
82
|
+
* hashing so rewriting them cannot feed back into the hash.
|
|
83
|
+
*/
|
|
84
|
+
function shellRevision(entries) {
|
|
85
|
+
const hash = createHash('sha256')
|
|
86
|
+
for (const route of [...entries.keys()].sort()) {
|
|
87
|
+
const entry = entries.get(route)
|
|
88
|
+
const normalized = isCompressibleType(entry.type)
|
|
89
|
+
? entry.body
|
|
90
|
+
.toString('utf8')
|
|
91
|
+
.replace(/\?v=\d+/g, '?v=@')
|
|
92
|
+
.replace(/dsh-remote-v\d+/g, 'dsh-remote-v@')
|
|
93
|
+
: entry.body
|
|
94
|
+
hash.update(route).update('\0').update(normalized).update('\0')
|
|
95
|
+
}
|
|
96
|
+
return hash.digest('hex').slice(0, 10)
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function rewriteShell(body, revision) {
|
|
100
|
+
return body
|
|
101
|
+
.toString('utf8')
|
|
102
|
+
.replace(/\?v=\d+/g, `?v=${revision}`)
|
|
103
|
+
.replace(/dsh-remote-v\d+/g, `dsh-remote-v${revision}`)
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Text-ish shell assets are precompressed; images are already compressed. */
|
|
107
|
+
function isCompressibleType(type) {
|
|
108
|
+
return /^text\//.test(type) ||
|
|
109
|
+
type.startsWith('application/json') ||
|
|
110
|
+
type.startsWith('application/manifest+json') ||
|
|
111
|
+
type.startsWith('application/javascript') ||
|
|
112
|
+
type.startsWith('image/svg+xml')
|
|
113
|
+
}
|
|
114
|
+
|
|
51
115
|
function normalizeIp(value) {
|
|
52
116
|
if (typeof value !== 'string') return 'unknown'
|
|
53
117
|
return value.startsWith('::ffff:') ? value.slice(7) : value
|
|
@@ -433,6 +497,20 @@ function resolveEnabled(statePath) {
|
|
|
433
497
|
* The plugin's mobile server. `start()` is idempotent; `stop()` releases every
|
|
434
498
|
* socket, timer and listener.
|
|
435
499
|
*/
|
|
500
|
+
|
|
501
|
+
|
|
502
|
+
const FRAME_HANDLERS = Object.freeze({
|
|
503
|
+
...connectionFrameMap,
|
|
504
|
+
...sessionsFrameMap,
|
|
505
|
+
...promptsFrameMap,
|
|
506
|
+
...queueFrameMap,
|
|
507
|
+
...activityFrameMap,
|
|
508
|
+
...interactionsFrameMap,
|
|
509
|
+
...settingsFrameMap,
|
|
510
|
+
...historyFrameMap,
|
|
511
|
+
...subagentsFrameMap,
|
|
512
|
+
})
|
|
513
|
+
|
|
436
514
|
export class RemoteMobileServer {
|
|
437
515
|
/**
|
|
438
516
|
* @param {object} ctx Cordis host context (accepted for parity with the other
|
|
@@ -475,6 +553,7 @@ export class RemoteMobileServer {
|
|
|
475
553
|
this.sessionRefreshTimer = null
|
|
476
554
|
// Web Push service (VAPID key + subscriptions), created in start().
|
|
477
555
|
this.push = null
|
|
556
|
+
this.pushPrefs = new Map()
|
|
478
557
|
// deviceId -> whether that device currently has a foreground/visible phone
|
|
479
558
|
// page. Absent means "unknown", which is treated as not visible.
|
|
480
559
|
this.deviceVisibility = new Map()
|
|
@@ -485,6 +564,12 @@ export class RemoteMobileServer {
|
|
|
485
564
|
// test path bypasses the automatic dispatch limiter, so it needs its own cap.
|
|
486
565
|
this.pushTestWindows = new Map()
|
|
487
566
|
this.replyPushAt = new Map()
|
|
567
|
+
// Listener lifecycle: a desktop restart can briefly overlap the previous
|
|
568
|
+
// process, so an EADDRINUSE is retried with backoff instead of leaving the
|
|
569
|
+
// plugin active with no phone server until the next full restart.
|
|
570
|
+
this.listenRetryTimer = null
|
|
571
|
+
this.listenAttempt = 0
|
|
572
|
+
this.listenError = null
|
|
488
573
|
// Per-session assistant text, so a "reply ready" push can carry a short
|
|
489
574
|
// excerpt instead of only the session title. Bounded to a few recent turns.
|
|
490
575
|
this.replyBuffer = new Map()
|
|
@@ -506,8 +591,18 @@ export class RemoteMobileServer {
|
|
|
506
591
|
if (this.statePath !== null) {
|
|
507
592
|
try {
|
|
508
593
|
persisted = JSON.parse(await readFile(this.statePath, 'utf8'))
|
|
509
|
-
} catch {
|
|
510
|
-
|
|
594
|
+
} catch (error) {
|
|
595
|
+
// A half-written or raced state file must not silently drop every
|
|
596
|
+
// paired device: fall back to the last good `.bak` when it parses.
|
|
597
|
+
this.log.warn?.(
|
|
598
|
+
`remote-mobile: pairing state unreadable (${error instanceof Error ? error.message : String(error)}); trying backup`,
|
|
599
|
+
)
|
|
600
|
+
try {
|
|
601
|
+
persisted = JSON.parse(await readFile(`${this.statePath}.bak`, 'utf8'))
|
|
602
|
+
this.log.warn?.('remote-mobile: restored pairing state from backup')
|
|
603
|
+
} catch {
|
|
604
|
+
persisted = null
|
|
605
|
+
}
|
|
511
606
|
}
|
|
512
607
|
}
|
|
513
608
|
const secret = persisted !== null && typeof persisted.secret === 'string' && persisted.secret.length >= 32
|
|
@@ -515,6 +610,14 @@ export class RemoteMobileServer {
|
|
|
515
610
|
: randomBytes(32).toString('base64url')
|
|
516
611
|
this.auth = createAuth({ secret, log: this.log })
|
|
517
612
|
if (persisted !== null) this.auth.importState(persisted)
|
|
613
|
+
this.pushPrefs = new Map()
|
|
614
|
+
if (persisted !== null && persisted.pushPrefs && typeof persisted.pushPrefs === 'object') {
|
|
615
|
+
for (const [deviceId, raw] of Object.entries(persisted.pushPrefs)) {
|
|
616
|
+
if (typeof deviceId === 'string' && deviceId.length > 0) {
|
|
617
|
+
this.pushPrefs.set(deviceId, normalizePushPrefs(raw))
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
}
|
|
518
621
|
// Real Web Push: VAPID keys are generated once and restored from the same
|
|
519
622
|
// state file (the `push` field, absent in state files written by older
|
|
520
623
|
// versions). Subscriptions belong to paired devices and survive restarts.
|
|
@@ -550,19 +653,53 @@ export class RemoteMobileServer {
|
|
|
550
653
|
this.log.warn?.(`remote-mobile: cannot read mobile/${spec.file}: ${error instanceof Error ? error.message : String(error)}`)
|
|
551
654
|
}
|
|
552
655
|
}
|
|
656
|
+
// Derive one cache key for this exact shell. Source files carry ?v=1 as a
|
|
657
|
+
// placeholder; the running server serves ?v=<hash> so minor edits never
|
|
658
|
+
// require a manual version bump and phones cannot mix old modules.
|
|
659
|
+
this.assetRevision = shellRevision(this.staticCache)
|
|
660
|
+
for (const entry of this.staticCache.values()) {
|
|
661
|
+
if (!isCompressibleType(entry.type)) continue
|
|
662
|
+
entry.body = Buffer.from(rewriteShell(entry.body, this.assetRevision), 'utf8')
|
|
663
|
+
entry.gzip = gzipSync(entry.body, { level: 9 })
|
|
664
|
+
}
|
|
553
665
|
|
|
554
666
|
this.wireBridge()
|
|
555
667
|
if (this.enabled) {
|
|
556
|
-
|
|
557
|
-
await this.listen()
|
|
558
|
-
} catch (error) {
|
|
559
|
-
this.log.error?.(`remote-mobile: server failed to start: ${error instanceof Error ? error.message : String(error)}`)
|
|
560
|
-
}
|
|
668
|
+
await this.startListening()
|
|
561
669
|
} else {
|
|
562
670
|
this.log.info?.('remote-mobile: disabled by the desktop switch')
|
|
563
671
|
}
|
|
564
672
|
}
|
|
565
673
|
|
|
674
|
+
/**
|
|
675
|
+
* Listen, retrying with backoff when the port is momentarily held by a
|
|
676
|
+
* previous desktop process. A failed first bind used to leave the plugin
|
|
677
|
+
* active but unreachable until the user restarted Harness again.
|
|
678
|
+
*/
|
|
679
|
+
async startListening() {
|
|
680
|
+
if (!this.started || !this.enabled || this.listening) return
|
|
681
|
+
try {
|
|
682
|
+
await this.listen()
|
|
683
|
+
this.listenError = null
|
|
684
|
+
this.listenAttempt = 0
|
|
685
|
+
} catch (error) {
|
|
686
|
+
this.listenError = error instanceof Error ? error.message : String(error)
|
|
687
|
+
this.log.error?.(
|
|
688
|
+
`remote-mobile: server failed to start (attempt ${this.listenAttempt + 1}): ${this.listenError}`,
|
|
689
|
+
)
|
|
690
|
+
if (!this.started) return
|
|
691
|
+
const delays = [1000, 2000, 4000, 8000, 15000, 30000]
|
|
692
|
+
const delay = delays[Math.min(this.listenAttempt, delays.length - 1)]
|
|
693
|
+
this.listenAttempt += 1
|
|
694
|
+
clearTimeout(this.listenRetryTimer)
|
|
695
|
+
this.listenRetryTimer = setTimeout(() => {
|
|
696
|
+
this.listenRetryTimer = null
|
|
697
|
+
void this.startListening()
|
|
698
|
+
}, delay)
|
|
699
|
+
this.listenRetryTimer.unref?.()
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
|
|
566
703
|
async listen() {
|
|
567
704
|
if (this.listening) return
|
|
568
705
|
const server = createServer((req, res) => {
|
|
@@ -631,6 +768,7 @@ export class RemoteMobileServer {
|
|
|
631
768
|
}
|
|
632
769
|
this.server = server
|
|
633
770
|
this.listening = true
|
|
771
|
+
this.listenError = null
|
|
634
772
|
const address = server.address()
|
|
635
773
|
if (address !== null && typeof address === 'object') this.port = address.port
|
|
636
774
|
this.startHeartbeat()
|
|
@@ -742,6 +880,7 @@ export class RemoteMobileServer {
|
|
|
742
880
|
onQuestionResolved: (payload) => this.broadcastQuestionResolved(payload),
|
|
743
881
|
onQueue: (payload) => this.broadcastQueue(payload),
|
|
744
882
|
onStatus: (payload) => this.broadcastStatus(payload),
|
|
883
|
+
onSubagentStatus: (payload) => this.broadcastSubagentStatus(payload),
|
|
745
884
|
})
|
|
746
885
|
} catch (error) {
|
|
747
886
|
this.log.warn?.(`remote-mobile: cannot subscribe to bridge: ${error instanceof Error ? error.message : String(error)}`)
|
|
@@ -751,6 +890,10 @@ export class RemoteMobileServer {
|
|
|
751
890
|
async stop() {
|
|
752
891
|
if (!this.started) return
|
|
753
892
|
this.started = false
|
|
893
|
+
clearTimeout(this.listenRetryTimer)
|
|
894
|
+
this.listenRetryTimer = null
|
|
895
|
+
this.listenAttempt = 0
|
|
896
|
+
this.listenError = null
|
|
754
897
|
if (this.unsubscribeBridge !== null) {
|
|
755
898
|
try {
|
|
756
899
|
this.unsubscribeBridge()
|
|
@@ -791,6 +934,7 @@ export class RemoteMobileServer {
|
|
|
791
934
|
const tmp = `${this.statePath}.tmp`
|
|
792
935
|
try {
|
|
793
936
|
const state = this.auth.exportState()
|
|
937
|
+
state.pushPrefs = Object.fromEntries(this.pushPrefs)
|
|
794
938
|
if (this.push !== null) {
|
|
795
939
|
// Drop subscriptions of devices that were revoked (or evicted by the
|
|
796
940
|
// pairing device cap), then persist the VAPID key and subscriptions
|
|
@@ -799,8 +943,21 @@ export class RemoteMobileServer {
|
|
|
799
943
|
state.push = this.push.exportState()
|
|
800
944
|
}
|
|
801
945
|
const payload = JSON.stringify(state, null, 2)
|
|
946
|
+
// Keep one generation of the previous good state: a plugin reload can
|
|
947
|
+
// race the old and new server, and losing the device list would force
|
|
948
|
+
// every phone to pair again.
|
|
949
|
+
if (this.statePath !== null) {
|
|
950
|
+
try {
|
|
951
|
+
const existing = await readFile(this.statePath, 'utf8')
|
|
952
|
+
JSON.parse(existing)
|
|
953
|
+
await writeFile(`${this.statePath}.bak`, existing, { mode: 0o600 })
|
|
954
|
+
} catch {
|
|
955
|
+
// no previous state, or it was already corrupt
|
|
956
|
+
}
|
|
957
|
+
}
|
|
802
958
|
await writeFile(tmp, payload, { mode: 0o600 })
|
|
803
959
|
await rename(tmp, this.statePath)
|
|
960
|
+
|
|
804
961
|
} catch (error) {
|
|
805
962
|
this.log.warn?.(`remote-mobile: cannot persist pairing state: ${error instanceof Error ? error.message : String(error)}`)
|
|
806
963
|
}
|
|
@@ -989,8 +1146,11 @@ export class RemoteMobileServer {
|
|
|
989
1146
|
return
|
|
990
1147
|
}
|
|
991
1148
|
|
|
992
|
-
if (
|
|
993
|
-
|
|
1149
|
+
if (
|
|
1150
|
+
path.startsWith('/api/push/') &&
|
|
1151
|
+
(method === 'POST' || (path === '/api/push/prefs' && method === 'GET'))
|
|
1152
|
+
) {
|
|
1153
|
+
await this.handlePushApi(req, res, path, method)
|
|
994
1154
|
return
|
|
995
1155
|
}
|
|
996
1156
|
|
|
@@ -1012,6 +1172,47 @@ export class RemoteMobileServer {
|
|
|
1012
1172
|
return
|
|
1013
1173
|
}
|
|
1014
1174
|
|
|
1175
|
+
if (path === '/api/devices' && method === 'GET') {
|
|
1176
|
+
const device = this.currentDevice(req)
|
|
1177
|
+
if (device === null) {
|
|
1178
|
+
jsonResponse(res, 401, { error: 'unauthenticated' })
|
|
1179
|
+
return
|
|
1180
|
+
}
|
|
1181
|
+
const devices = this.auth.devices().map((entry) => ({
|
|
1182
|
+
id: entry.id,
|
|
1183
|
+
name: entry.name,
|
|
1184
|
+
createdAt: entry.createdAt,
|
|
1185
|
+
lastSeenAt: entry.lastSeenAt,
|
|
1186
|
+
canApprove: entry.canApprove !== false,
|
|
1187
|
+
current: entry.id === device.id,
|
|
1188
|
+
}))
|
|
1189
|
+
jsonResponse(res, 200, { devices })
|
|
1190
|
+
return
|
|
1191
|
+
}
|
|
1192
|
+
|
|
1193
|
+
if (path === '/api/devices/name' && method === 'POST') {
|
|
1194
|
+
const device = this.currentDevice(req)
|
|
1195
|
+
if (device === null) {
|
|
1196
|
+
jsonResponse(res, 401, { error: 'unauthenticated' })
|
|
1197
|
+
return
|
|
1198
|
+
}
|
|
1199
|
+
let body
|
|
1200
|
+
try {
|
|
1201
|
+
body = await readJsonBody(req, 4 * 1024)
|
|
1202
|
+
} catch {
|
|
1203
|
+
jsonResponse(res, 400, { error: 'bad-request' })
|
|
1204
|
+
return
|
|
1205
|
+
}
|
|
1206
|
+
const renamed = this.auth.renameDevice(device.id, body?.name)
|
|
1207
|
+
if (renamed === null) {
|
|
1208
|
+
jsonResponse(res, 400, { error: 'bad-request' })
|
|
1209
|
+
return
|
|
1210
|
+
}
|
|
1211
|
+
this.scheduleSave()
|
|
1212
|
+
jsonResponse(res, 200, { device: renamed })
|
|
1213
|
+
return
|
|
1214
|
+
}
|
|
1215
|
+
|
|
1015
1216
|
if (path === '/api/preview' && method === 'GET') {
|
|
1016
1217
|
const device = this.currentDevice(req)
|
|
1017
1218
|
if (device === null) {
|
|
@@ -1058,7 +1259,7 @@ export class RemoteMobileServer {
|
|
|
1058
1259
|
}
|
|
1059
1260
|
let body
|
|
1060
1261
|
try {
|
|
1061
|
-
body = await readBodyBuffer(req,
|
|
1262
|
+
body = await readBodyBuffer(req, MAX_UPLOAD_BYTES)
|
|
1062
1263
|
} catch (error) {
|
|
1063
1264
|
jsonResponse(res, error instanceof Error && error.message === 'body-too-large' ? 413 : 400, { error: 'bad-upload' })
|
|
1064
1265
|
return
|
|
@@ -1149,9 +1350,16 @@ export class RemoteMobileServer {
|
|
|
1149
1350
|
"frame-ancestors 'none'",
|
|
1150
1351
|
].join('; ')
|
|
1151
1352
|
}
|
|
1353
|
+
const acceptsGzip = /\bgzip\b/.test(String(req.headers['accept-encoding'] || ''))
|
|
1354
|
+
const gzip = stat.gzip !== undefined && acceptsGzip ? stat.gzip : null
|
|
1355
|
+
if (stat.gzip !== undefined) headers.vary = 'accept-encoding'
|
|
1356
|
+
if (gzip !== null) {
|
|
1357
|
+
headers['content-encoding'] = 'gzip'
|
|
1358
|
+
headers['content-length'] = String(gzip.length)
|
|
1359
|
+
}
|
|
1152
1360
|
res.writeHead(200, headers)
|
|
1153
1361
|
if (req.method === 'HEAD') res.end()
|
|
1154
|
-
else res.end(stat.body)
|
|
1362
|
+
else res.end(gzip ?? stat.body)
|
|
1155
1363
|
}
|
|
1156
1364
|
|
|
1157
1365
|
async handlePair(req, res) {
|
|
@@ -1195,7 +1403,7 @@ export class RemoteMobileServer {
|
|
|
1195
1403
|
* because it is intentionally public. A device can only remove its own
|
|
1196
1404
|
* endpoint, never another paired device's.
|
|
1197
1405
|
*/
|
|
1198
|
-
async handlePushApi(req, res, path) {
|
|
1406
|
+
async handlePushApi(req, res, path, method) {
|
|
1199
1407
|
if (this.push === null) {
|
|
1200
1408
|
jsonResponse(res, 503, { error: 'starting' })
|
|
1201
1409
|
return
|
|
@@ -1205,6 +1413,18 @@ export class RemoteMobileServer {
|
|
|
1205
1413
|
jsonResponse(res, 401, { error: 'unauthenticated' })
|
|
1206
1414
|
return
|
|
1207
1415
|
}
|
|
1416
|
+
if (path === '/api/push/prefs' && method === 'GET') {
|
|
1417
|
+
const device = this.currentDevice(req)
|
|
1418
|
+
if (device === null) {
|
|
1419
|
+
jsonResponse(res, 401, { error: 'unauthenticated' })
|
|
1420
|
+
return
|
|
1421
|
+
}
|
|
1422
|
+
jsonResponse(res, 200, {
|
|
1423
|
+
prefs: this.pushPrefs.get(device.id) ?? DEFAULT_PUSH_PREFS,
|
|
1424
|
+
})
|
|
1425
|
+
return
|
|
1426
|
+
}
|
|
1427
|
+
|
|
1208
1428
|
let body
|
|
1209
1429
|
try {
|
|
1210
1430
|
body = await readJsonBody(req, 8 * 1024)
|
|
@@ -1212,6 +1432,23 @@ export class RemoteMobileServer {
|
|
|
1212
1432
|
jsonResponse(res, 400, { error: 'bad-request' })
|
|
1213
1433
|
return
|
|
1214
1434
|
}
|
|
1435
|
+
if (path === '/api/push/prefs' && method === 'POST') {
|
|
1436
|
+
const device = this.currentDevice(req)
|
|
1437
|
+
if (device === null) {
|
|
1438
|
+
jsonResponse(res, 401, { error: 'unauthenticated' })
|
|
1439
|
+
return
|
|
1440
|
+
}
|
|
1441
|
+
if (body === null || typeof body !== 'object' || Array.isArray(body)) {
|
|
1442
|
+
jsonResponse(res, 400, { error: 'bad-request' })
|
|
1443
|
+
return
|
|
1444
|
+
}
|
|
1445
|
+
const prefs = normalizePushPrefs(body)
|
|
1446
|
+
this.pushPrefs.set(device.id, prefs)
|
|
1447
|
+
this.scheduleSave()
|
|
1448
|
+
jsonResponse(res, 200, { prefs })
|
|
1449
|
+
return
|
|
1450
|
+
}
|
|
1451
|
+
|
|
1215
1452
|
if (path === '/api/push/subscribe') {
|
|
1216
1453
|
const endpoint = typeof body.subscription?.endpoint === 'string' ? body.subscription.endpoint : ''
|
|
1217
1454
|
const owned = this.push.subscriptions(device.id)
|
|
@@ -1332,6 +1569,8 @@ export class RemoteMobileServer {
|
|
|
1332
1569
|
const devices = auth.devices()
|
|
1333
1570
|
return {
|
|
1334
1571
|
enabled: false,
|
|
1572
|
+
listening: false,
|
|
1573
|
+
listenError: this.listenError,
|
|
1335
1574
|
version: VERSION,
|
|
1336
1575
|
port: this.port,
|
|
1337
1576
|
bindHost: this.bindHost,
|
|
@@ -1361,6 +1600,8 @@ export class RemoteMobileServer {
|
|
|
1361
1600
|
const connectedNames = [...new Set([...this.peers].map((peer) => peer.device.name))]
|
|
1362
1601
|
return {
|
|
1363
1602
|
enabled: true,
|
|
1603
|
+
listening: this.listening,
|
|
1604
|
+
listenError: this.listenError,
|
|
1364
1605
|
version: VERSION,
|
|
1365
1606
|
port: this.port,
|
|
1366
1607
|
bindHost: this.bindHost,
|
|
@@ -1660,7 +1901,16 @@ export class RemoteMobileServer {
|
|
|
1660
1901
|
peer.on('message', (frame) => {
|
|
1661
1902
|
this.handleFrame(peer, frame).catch((error) => {
|
|
1662
1903
|
const code = typeof error?.code === 'string' && error.code.length > 0 ? error.code : 'internal'
|
|
1663
|
-
peer.sendObject({
|
|
1904
|
+
peer.sendObject({
|
|
1905
|
+
type: 'error',
|
|
1906
|
+
code,
|
|
1907
|
+
message: String(error instanceof Error ? error.message : error),
|
|
1908
|
+
// Echo the request id when the failed frame carried one so a phone can
|
|
1909
|
+
// mark the exact optimistic message instead of guessing.
|
|
1910
|
+
...(typeof frame?.requestId === 'string' && frame.requestId.length > 0
|
|
1911
|
+
? { requestId: frame.requestId }
|
|
1912
|
+
: {}),
|
|
1913
|
+
})
|
|
1664
1914
|
})
|
|
1665
1915
|
})
|
|
1666
1916
|
this.sendWelcome(peer).catch((error) => {
|
|
@@ -1729,6 +1979,9 @@ export class RemoteMobileServer {
|
|
|
1729
1979
|
questions: question.questions,
|
|
1730
1980
|
})
|
|
1731
1981
|
}
|
|
1982
|
+
// Authoritative snapshot for reconciliation: anything the phone still has
|
|
1983
|
+
// locally but is absent here was resolved while its socket was down.
|
|
1984
|
+
peer.sendObject({ type: 'pending', ...this.pendingSnapshot() })
|
|
1732
1985
|
}
|
|
1733
1986
|
|
|
1734
1987
|
async callBridge(method, ...args) {
|
|
@@ -1775,416 +2028,42 @@ export class RemoteMobileServer {
|
|
|
1775
2028
|
|
|
1776
2029
|
async handleFrame(peer, frame) {
|
|
1777
2030
|
const type = typeof frame.type === 'string' ? frame.type : ''
|
|
1778
|
-
|
|
1779
|
-
|
|
1780
|
-
|
|
1781
|
-
|
|
1782
|
-
case 'client.visibility': {
|
|
1783
|
-
// The SPA reports whether its page is visible (foreground). While any
|
|
1784
|
-
// phone page is visible no Web Push is sent; unknown/backgrounded is the
|
|
1785
|
-
// default so a phone that never reports still receives notifications.
|
|
1786
|
-
const visible = frame.visible === true
|
|
1787
|
-
this.deviceVisibility.set(peer.device.id, visible)
|
|
1788
|
-
peer.sendObject({ type: 'visibility', visible })
|
|
1789
|
-
return
|
|
1790
|
-
}
|
|
1791
|
-
case 'sessions.list': {
|
|
1792
|
-
const sessions = await this.callBridge('listSessions')
|
|
1793
|
-
peer.sendObject({
|
|
1794
|
-
type: 'sessions',
|
|
1795
|
-
sessions: Array.isArray(sessions) ? sessions : [],
|
|
1796
|
-
workspaces: await this.fetchWorkspaces(),
|
|
1797
|
-
activeSessionId: null,
|
|
1798
|
-
})
|
|
1799
|
-
return
|
|
1800
|
-
}
|
|
1801
|
-
case 'sessions.open': {
|
|
1802
|
-
if (typeof frame.sessionId !== 'string') throw new Error('sessionId required')
|
|
1803
|
-
const opened = await this.callBridge('openSession', frame.sessionId)
|
|
1804
|
-
peer.sendObject({
|
|
1805
|
-
type: 'session.opened',
|
|
1806
|
-
session: opened?.session ?? null,
|
|
1807
|
-
history: opened?.history ?? [],
|
|
1808
|
-
queue: Array.isArray(opened?.queue) ? opened.queue : [],
|
|
1809
|
-
context: opened?.context ?? null,
|
|
1810
|
-
})
|
|
1811
|
-
return
|
|
1812
|
-
}
|
|
1813
|
-
case 'session.rename': {
|
|
1814
|
-
if (typeof frame.sessionId !== 'string' || typeof frame.title !== 'string') {
|
|
1815
|
-
throw new Error('sessionId and title required')
|
|
1816
|
-
}
|
|
1817
|
-
const result = await this.callBridgeResult('renameSession', frame.sessionId, frame.title)
|
|
1818
|
-
if (!result.ok) {
|
|
1819
|
-
peer.sendObject({ type: 'error', code: result.code, message: result.message })
|
|
1820
|
-
return
|
|
1821
|
-
}
|
|
1822
|
-
const sessions = await this.fetchSessions()
|
|
1823
|
-
const session = sessions.find((item) => item && item.id === frame.sessionId) ?? null
|
|
1824
|
-
this.broadcast({
|
|
1825
|
-
type: 'session.updated',
|
|
1826
|
-
sessionId: frame.sessionId,
|
|
1827
|
-
title: result.value?.title ?? frame.title,
|
|
1828
|
-
session,
|
|
1829
|
-
})
|
|
1830
|
-
this.broadcast({ type: 'sessions', sessions, workspaces: await this.fetchWorkspaces(), activeSessionId: null })
|
|
1831
|
-
return
|
|
1832
|
-
}
|
|
1833
|
-
case 'session.fork': {
|
|
1834
|
-
if (typeof frame.sessionId !== 'string') throw new Error('sessionId required')
|
|
1835
|
-
const atSeq = Number.isInteger(frame.atSeq) && frame.atSeq >= 0 ? frame.atSeq : undefined
|
|
1836
|
-
const result = await this.callBridgeResult('forkSession', frame.sessionId, atSeq)
|
|
1837
|
-
if (!result.ok) {
|
|
1838
|
-
peer.sendObject({ type: 'error', code: result.code, message: result.message })
|
|
1839
|
-
return
|
|
1840
|
-
}
|
|
1841
|
-
const forkId = result.value?.sessionId
|
|
1842
|
-
this.broadcastSessionRefresh()
|
|
1843
|
-
if (typeof forkId !== 'string') return
|
|
1844
|
-
// Open the fork for the requesting phone through the normal path; the
|
|
1845
|
-
// other devices get the new row from the `sessions` refresh.
|
|
1846
|
-
try {
|
|
1847
|
-
const opened = await this.callBridge('openSession', forkId)
|
|
1848
|
-
peer.sendObject({
|
|
1849
|
-
type: 'session.opened',
|
|
1850
|
-
session: opened?.session ?? null,
|
|
1851
|
-
history: opened?.history ?? [],
|
|
1852
|
-
queue: Array.isArray(opened?.queue) ? opened.queue : [],
|
|
1853
|
-
context: opened?.context ?? null,
|
|
1854
|
-
})
|
|
1855
|
-
} catch (error) {
|
|
1856
|
-
peer.sendObject({
|
|
1857
|
-
type: 'error',
|
|
1858
|
-
code: 'internal',
|
|
1859
|
-
message: `the fork was created but could not be opened: ${error instanceof Error ? error.message : String(error)}`,
|
|
1860
|
-
})
|
|
1861
|
-
}
|
|
1862
|
-
return
|
|
1863
|
-
}
|
|
1864
|
-
case 'sessions.search': {
|
|
1865
|
-
if (typeof frame.query !== 'string') throw new Error('query required')
|
|
1866
|
-
const result = await this.callBridgeResult('searchSessions', frame.query)
|
|
1867
|
-
if (!result.ok) {
|
|
1868
|
-
peer.sendObject({ type: 'error', code: result.code, message: result.message })
|
|
1869
|
-
return
|
|
1870
|
-
}
|
|
1871
|
-
peer.sendObject({
|
|
1872
|
-
type: 'sessions.found',
|
|
1873
|
-
query: result.value?.query ?? frame.query,
|
|
1874
|
-
results: Array.isArray(result.value?.results) ? result.value.results : [],
|
|
1875
|
-
hasMore: result.value?.hasMore === true,
|
|
1876
|
-
})
|
|
1877
|
-
return
|
|
1878
|
-
}
|
|
1879
|
-
case 'session.pin':
|
|
1880
|
-
case 'session.unpin': {
|
|
1881
|
-
if (typeof frame.sessionId !== 'string') throw new Error('sessionId required')
|
|
1882
|
-
const result = await this.callBridgeResult('setSessionPinned', frame.sessionId, type === 'session.pin')
|
|
1883
|
-
if (!result.ok) {
|
|
1884
|
-
peer.sendObject({ type: 'error', code: result.code, message: result.message })
|
|
1885
|
-
return
|
|
1886
|
-
}
|
|
1887
|
-
peer.sendObject({
|
|
1888
|
-
type: 'session.pinned',
|
|
1889
|
-
sessionId: frame.sessionId,
|
|
1890
|
-
pinned: result.value?.pinned === true,
|
|
1891
|
-
archived: result.value?.archived === true,
|
|
1892
|
-
})
|
|
1893
|
-
this.broadcastSessionRefresh()
|
|
1894
|
-
return
|
|
1895
|
-
}
|
|
1896
|
-
case 'session.archive':
|
|
1897
|
-
case 'session.unarchive': {
|
|
1898
|
-
if (typeof frame.sessionId !== 'string') throw new Error('sessionId required')
|
|
1899
|
-
const stopActivity = frame.stopActivity === true
|
|
1900
|
-
const result = await this.callBridgeResult(
|
|
1901
|
-
'setSessionArchived',
|
|
1902
|
-
frame.sessionId,
|
|
1903
|
-
type === 'session.archive',
|
|
1904
|
-
stopActivity,
|
|
1905
|
-
)
|
|
1906
|
-
if (!result.ok) {
|
|
1907
|
-
peer.sendObject({ type: 'error', code: result.code, message: result.message })
|
|
1908
|
-
return
|
|
1909
|
-
}
|
|
1910
|
-
peer.sendObject({
|
|
1911
|
-
type: 'session.archived',
|
|
1912
|
-
sessionId: frame.sessionId,
|
|
1913
|
-
archived: result.value?.archived === true,
|
|
1914
|
-
pinned: result.value?.pinned === true,
|
|
1915
|
-
})
|
|
1916
|
-
this.broadcastSessionRefresh()
|
|
1917
|
-
return
|
|
1918
|
-
}
|
|
1919
|
-
case 'queue.list': {
|
|
1920
|
-
if (typeof frame.sessionId !== 'string') throw new Error('sessionId required')
|
|
1921
|
-
const result = await this.callBridgeResult('listQueue', frame.sessionId)
|
|
1922
|
-
if (!result.ok) {
|
|
1923
|
-
peer.sendObject({ type: 'error', code: result.code, message: result.message })
|
|
1924
|
-
return
|
|
1925
|
-
}
|
|
1926
|
-
peer.sendObject({
|
|
1927
|
-
type: 'queue',
|
|
1928
|
-
sessionId: frame.sessionId,
|
|
1929
|
-
items: Array.isArray(result.value?.items) ? result.value.items : [],
|
|
1930
|
-
pendingInput: Array.isArray(result.value?.pendingInput) ? result.value.pendingInput : [],
|
|
1931
|
-
running: result.value?.running === true,
|
|
1932
|
-
active: result.value?.active === true,
|
|
1933
|
-
})
|
|
1934
|
-
return
|
|
1935
|
-
}
|
|
1936
|
-
case 'queue.update': {
|
|
1937
|
-
if (typeof frame.sessionId !== 'string' || typeof frame.itemId !== 'string') {
|
|
1938
|
-
throw new Error('sessionId and itemId required')
|
|
1939
|
-
}
|
|
1940
|
-
const action = frame.action === 'edit' || frame.action === 'remove' || frame.action === 'steer'
|
|
1941
|
-
? frame.action
|
|
1942
|
-
: null
|
|
1943
|
-
if (action === null) throw new Error('action must be edit, remove or steer')
|
|
1944
|
-
const result = await this.callBridgeResult(
|
|
1945
|
-
'updateQueue',
|
|
1946
|
-
frame.sessionId,
|
|
1947
|
-
frame.itemId,
|
|
1948
|
-
action,
|
|
1949
|
-
typeof frame.text === 'string' ? frame.text : undefined,
|
|
1950
|
-
)
|
|
1951
|
-
if (!result.ok) {
|
|
1952
|
-
peer.sendObject({ type: 'error', code: result.code, message: result.message })
|
|
1953
|
-
return
|
|
1954
|
-
}
|
|
1955
|
-
// Ack only to the requesting device; every device learns the new queue
|
|
1956
|
-
// from the bridge's own `queue.changed` push. Read the live state once
|
|
1957
|
-
// more so the ack carries the full queue-frame shape.
|
|
1958
|
-
const state = await this.callBridgeResult('listQueue', frame.sessionId)
|
|
1959
|
-
peer.sendObject({
|
|
1960
|
-
type: 'queue',
|
|
1961
|
-
sessionId: frame.sessionId,
|
|
1962
|
-
items: Array.isArray(result.value?.items) ? result.value.items : [],
|
|
1963
|
-
pendingInput: state.ok && Array.isArray(state.value?.pendingInput) ? state.value.pendingInput : [],
|
|
1964
|
-
running: state.ok ? state.value?.running === true : true,
|
|
1965
|
-
active: state.ok ? state.value?.active === true : true,
|
|
1966
|
-
})
|
|
1967
|
-
return
|
|
1968
|
-
}
|
|
1969
|
-
case 'context.get': {
|
|
1970
|
-
if (typeof frame.sessionId !== 'string') throw new Error('sessionId required')
|
|
1971
|
-
const result = await this.callBridgeResult('contextFor', frame.sessionId)
|
|
1972
|
-
if (!result.ok) {
|
|
1973
|
-
peer.sendObject({ type: 'error', code: result.code, message: result.message })
|
|
1974
|
-
return
|
|
1975
|
-
}
|
|
1976
|
-
peer.sendObject({
|
|
1977
|
-
type: 'context',
|
|
1978
|
-
sessionId: frame.sessionId,
|
|
1979
|
-
usedTokens: result.value?.usedTokens ?? null,
|
|
1980
|
-
pressureTokens: result.value?.pressureTokens ?? null,
|
|
1981
|
-
projectedTokens: result.value?.projectedTokens ?? null,
|
|
1982
|
-
contextWindow: result.value?.contextWindow ?? null,
|
|
1983
|
-
basis: typeof result.value?.basis === 'string' ? result.value.basis : 'unknown',
|
|
1984
|
-
tokenUsage: result.value?.tokenUsage ?? null,
|
|
1985
|
-
})
|
|
1986
|
-
return
|
|
1987
|
-
}
|
|
1988
|
-
case 'changes.list': {
|
|
1989
|
-
if (typeof frame.sessionId !== 'string') throw new Error('sessionId required')
|
|
1990
|
-
const result = await this.callBridgeResult('changesList', frame.sessionId, frame.limit)
|
|
1991
|
-
if (!result.ok) {
|
|
1992
|
-
peer.sendObject({ type: 'error', code: result.code, message: result.message })
|
|
1993
|
-
return
|
|
1994
|
-
}
|
|
1995
|
-
peer.sendObject({
|
|
1996
|
-
type: 'changes',
|
|
1997
|
-
sessionId: frame.sessionId,
|
|
1998
|
-
items: Array.isArray(result.value?.items) ? result.value.items : [],
|
|
1999
|
-
})
|
|
2000
|
-
return
|
|
2001
|
-
}
|
|
2002
|
-
case 'changes.diff': {
|
|
2003
|
-
if (typeof frame.sessionId !== 'string' || !Number.isInteger(frame.seq) || !Number.isInteger(frame.index)) {
|
|
2004
|
-
throw new Error('sessionId, seq and index required')
|
|
2005
|
-
}
|
|
2006
|
-
const result = await this.callBridgeResult('changesDiff', frame.sessionId, frame.seq, frame.index)
|
|
2007
|
-
if (!result.ok) {
|
|
2008
|
-
peer.sendObject({ type: 'error', code: result.code, message: result.message })
|
|
2009
|
-
return
|
|
2010
|
-
}
|
|
2011
|
-
peer.sendObject({
|
|
2012
|
-
type: 'changes.diff',
|
|
2013
|
-
sessionId: frame.sessionId,
|
|
2014
|
-
seq: result.value?.seq ?? frame.seq,
|
|
2015
|
-
index: result.value?.index ?? frame.index,
|
|
2016
|
-
kind: typeof result.value?.kind === 'string' ? result.value.kind : 'text',
|
|
2017
|
-
path: typeof result.value?.path === 'string' ? result.value.path : '',
|
|
2018
|
-
coarse: result.value?.coarse === true,
|
|
2019
|
-
hunks: Array.isArray(result.value?.hunks) ? result.value.hunks : [],
|
|
2020
|
-
})
|
|
2021
|
-
return
|
|
2022
|
-
}
|
|
2023
|
-
case 'commands.list': {
|
|
2024
|
-
if (typeof frame.sessionId !== 'string') throw new Error('sessionId required')
|
|
2025
|
-
const result = await this.callBridgeResult('listCommands', frame.sessionId)
|
|
2026
|
-
if (!result.ok) {
|
|
2027
|
-
peer.sendObject({ type: 'error', code: result.code, message: result.message })
|
|
2028
|
-
return
|
|
2029
|
-
}
|
|
2030
|
-
peer.sendObject({
|
|
2031
|
-
type: 'commands',
|
|
2032
|
-
sessionId: frame.sessionId,
|
|
2033
|
-
available: result.value?.available === true,
|
|
2034
|
-
items: Array.isArray(result.value?.items) ? result.value.items : [],
|
|
2035
|
-
reason: typeof result.value?.reason === 'string' ? result.value.reason : null,
|
|
2036
|
-
})
|
|
2037
|
-
return
|
|
2038
|
-
}
|
|
2039
|
-
case 'commands.execute': {
|
|
2040
|
-
if (typeof frame.sessionId !== 'string' || typeof frame.line !== 'string') {
|
|
2041
|
-
throw new Error('sessionId and line required')
|
|
2042
|
-
}
|
|
2043
|
-
const result = await this.callBridgeResult('executeCommand', frame.sessionId, frame.line)
|
|
2044
|
-
if (!result.ok) {
|
|
2045
|
-
peer.sendObject({ type: 'error', code: result.code, message: result.message })
|
|
2046
|
-
return
|
|
2047
|
-
}
|
|
2048
|
-
peer.sendObject({
|
|
2049
|
-
type: 'command.result',
|
|
2050
|
-
sessionId: frame.sessionId,
|
|
2051
|
-
commandId: result.value?.commandId ?? null,
|
|
2052
|
-
name: typeof result.value?.name === 'string' ? result.value.name : '',
|
|
2053
|
-
kind: result.value?.kind === 'error' ? 'error' : 'success',
|
|
2054
|
-
text: typeof result.value?.text === 'string' ? result.value.text : null,
|
|
2055
|
-
sourceEventSeq: result.value?.sourceEventSeq ?? null,
|
|
2056
|
-
})
|
|
2057
|
-
return
|
|
2058
|
-
}
|
|
2059
|
-
case 'sessions.create': {
|
|
2060
|
-
const cwd = typeof frame.cwd === 'string' ? frame.cwd.trim() : ''
|
|
2061
|
-
const created = await this.callBridge('createSession', {
|
|
2062
|
-
preset: typeof frame.preset === 'string' ? frame.preset : undefined,
|
|
2063
|
-
cwd: cwd.length > 0 ? cwd : undefined,
|
|
2064
|
-
})
|
|
2065
|
-
peer.sendObject({
|
|
2066
|
-
type: 'sessions',
|
|
2067
|
-
sessions: await this.fetchSessions(),
|
|
2068
|
-
workspaces: await this.fetchWorkspaces(),
|
|
2069
|
-
activeSessionId: created?.id ?? null,
|
|
2070
|
-
})
|
|
2071
|
-
return
|
|
2072
|
-
}
|
|
2073
|
-
case 'history.load': {
|
|
2074
|
-
if (typeof frame.sessionId !== 'string') throw new Error('sessionId required')
|
|
2075
|
-
const limit = Number.isInteger(frame.limit) ? Math.min(Math.max(frame.limit, 1), 200) : 50
|
|
2076
|
-
const items = await this.callBridge('history', frame.sessionId, { limit })
|
|
2077
|
-
peer.sendObject({ type: 'history', sessionId: frame.sessionId, items: Array.isArray(items) ? items : [], hasMore: false })
|
|
2078
|
-
return
|
|
2079
|
-
}
|
|
2080
|
-
case 'prompt': {
|
|
2081
|
-
const hasText = typeof frame.text === 'string' && frame.text.trim().length > 0
|
|
2082
|
-
const hasAttachments = Array.isArray(frame.attachments) && frame.attachments.length > 0
|
|
2083
|
-
if (typeof frame.sessionId !== 'string' || (!hasText && !hasAttachments)) {
|
|
2084
|
-
throw new Error('sessionId and text or attachments required')
|
|
2085
|
-
}
|
|
2086
|
-
await this.callBridge(
|
|
2087
|
-
'prompt',
|
|
2088
|
-
frame.sessionId,
|
|
2089
|
-
typeof frame.text === 'string' ? frame.text : '',
|
|
2090
|
-
typeof frame.requestId === 'string' ? frame.requestId : undefined,
|
|
2091
|
-
Array.isArray(frame.attachments) ? frame.attachments : undefined,
|
|
2092
|
-
frame.mode === 'steer' ? 'steer' : 'queue',
|
|
2093
|
-
)
|
|
2094
|
-
return
|
|
2095
|
-
}
|
|
2096
|
-
case 'stop': {
|
|
2097
|
-
if (typeof frame.sessionId !== 'string') throw new Error('sessionId required')
|
|
2098
|
-
await this.callBridge('cancel', frame.sessionId)
|
|
2099
|
-
return
|
|
2100
|
-
}
|
|
2101
|
-
case 'approval.answer': {
|
|
2102
|
-
if (typeof frame.requestId !== 'string') throw new Error('requestId required')
|
|
2103
|
-
// Per-device permission: a device the owner restricted may not answer.
|
|
2104
|
-
if (peer.device.canApprove === false) {
|
|
2105
|
-
peer.sendObject({
|
|
2106
|
-
type: 'error',
|
|
2107
|
-
code: 'forbidden',
|
|
2108
|
-
message: 'this device is not allowed to answer approvals',
|
|
2109
|
-
})
|
|
2110
|
-
return
|
|
2111
|
-
}
|
|
2112
|
-
const decision = frame.decision === 'allow' ? 'allow' : frame.decision === 'reject' ? 'reject' : null
|
|
2113
|
-
if (decision === null) throw new Error('decision must be allow or reject')
|
|
2114
|
-
this.answerOrigins.set(frame.requestId, 'phone')
|
|
2115
|
-
let accepted
|
|
2116
|
-
try {
|
|
2117
|
-
accepted = await this.callBridge('answerApproval', frame.requestId, decision)
|
|
2118
|
-
} finally {
|
|
2119
|
-
this.answerOrigins.delete(frame.requestId)
|
|
2120
|
-
}
|
|
2121
|
-
this.appendDebug(`approval.answer req=${frame.requestId} decision=${decision} accepted=${accepted !== false}`)
|
|
2122
|
-
if (accepted === false) {
|
|
2123
|
-
peer.sendObject({ type: 'error', code: 'not-found', message: 'approval is no longer pending' })
|
|
2124
|
-
}
|
|
2125
|
-
return
|
|
2126
|
-
}
|
|
2127
|
-
case 'question.answer': {
|
|
2128
|
-
if (!Array.isArray(frame.answers)) throw new Error('answers required')
|
|
2129
|
-
const requestId = typeof frame.requestId === 'string' ? frame.requestId : undefined
|
|
2130
|
-
if (requestId !== undefined) this.answerOrigins.set(requestId, 'phone')
|
|
2131
|
-
let result
|
|
2132
|
-
try {
|
|
2133
|
-
result = await this.callBridge('answerQuestion', {
|
|
2134
|
-
requestId,
|
|
2135
|
-
sessionId: typeof frame.sessionId === 'string' ? frame.sessionId : undefined,
|
|
2136
|
-
callId: typeof frame.callId === 'string' ? frame.callId : undefined,
|
|
2137
|
-
answers: frame.answers,
|
|
2138
|
-
})
|
|
2139
|
-
} finally {
|
|
2140
|
-
if (requestId !== undefined) this.answerOrigins.delete(requestId)
|
|
2141
|
-
}
|
|
2142
|
-
if (result === false) {
|
|
2143
|
-
peer.sendObject({ type: 'error', code: 'not-found', message: 'the question is no longer open' })
|
|
2144
|
-
}
|
|
2145
|
-
return
|
|
2146
|
-
}
|
|
2147
|
-
case 'model.list': {
|
|
2148
|
-
const models = await this.callBridge('listModels')
|
|
2149
|
-
peer.sendObject({ type: 'models', catalog: models?.catalog ?? [], current: models?.current ?? null })
|
|
2150
|
-
return
|
|
2151
|
-
}
|
|
2152
|
-
case 'model.select': {
|
|
2153
|
-
if (typeof frame.sessionId !== 'string' || typeof frame.provider !== 'string' || typeof frame.model !== 'string') {
|
|
2154
|
-
throw new Error('sessionId, provider and model required')
|
|
2155
|
-
}
|
|
2156
|
-
await this.callBridge('selectModel', frame.sessionId, {
|
|
2157
|
-
provider: frame.provider,
|
|
2158
|
-
model: frame.model,
|
|
2159
|
-
reasoningEffort: frame.reasoningEffort ?? null,
|
|
2160
|
-
})
|
|
2161
|
-
return
|
|
2162
|
-
}
|
|
2163
|
-
case 'preset.list': {
|
|
2164
|
-
const presets = await this.callBridge('listPresets')
|
|
2165
|
-
peer.sendObject({ type: 'presets', presets: presets?.presets ?? [], current: presets?.current ?? null })
|
|
2166
|
-
return
|
|
2167
|
-
}
|
|
2168
|
-
case 'limits': {
|
|
2169
|
-
const result = await this.callBridgeResult('imageLimits')
|
|
2170
|
-
peer.sendObject({
|
|
2171
|
-
type: 'limits',
|
|
2172
|
-
image: result.ok && result.value && typeof result.value === 'object' ? result.value.image ?? null : null,
|
|
2173
|
-
})
|
|
2174
|
-
return
|
|
2175
|
-
}
|
|
2176
|
-
case 'preset.select': {
|
|
2177
|
-
if (typeof frame.sessionId !== 'string' || typeof frame.preset !== 'string') {
|
|
2178
|
-
throw new Error('sessionId and preset required')
|
|
2179
|
-
}
|
|
2180
|
-
await this.callBridge('selectPreset', frame.sessionId, frame.preset)
|
|
2181
|
-
return
|
|
2182
|
-
}
|
|
2183
|
-
default:
|
|
2184
|
-
peer.sendObject({ type: 'error', code: 'bad-request', message: `unknown frame type ${type}` })
|
|
2031
|
+
const method = FRAME_HANDLERS[type]
|
|
2032
|
+
if (method === undefined) {
|
|
2033
|
+
peer.sendObject({ type: 'error', code: 'bad-request', message: `unknown frame type ${type}` })
|
|
2034
|
+
return
|
|
2185
2035
|
}
|
|
2036
|
+
await this[method](peer, frame, type)
|
|
2186
2037
|
}
|
|
2187
2038
|
|
|
2039
|
+
|
|
2040
|
+
|
|
2041
|
+
|
|
2042
|
+
|
|
2043
|
+
|
|
2044
|
+
|
|
2045
|
+
|
|
2046
|
+
|
|
2047
|
+
|
|
2048
|
+
|
|
2049
|
+
|
|
2050
|
+
|
|
2051
|
+
|
|
2052
|
+
|
|
2053
|
+
|
|
2054
|
+
|
|
2055
|
+
|
|
2056
|
+
|
|
2057
|
+
|
|
2058
|
+
|
|
2059
|
+
|
|
2060
|
+
|
|
2061
|
+
|
|
2062
|
+
|
|
2063
|
+
|
|
2064
|
+
|
|
2065
|
+
|
|
2066
|
+
|
|
2188
2067
|
broadcast(value) {
|
|
2189
2068
|
for (const peer of this.peers) peer.sendObject(value)
|
|
2190
2069
|
}
|
|
@@ -2342,6 +2221,21 @@ export class RemoteMobileServer {
|
|
|
2342
2221
|
}
|
|
2343
2222
|
|
|
2344
2223
|
/** Pending approvals for the desktop overlay (both devices show the same list). */
|
|
2224
|
+
/** IDs only: the full cards were already replayed above. */
|
|
2225
|
+
pendingSnapshot() {
|
|
2226
|
+
return {
|
|
2227
|
+
approvals: [...this.pendingApprovals.values()].map((approval) => ({
|
|
2228
|
+
requestId: approval.requestId,
|
|
2229
|
+
sessionId: approval.sessionId ?? null,
|
|
2230
|
+
})),
|
|
2231
|
+
questions: [...this.pendingQuestions.values()].map((question) => ({
|
|
2232
|
+
requestId: question.requestId,
|
|
2233
|
+
callId: question.callId ?? null,
|
|
2234
|
+
sessionId: question.sessionId ?? null,
|
|
2235
|
+
})),
|
|
2236
|
+
}
|
|
2237
|
+
}
|
|
2238
|
+
|
|
2345
2239
|
pendingApprovalsSnapshot() {
|
|
2346
2240
|
return [...this.pendingApprovals.values()].sort((left, right) => left.createdAt - right.createdAt)
|
|
2347
2241
|
}
|
|
@@ -2381,6 +2275,16 @@ export class RemoteMobileServer {
|
|
|
2381
2275
|
})
|
|
2382
2276
|
}
|
|
2383
2277
|
|
|
2278
|
+
broadcastSubagentStatus(payload) {
|
|
2279
|
+
if (!payload || typeof payload.parentSessionId !== 'string' || payload.parentSessionId.length === 0) return
|
|
2280
|
+
this.broadcast({
|
|
2281
|
+
type: 'subagents.changed',
|
|
2282
|
+
sessionId: payload.parentSessionId,
|
|
2283
|
+
subagentId: typeof payload.subagentId === 'string' ? payload.subagentId : null,
|
|
2284
|
+
running: payload.running === true,
|
|
2285
|
+
})
|
|
2286
|
+
}
|
|
2287
|
+
|
|
2384
2288
|
broadcastStatus(payload) {
|
|
2385
2289
|
if (payload === null || typeof payload !== 'object') return
|
|
2386
2290
|
this.broadcast({ type: 'session.status', sessionId: payload.sessionId, running: payload.running === true })
|
|
@@ -2469,7 +2373,11 @@ export class RemoteMobileServer {
|
|
|
2469
2373
|
this.pushTags.set(tag, now)
|
|
2470
2374
|
let sent = 0
|
|
2471
2375
|
let gone = 0
|
|
2376
|
+
const kind = typeof payload?.kind === 'string' ? payload.kind : ''
|
|
2472
2377
|
for (const subscription of this.push.subscriptions()) {
|
|
2378
|
+
if (!pushAllowed(this.pushPrefs.get(subscription.deviceId), kind, now)) {
|
|
2379
|
+
continue
|
|
2380
|
+
}
|
|
2473
2381
|
let result
|
|
2474
2382
|
try {
|
|
2475
2383
|
result = await this.push.sendNotification(subscription, payload)
|
|
@@ -2644,5 +2552,15 @@ export class RemoteMobileServer {
|
|
|
2644
2552
|
this.broadcastSessionRefresh(250)
|
|
2645
2553
|
}
|
|
2646
2554
|
}
|
|
2555
|
+
Object.assign(RemoteMobileServer.prototype, connectionFrameMethods)
|
|
2556
|
+
Object.assign(RemoteMobileServer.prototype, sessionsFrameMethods)
|
|
2557
|
+
Object.assign(RemoteMobileServer.prototype, promptsFrameMethods)
|
|
2558
|
+
Object.assign(RemoteMobileServer.prototype, queueFrameMethods)
|
|
2559
|
+
Object.assign(RemoteMobileServer.prototype, activityFrameMethods)
|
|
2560
|
+
Object.assign(RemoteMobileServer.prototype, interactionsFrameMethods)
|
|
2561
|
+
Object.assign(RemoteMobileServer.prototype, settingsFrameMethods)
|
|
2562
|
+
Object.assign(RemoteMobileServer.prototype, historyFrameMethods)
|
|
2563
|
+
Object.assign(RemoteMobileServer.prototype, subagentsFrameMethods)
|
|
2564
|
+
|
|
2647
2565
|
|
|
2648
2566
|
|