dsh-remote-plugin 0.7.6 → 0.8.0-rc.2
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/apk/dsh-remote.apk +0 -0
- package/gateway.cjs +708 -12
- package/index.mjs +20 -5
- package/package.json +1 -1
- package/plugin-center.mjs +9 -2
- package/public/admin.html +4 -0
- package/public/admin.js +4 -0
- package/public/app.js +137 -26
- package/public/chat-files.js +3 -1
- package/public/desktop/desktop.html +6 -0
- package/public/desktop/desktop.js +81 -21
- package/public/index.html +7 -1
- package/public/motion.js +3 -3
- package/public/network.js +7 -1
- package/public/operations.js +109 -0
- package/public/relay-settings.css +2 -0
- package/public/relay-settings.js +119 -0
- package/public/update.json +4 -4
- package/public/version.json +1 -1
- package/public/workflow.css +151 -0
- package/public/workflow.js +286 -0
|
@@ -561,11 +561,13 @@ function closeNotesModal() {
|
|
|
561
561
|
if (notesVersion) { LS.set(NOTES_KEY, notesVersion); notesVersion = '' }
|
|
562
562
|
}
|
|
563
563
|
async function checkNotesOnStart() {
|
|
564
|
+
if (typeof window !== 'undefined' && window.DshWorkflow?.isMounted()) return
|
|
564
565
|
try {
|
|
565
566
|
const res = await fetch('../update.json?t=' + Date.now(), { cache: 'no-store' })
|
|
566
567
|
if (!res.ok || res.redirected || !String(res.headers.get('content-type') || '').includes('application/json')) return
|
|
567
568
|
const info = await res.json()
|
|
568
569
|
if (!info || typeof info !== 'object' || !info.version) return
|
|
570
|
+
if (typeof window !== 'undefined' && window.DshWorkflow?.isMounted()) return
|
|
569
571
|
openNotesModal(info)
|
|
570
572
|
} catch {}
|
|
571
573
|
}
|
|
@@ -661,7 +663,10 @@ async function rpc(method, payload = {}, timeoutMs = 45000) {
|
|
|
661
663
|
if (typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function') {
|
|
662
664
|
opts.signal = AbortSignal.timeout(timeoutMs)
|
|
663
665
|
}
|
|
664
|
-
const
|
|
666
|
+
const operation = window.DshOperations?.supports(method) && activeGatewayCapability('operations') === true
|
|
667
|
+
const connection = operation ? captureConnection() : null
|
|
668
|
+
const receipt = operation ? await window.DshOperations.execute({ method, payload, url: apiUrl, headers: opts.headers, valid: () => connection.valid() }) : null
|
|
669
|
+
const res = receipt ? { status: 200, ok: true, json: async () => receipt } : await fetch(apiUrl('/api/' + method), opts)
|
|
665
670
|
if (res.status === 401) throw new Error('AUTH')
|
|
666
671
|
if (!res.ok) throw new Error('HTTP ' + res.status)
|
|
667
672
|
const full = await res.json()
|
|
@@ -1390,7 +1395,7 @@ async function pollKind(kind, cancellation) {
|
|
|
1390
1395
|
const timeout = typeof AbortSignal?.timeout === 'function' ? AbortSignal.timeout(window.DshNetwork?.profile().pollTimeout || 30000) : undefined
|
|
1391
1396
|
const signal = cancellation && timeout && typeof AbortSignal.any === 'function' ? AbortSignal.any([cancellation, timeout]) : timeout || cancellation
|
|
1392
1397
|
const headers = { authorization: 'Bearer ' + state.token, 'x-dsh-remote-client': 'web', ...clientIdHeaders() }
|
|
1393
|
-
res =
|
|
1398
|
+
res = await fetch(apiUrl(`/api/events.poll?kind=${kind}&since=${since}&wait=25000&epoch=${encodeURIComponent(cursors[kind + "Epoch"] || "")}`), { ...(signal ? { signal } : {}), headers })
|
|
1394
1399
|
} catch { return }
|
|
1395
1400
|
if (!valid()) return
|
|
1396
1401
|
if (res.status === 401) { toast(t('ds.toastAuth'), 'err'); return }
|
|
@@ -1399,13 +1404,15 @@ async function pollKind(kind, cancellation) {
|
|
|
1399
1404
|
try { data = await res.json() } catch { return }
|
|
1400
1405
|
if (!valid()) return
|
|
1401
1406
|
if (!data || !Array.isArray(data.events)) return
|
|
1402
|
-
const reset = data.truncated === true || (typeof data.latestSeq === 'number' && data.latestSeq < since)
|
|
1407
|
+
const reset = data.reset === true || (!!data.epoch && !!cursors[kind + 'Epoch'] && cursors[kind + 'Epoch'] !== data.epoch) || data.truncated === true || (typeof data.latestSeq === 'number' && data.latestSeq < since)
|
|
1403
1408
|
if (reset) {
|
|
1404
1409
|
state.pollSeq[kind] = 0
|
|
1405
1410
|
if (kind === 'mux') renderNotifStack()
|
|
1406
1411
|
refreshSessions()
|
|
1407
1412
|
if (state.current) void resyncCurrentSession()
|
|
1408
1413
|
}
|
|
1414
|
+
if (data.epoch) cursors[kind + 'Epoch'] = data.epoch
|
|
1415
|
+
for (const frame of data.baseline || []) { if (kind === 'mux') onMuxFrame(frame); else onHostFrame(frame) }
|
|
1409
1416
|
for (const item of data.events) {
|
|
1410
1417
|
if (item.seq > (state.pollSeq[kind] || 0)) {
|
|
1411
1418
|
state.pollSeq[kind] = item.seq
|
|
@@ -1521,6 +1528,7 @@ function setCompactionStatus(sessionId, next) {
|
|
|
1521
1528
|
}
|
|
1522
1529
|
if (previous?.active && previous.notify && next?.notify !== false && ['complete', 'failed'].includes(next?.phase)) {
|
|
1523
1530
|
const command = previous.command || 'compact'
|
|
1531
|
+
if (command === 'export' && next?.phase === 'complete' && state.current === sessionId && typeof downloadSessionExport === 'function') void downloadSessionExport(sessionId)
|
|
1524
1532
|
if (next?.phase === 'failed') toast(command === 'compact'
|
|
1525
1533
|
? t('ds.compactFailed', { msg: next.message || t('ds.sessionRecoveryFailed') })
|
|
1526
1534
|
: t('ds.commandFailed', { command, msg: next.message || t('ds.sessionRecoveryFailed') }), 'err')
|
|
@@ -2392,7 +2400,7 @@ async function runSlashCommand(text) {
|
|
|
2392
2400
|
const res = await fetch(apiUrl('/remote/api/command'), {
|
|
2393
2401
|
method: 'POST',
|
|
2394
2402
|
headers: { 'content-type': 'application/json', authorization: 'Bearer ' + state.token, 'x-dsh-remote-client': 'web', ...clientIdHeaders() },
|
|
2395
|
-
body: JSON.stringify({ sessionId, line: clean }),
|
|
2403
|
+
body: JSON.stringify({ sessionId, line: clean, async: true }),
|
|
2396
2404
|
...(signal ? { signal } : {})
|
|
2397
2405
|
})
|
|
2398
2406
|
if (!connection.valid()) return true
|
|
@@ -2406,7 +2414,7 @@ async function runSlashCommand(text) {
|
|
|
2406
2414
|
if (data?.ok === false) return true
|
|
2407
2415
|
if (data?.ok === true && data.executed === true) {
|
|
2408
2416
|
if (data.accepted) {
|
|
2409
|
-
if (command === 'compact') {
|
|
2417
|
+
if (command === 'compact' || command === 'export') {
|
|
2410
2418
|
setCompactionStatus(sessionId, { ...(data.operation || data.compact), active: true, command, source: 'command' })
|
|
2411
2419
|
} else {
|
|
2412
2420
|
state.pendingCommands[sessionId] = command
|
|
@@ -2426,7 +2434,7 @@ async function runSlashCommand(text) {
|
|
|
2426
2434
|
return !connection.valid() || state.current !== sessionId
|
|
2427
2435
|
}
|
|
2428
2436
|
|
|
2429
|
-
async function sendMessage() {
|
|
2437
|
+
async function sendMessage(requestedMode = 'queue') {
|
|
2430
2438
|
const input = $('composer')
|
|
2431
2439
|
const originalText = input.value, text = originalText.trim()
|
|
2432
2440
|
if (!text || !state.current) return
|
|
@@ -2442,7 +2450,7 @@ async function sendMessage() {
|
|
|
2442
2450
|
setSessionRecovery('resuming')
|
|
2443
2451
|
const v = await safeRpc('session.prompt', {
|
|
2444
2452
|
sessionId,
|
|
2445
|
-
mode: 'queue',
|
|
2453
|
+
mode: requestedMode === 'steer' && state.byId.get(sessionId)?.running ? 'steer' : 'queue',
|
|
2446
2454
|
content: [{ type: 'text', text }]
|
|
2447
2455
|
}, '')
|
|
2448
2456
|
if (!valid()) return
|
|
@@ -2451,7 +2459,7 @@ async function sendMessage() {
|
|
|
2451
2459
|
setSessionRecovery('ready'); noteSessionTurnTime(sessionId, Date.now()); renderSessions(); toast(t('ds.toastSent'), 'ok')
|
|
2452
2460
|
}
|
|
2453
2461
|
else setSessionRecovery('error')
|
|
2454
|
-
} finally { pending.delete(history) }
|
|
2462
|
+
} finally { pending.delete(history); window.DshWorkflow?.update() }
|
|
2455
2463
|
}
|
|
2456
2464
|
|
|
2457
2465
|
async function cancelSession() {
|
|
@@ -2512,6 +2520,7 @@ async function archiveCurrentSession() {
|
|
|
2512
2520
|
}
|
|
2513
2521
|
|
|
2514
2522
|
function updateComposerStatus() {
|
|
2523
|
+
window.DshWorkflow?.update()
|
|
2515
2524
|
const status = $('composer-status')
|
|
2516
2525
|
if (!status) return
|
|
2517
2526
|
const compact = activeCompaction()
|
|
@@ -3036,13 +3045,15 @@ function commitWorkspaceSessionOrder(workspaceId, order) {
|
|
|
3036
3045
|
renderWorkbench()
|
|
3037
3046
|
toast(t('ds.wbOrderSaved'), 'ok')
|
|
3038
3047
|
}
|
|
3039
|
-
async function refreshWorkbench({ silent = false } = {}) {
|
|
3048
|
+
async function refreshWorkbench({ silent = false, discover = false } = {}) {
|
|
3040
3049
|
const connection = captureConnection(), request = ++workbenchRequest
|
|
3041
3050
|
const valid = () => connection.valid() && request === workbenchRequest
|
|
3051
|
+
const sharedRead = (name, read) => window.DshNetwork?.shareRead ? window.DshNetwork.shareRead(JSON.stringify([connection.server, connection.token, name]), read) : read()
|
|
3042
3052
|
if (!state.token) { renderWorkbench(); return }
|
|
3053
|
+
const workspaceRead = sharedRead('workspace.list', () => connection.valid() ? safeRpc('workspace.list', {}, '') : null)
|
|
3043
3054
|
let wb = null
|
|
3044
3055
|
try {
|
|
3045
|
-
wb = await wbGateway('GET', '/workbench')
|
|
3056
|
+
wb = await sharedRead('workbench', () => connection.valid() ? wbGateway('GET', '/workbench') : null)
|
|
3046
3057
|
if (!valid()) return
|
|
3047
3058
|
state.wb.apiMissing = false
|
|
3048
3059
|
} catch (e) {
|
|
@@ -3051,10 +3062,12 @@ async function refreshWorkbench({ silent = false } = {}) {
|
|
|
3051
3062
|
if (!silent) toast(t('wb.loadFailed', { msg: e.message }), 'err')
|
|
3052
3063
|
if (!state.wb.bound && /404/.test(e.message)) state.wb.apiMissing = true
|
|
3053
3064
|
}
|
|
3054
|
-
const wl = await
|
|
3065
|
+
const wl = await workspaceRead
|
|
3055
3066
|
if (!valid()) return
|
|
3056
|
-
|
|
3057
|
-
|
|
3067
|
+
if(wl){
|
|
3068
|
+
state.archivedIds = Array.isArray(wl.archivedSessionIds) ? wl.archivedSessionIds : []
|
|
3069
|
+
state.workspaces = Array.isArray(wl.items) ? wl.items.slice() : []
|
|
3070
|
+
}
|
|
3058
3071
|
if (!wb) { renderWorkbench(); renderSessions(); return }
|
|
3059
3072
|
if (!wb.bound) {
|
|
3060
3073
|
state.wb = { bound: false, path: '', title: '', expanded: false, projects: null, open: null, apiMissing: false }
|
|
@@ -3065,9 +3078,9 @@ async function refreshWorkbench({ silent = false } = {}) {
|
|
|
3065
3078
|
state.wb.bound = true
|
|
3066
3079
|
state.wb.path = wb.path || ''
|
|
3067
3080
|
state.wb.title = wb.title || ''
|
|
3068
|
-
if (!wl) {
|
|
3081
|
+
if (!wl) { renderWorkbench(); renderSessions(); return }
|
|
3069
3082
|
const items = Array.isArray(wl.items) ? wl.items.slice() : []
|
|
3070
|
-
try {
|
|
3083
|
+
if (discover) try {
|
|
3071
3084
|
const listRes = await fetch(fsApiUrl('/list', { path: state.wb.path }), { headers: fsHeaders() })
|
|
3072
3085
|
if (!valid()) return
|
|
3073
3086
|
if (listRes.ok) {
|
|
@@ -3187,6 +3200,7 @@ async function openNewSessionModal() {
|
|
|
3187
3200
|
if (!state.token) return showView('view-settings')
|
|
3188
3201
|
if (!workspaceItems().length) await refreshWorkbench({ silent: true })
|
|
3189
3202
|
renderNewSessionWorkspace(LS.get('lastNewSessionWorkspaceV1', ''))
|
|
3203
|
+
if (workspaceItems().length === 1) return createSessionInWorkspace()
|
|
3190
3204
|
$('modal-new-session').classList.remove('hidden')
|
|
3191
3205
|
setTimeout(() => $('new-session-workspace')?.focus(), 50)
|
|
3192
3206
|
}
|
|
@@ -3204,9 +3218,12 @@ async function createSessionInWorkspace() {
|
|
|
3204
3218
|
if (!connection.valid() || !value?.sessionId) return
|
|
3205
3219
|
LS.set('lastNewSessionWorkspaceV1', workspaceId)
|
|
3206
3220
|
closeNewSessionModal()
|
|
3207
|
-
|
|
3208
|
-
|
|
3209
|
-
|
|
3221
|
+
const workspace = workspaceById(workspaceId)
|
|
3222
|
+
const session = { sessionId: value.sessionId, cwd: workspace?.path || '', running: false, projections: { values: {} } }
|
|
3223
|
+
state.byId.set(session.sessionId, session)
|
|
3224
|
+
state.sessions.unshift(session)
|
|
3225
|
+
void openSession(session.sessionId)
|
|
3226
|
+
void refreshSessions()
|
|
3210
3227
|
} finally {
|
|
3211
3228
|
createSessionInWorkspace.busy = false
|
|
3212
3229
|
button.disabled = false
|
|
@@ -3444,6 +3461,7 @@ window.addEventListener('offline',()=>startOverviewDetection(true))
|
|
|
3444
3461
|
document.addEventListener('visibilitychange',()=>{if(document.visibilityState==='visible')startOverviewDetection(true);else {overviewDetector?.pause();overviewPulse?.pause()}})
|
|
3445
3462
|
|
|
3446
3463
|
function renderOverviewDesktop() {
|
|
3464
|
+
window.DshWorkflow?.update()
|
|
3447
3465
|
const ring = $('ds-overview-pulse-ring')
|
|
3448
3466
|
if (!ring) return
|
|
3449
3467
|
const checks = overviewChecks()
|
|
@@ -3480,7 +3498,7 @@ function renderOverviewDesktop() {
|
|
|
3480
3498
|
...state.questions.map(q => ({ kind: 'question', item: q }))
|
|
3481
3499
|
]
|
|
3482
3500
|
$('ds-overview-attention-count').textContent = pending.length ? t('ds.pendingCount', { n: pending.length }) : '—'
|
|
3483
|
-
$('ds-overview-attention-list').innerHTML = pending.length ? pending.
|
|
3501
|
+
$('ds-overview-attention-list').innerHTML = pending.length ? pending.map(({ kind, item }) => {
|
|
3484
3502
|
const title = sessionLabelOf(state.byId.get(item.sessionId))
|
|
3485
3503
|
if (kind === 'approval') return `<div class="ds-overview-attention-item" data-ds-overview-approval="${esc(item.approvalId)}">
|
|
3486
3504
|
<span class="ds-overview-mark">⌁</span><span class="ds-overview-copy"><span class="ds-overview-item-title">${esc(item.toolName || t('ds.toolDefault'))}</span><span class="ds-overview-item-desc">${esc(desktopApprovalDetail(item))} · ${esc(title)}</span></span>
|
|
@@ -3551,9 +3569,12 @@ function openDesktopPlugins(route = 'manage') {
|
|
|
3551
3569
|
}
|
|
3552
3570
|
|
|
3553
3571
|
function showView(id) {
|
|
3572
|
+
window.DshWorkflow?.close()
|
|
3573
|
+
if (window.DshWorkflow?.isMounted() && id === 'view-overview') id = 'view-sessions'
|
|
3554
3574
|
if (id !== 'view-chat') conversationView?.pause()
|
|
3555
3575
|
if (state.view === 'view-chat' && id !== 'view-chat' && state.current) void archiveEmptySessionOnLeave(state.current)
|
|
3556
3576
|
state.view = id
|
|
3577
|
+
document.body?.classList.toggle('workflow-at-start', !!window.DshWorkflow?.isMounted() && id === 'view-sessions')
|
|
3557
3578
|
for (const v of ['view-overview', 'view-sessions', 'view-chat', 'view-files', 'view-plugins', 'view-settings']) $(v).classList.toggle('hidden', v !== id)
|
|
3558
3579
|
if (id === 'view-chat') conversationView?.resume()
|
|
3559
3580
|
document.querySelectorAll('.ds-nav-item').forEach(b => b.classList.toggle('active', b.dataset.view === id))
|
|
@@ -3772,7 +3793,7 @@ function bindUi() {
|
|
|
3772
3793
|
$('btn-stats-top').addEventListener('click', toggleStatsDrawer)
|
|
3773
3794
|
for (const id of ['history', 'question-body']) window.DshChatFiles?.bind($(id), () => {
|
|
3774
3795
|
const c=captureConnection(),sessionId=id==='history'?state.current:state.questionModal?.sessionId
|
|
3775
|
-
return { ...c,sessionId,cwd:sessionCwd(state.byId.get(sessionId)),native:false,headers:{authorization:'Bearer '+c.token,...clientIdHeaders()},notice:toast,
|
|
3796
|
+
return { ...c,sessionId,cwd:sessionCwd(state.byId.get(sessionId)),native:false,headers:{authorization:'Bearer '+c.token,...clientIdHeaders()},notice:toast,preview:(path,name)=>window.DshWorkflow?.preview({...c,headers:{authorization:'Bearer '+c.token}},path,name),
|
|
3776
3797
|
valid:()=>c.valid()&&sessionId===(id==='history'?state.current:state.questionModal?.sessionId) }
|
|
3777
3798
|
})
|
|
3778
3799
|
$('btn-insights').addEventListener('click', () => openInsights())
|
|
@@ -3915,7 +3936,7 @@ async function start() {
|
|
|
3915
3936
|
}
|
|
3916
3937
|
loadServers()
|
|
3917
3938
|
renderServers()
|
|
3918
|
-
showView('view-overview')
|
|
3939
|
+
showView(window.DshWorkflow?.isMounted() ? 'view-sessions' : 'view-overview')
|
|
3919
3940
|
if (urlToken) {
|
|
3920
3941
|
state.token = urlToken
|
|
3921
3942
|
const currentId = state.groupActive[state.activeGroup]
|
|
@@ -3942,3 +3963,42 @@ async function start() {
|
|
|
3942
3963
|
}
|
|
3943
3964
|
|
|
3944
3965
|
start()
|
|
3966
|
+
mountWorkflowDesktop()
|
|
3967
|
+
|
|
3968
|
+
function mountWorkflowDesktop() {
|
|
3969
|
+
window.DshWorkflow?.mount({
|
|
3970
|
+
desktop:true, start:()=>{if(state.view==='view-overview')showView('view-sessions')},
|
|
3971
|
+
snapshot:()=>({token:!!state.token,host:currentServerEntry()?.note || state.server || location.host,
|
|
3972
|
+
gateway:activeGatewayHealth()?.ok || !!state.streamsOk?.mux,dsh:dshReachable(),
|
|
3973
|
+
mux:!!state.streamsOk?.mux,hostEvents:!!state.streamsOk?.host,pending:state.approvals.length+state.questions.length,
|
|
3974
|
+
busy:!!state.byId.get(state.current)?.running,sending:sendMessage.pending?.has(state.history)}),
|
|
3975
|
+
settings:name=>{showView('view-settings');showSettingsPage(name)},plugins:()=>showView('view-plugins'),
|
|
3976
|
+
feedback:openFeedbackModal,
|
|
3977
|
+
browse:()=>{closeNewSessionModal();showView('view-files')},
|
|
3978
|
+
register:async()=>{
|
|
3979
|
+
const connection=captureConnection(),path=state.fs.path;if(!path)return toast('请先选择主机目录','err')
|
|
3980
|
+
try{const value=await rpc('workspace.create',{path});if(!connection.valid()||!value?.workspace)return
|
|
3981
|
+
state.workspaces=[...state.workspaces.filter(w=>w.workspaceId!==value.workspace.workspaceId),value.workspace]
|
|
3982
|
+
closeWorkspaceModal();renderNewSessionWorkspace(value.workspace.workspaceId);await createSessionInWorkspace()
|
|
3983
|
+
}catch(error){if(connection.valid())toast(error.message,'err')}
|
|
3984
|
+
},
|
|
3985
|
+
command:runSlashCommand,send:sendMessage,refresh:refreshSessions,retry:()=>{startOverviewDetection(true);void refreshSessions()},
|
|
3986
|
+
operations:()=>{const connection=captureConnection();return {url:apiUrl,headers:{authorization:'Bearer '+connection.token},valid:connection.valid}},
|
|
3987
|
+
discover:()=>{if(confirm('登记当前绑定目录下的子目录为工作区?'))void refreshWorkbench({discover:true})},
|
|
3988
|
+
files:()=>{const cwd=sessionCwd(state.byId.get(state.current));if(!cwd)return toast('当前会话没有工作目录','err');state.fs.loaded=true;showView('view-files');void loadFs(cwd,true)},
|
|
3989
|
+
admin:()=>window.open(new URL(apiUrl('/admin/'),location.href).href,'_blank','noopener,noreferrer'),
|
|
3990
|
+
clear:async kind=>{
|
|
3991
|
+
const text=kind==='history'?'清除本机历史缓存?主机记录保留。':kind==='connection'?'移除当前地址和保存的凭证?其他连接条目保留。':'清除本机全部 Remote 配置与凭证?主机数据保留。'
|
|
3992
|
+
if(!confirm(text))return
|
|
3993
|
+
clearTimeout(scheduleHistoryCacheSave._t)
|
|
3994
|
+
if(kind==='connection'){
|
|
3995
|
+
const current=currentServerEntry();if(current)state.servers=state.servers.filter(s=>s.id!==current.id)
|
|
3996
|
+
state.groupActive[state.activeGroup]='';state.token='';state.server='';LS.del('token');LS.del('server');saveServers()
|
|
3997
|
+
closeStream('mux');closeStream('host');stopPolling();renderServers();showView('view-settings');showSettingsPage('servers');return
|
|
3998
|
+
}
|
|
3999
|
+
await window.DshHistory.cacheClear()
|
|
4000
|
+
if(kind==='all'){window.DshWorkflow.clearStorage();location.reload()}else toast('历史缓存已清除','ok')
|
|
4001
|
+
},
|
|
4002
|
+
recover:(row,receipt)=>{const value=receipt.result?.result?.value;if(row.method==='session.create'&&value?.sessionId)void openSession(value.sessionId);if(row.sessionId===state.current)void resyncCurrentSession()},
|
|
4003
|
+
})
|
|
4004
|
+
}
|
package/public/index.html
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
<meta name="mobile-web-app-capable" content="yes">
|
|
8
8
|
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
|
|
9
9
|
<title>DSH Remote</title>
|
|
10
|
-
<script>/* 统一入口: 桌面浏览器(宽屏且 UA 非移动)访问根地址自动切换到桌面端, 手机/窄窗口继续 App 界面 */ (function(){try{var proto=location.protocol;var ua=navigator.userAgent||'';var mobile=/Android|iPhone|iPad|iPod|Mobile|Windows Phone/i.test(ua);if((proto==='http:'||proto==='https:')&&!mobile&&window.innerWidth>=1024){var p=location.pathname;if(p==='/'||/\/index\.html$/.test(p)){location.replace('desktop/desktop.html'+location.search)}}}catch(e){}})()</script>
|
|
10
|
+
<script>/* 统一入口: 桌面浏览器(宽屏且 UA 非移动)访问根地址自动切换到桌面端, 手机/窄窗口继续 App 界面 */ (function(){try{if(new URLSearchParams(location.search).get('layout')==='mobile'){sessionStorage.setItem('dshRemoteLayout','mobile');return}if(sessionStorage.getItem('dshRemoteLayout')==='mobile')return;var proto=location.protocol;var ua=navigator.userAgent||'';var mobile=/Android|iPhone|iPad|iPod|Mobile|Windows Phone/i.test(ua);if((proto==='http:'||proto==='https:')&&!mobile&&window.innerWidth>=1024){var p=location.pathname;if(p==='/'||/\/index\.html$/.test(p)){location.replace('desktop/desktop.html'+location.search)}}}catch(e){}})()</script>
|
|
11
11
|
<script>/* 首帧前应用皮肤, 避免闪白/闪黑 */ (function(){try{var t=localStorage.getItem('dshTheme');if(t!=='default'&&t!=='dark'&&t!=='light'&&t!=='neutral'&&t!=='mono'){t=window.matchMedia('(prefers-color-scheme: light)').matches?'light':'default'}document.documentElement.setAttribute('data-theme',t)}catch(e){}})()</script>
|
|
12
12
|
<link rel="manifest" href="manifest.webmanifest">
|
|
13
13
|
<link rel="icon" href="icon.svg" type="image/svg+xml">
|
|
@@ -17,6 +17,8 @@
|
|
|
17
17
|
<link rel="stylesheet" href="skills.css">
|
|
18
18
|
<link rel="stylesheet" href="extensions.css">
|
|
19
19
|
<link rel="stylesheet" href="insights.css">
|
|
20
|
+
<link rel="stylesheet" href="workflow.css">
|
|
21
|
+
<link rel="stylesheet" href="relay-settings.css">
|
|
20
22
|
</head>
|
|
21
23
|
<body>
|
|
22
24
|
<header class="topbar">
|
|
@@ -391,6 +393,7 @@
|
|
|
391
393
|
</div>
|
|
392
394
|
|
|
393
395
|
<div id="settings-page-servers" class="settings-subpage hidden" data-motion-panel>
|
|
396
|
+
<div id="relay-settings"></div>
|
|
394
397
|
<div class="settings-group">
|
|
395
398
|
<div class="setting-row" data-settings-back style="cursor:pointer">
|
|
396
399
|
<button class="mini-btn" data-i18n="settings.back">‹ 返回</button>
|
|
@@ -1415,6 +1418,9 @@
|
|
|
1415
1418
|
<script src="history.js"></script>
|
|
1416
1419
|
<script src="link-check.js"></script>
|
|
1417
1420
|
<script src="network.js"></script>
|
|
1421
|
+
<script src="operations.js"></script>
|
|
1422
|
+
<script src="workflow.js"></script>
|
|
1423
|
+
<script src="relay-settings.js"></script>
|
|
1418
1424
|
<script src="app.js"></script>
|
|
1419
1425
|
</body>
|
|
1420
1426
|
</html>
|
package/public/motion.js
CHANGED
|
@@ -48,7 +48,7 @@
|
|
|
48
48
|
const targets = children.length ? children : [view]
|
|
49
49
|
gsap.killTweensOf([view, ...targets])
|
|
50
50
|
gsap.set(view, { autoAlpha: 1, clearProps: 'transform' })
|
|
51
|
-
if (reduced) {
|
|
51
|
+
if (reduced || document.body?.classList?.contains('workflow-v8')) {
|
|
52
52
|
clear([view, ...targets])
|
|
53
53
|
return
|
|
54
54
|
}
|
|
@@ -74,7 +74,7 @@
|
|
|
74
74
|
if (container.dataset.motionListSignature === signature) return
|
|
75
75
|
container.dataset.motionListSignature = signature
|
|
76
76
|
gsap.killTweensOf(items)
|
|
77
|
-
if (reduced) {
|
|
77
|
+
if (reduced || document.body?.classList?.contains('workflow-v8')) {
|
|
78
78
|
clear(items)
|
|
79
79
|
return
|
|
80
80
|
}
|
|
@@ -97,7 +97,7 @@
|
|
|
97
97
|
gsap.killTweensOf(existing)
|
|
98
98
|
render()
|
|
99
99
|
const next = [...container.querySelectorAll(selector)]
|
|
100
|
-
if (reduced) {
|
|
100
|
+
if (reduced || document.body?.classList?.contains('workflow-v8')) {
|
|
101
101
|
clear(next)
|
|
102
102
|
return true
|
|
103
103
|
}
|
package/public/network.js
CHANGED
|
@@ -2,6 +2,12 @@
|
|
|
2
2
|
'use strict';
|
|
3
3
|
;(function(root){
|
|
4
4
|
let measuredLatency=0
|
|
5
|
+
const sharedReads=new Map()
|
|
6
|
+
function shareRead(key,read){
|
|
7
|
+
if(sharedReads.has(key))return sharedReads.get(key)
|
|
8
|
+
const job=Promise.resolve().then(read).finally(()=>{if(sharedReads.get(key)===job)sharedReads.delete(key)})
|
|
9
|
+
sharedReads.set(key,job);return job
|
|
10
|
+
}
|
|
5
11
|
function mode(){try{return ['auto','weak','normal'].includes(root.localStorage.getItem('dshNetworkModeV1'))?root.localStorage.getItem('dshNetworkModeV1'):'auto'}catch{return 'auto'}}
|
|
6
12
|
function profile(){
|
|
7
13
|
const selected=mode(),connection=root.navigator?.connection
|
|
@@ -50,7 +56,7 @@
|
|
|
50
56
|
row.querySelector('[data-network-detail]').textContent=english?'Weak mode loads fewer history entries and allows longer read waits. Sending is never retried automatically.':'弱网模式减少每页历史条数、延长读取等待;发送操作不会自动重试。'
|
|
51
57
|
const select=row.querySelector('select');select.setAttribute('aria-label',english?'Network mode':'网络模式');['auto','weak','normal'].forEach((v,i)=>select.options[i].textContent=(english?['Automatic','Weak network','Standard']:['自动判断','弱网优先','标准模式'])[i]);select.value=mode();root.enhanceCustomSelect?.(select);root.syncCustomSelect?.(select)
|
|
52
58
|
}
|
|
53
|
-
const api={profile,setMode,PollLoop,observeLatency:ms=>{if(Number.isFinite(ms))measuredLatency=ms},preferences}
|
|
59
|
+
const api={profile,setMode,PollLoop,shareRead,observeLatency:ms=>{if(Number.isFinite(ms))measuredLatency=ms},preferences}
|
|
54
60
|
if(typeof module!=='undefined'&&module.exports)module.exports=api
|
|
55
61
|
else{root.DshNetwork=api;root.document.addEventListener('DOMContentLoaded',()=>{preferences();new MutationObserver(preferences).observe(root.document.documentElement,{attributes:true,attributeFilter:['lang']})})}
|
|
56
62
|
})(typeof window==='undefined'?globalThis:window)
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/* Durable write receipts. POST once, recover using GET only; zero dependencies. */
|
|
2
|
+
;(function(root) {
|
|
3
|
+
'use strict'
|
|
4
|
+
const methods = new Set(['session.create','session.prompt','session.updateQueue','session.selectModel',
|
|
5
|
+
'session.rename','session.cancel','workspace.create','workspace.archiveSession',
|
|
6
|
+
'goal.edit','goal.pause','goal.resume','goal.complete','goal.clear'])
|
|
7
|
+
const pending = new Map()
|
|
8
|
+
const storageKey = 'dshRemoteOperationReceiptsV1'
|
|
9
|
+
function saved() { try { return JSON.parse(root.localStorage?.getItem(storageKey) || '[]').filter(row => Date.now()-row.createdAt<86400000).slice(-100) } catch { return [] } }
|
|
10
|
+
function persist() {
|
|
11
|
+
const rows=new Map(saved().map(row=>[row.id,row]))
|
|
12
|
+
for(const row of pending.values())rows.set(row.id,{id:row.id,scope:row.scope,intent:row.intent,method:row.method,sessionId:row.sessionId,createdAt:row.createdAt})
|
|
13
|
+
try { root.localStorage?.setItem(storageKey,JSON.stringify([...rows.values()].slice(-100))) } catch {}
|
|
14
|
+
root.dispatchEvent?.(new Event('dsh-operation-change'))
|
|
15
|
+
}
|
|
16
|
+
function forget(id) {
|
|
17
|
+
pending.delete(id)
|
|
18
|
+
try { root.localStorage?.setItem(storageKey,JSON.stringify(saved().filter(row=>row.id!==id))) } catch {}
|
|
19
|
+
root.dispatchEvent?.(new Event('dsh-operation-change'))
|
|
20
|
+
}
|
|
21
|
+
async function digest(value) {
|
|
22
|
+
const input=new TextEncoder().encode(value)
|
|
23
|
+
if(root.crypto?.subtle) {
|
|
24
|
+
const bytes=await root.crypto.subtle.digest('SHA-256',input)
|
|
25
|
+
return [...new Uint8Array(bytes)].map(n=>n.toString(16).padStart(2,'0')).join('')
|
|
26
|
+
}
|
|
27
|
+
// LAN HTTP does not expose SubtleCrypto. Reuse the existing upload hasher.
|
|
28
|
+
if(typeof root.SHA256==='function')return new root.SHA256().update(input).hex()
|
|
29
|
+
throw new Error('SHA-256 unavailable')
|
|
30
|
+
}
|
|
31
|
+
function newId() {
|
|
32
|
+
if(root.crypto.randomUUID)return root.crypto.randomUUID()
|
|
33
|
+
return [...root.crypto.getRandomValues(new Uint8Array(16))].map(n=>n.toString(16).padStart(2,'0')).join('')
|
|
34
|
+
}
|
|
35
|
+
async function restore(config) {
|
|
36
|
+
const scope=await digest(config.url('/api/operations')+'\0'+config.headers.authorization)
|
|
37
|
+
if(!config.valid())return scope
|
|
38
|
+
for(const row of saved())if(row.scope===scope&&!pending.has(row.id))pending.set(row.id,{...row,phase:'unknown',config})
|
|
39
|
+
for(const row of pending.values())if(row.scope===scope)row.config=config
|
|
40
|
+
return scope
|
|
41
|
+
}
|
|
42
|
+
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))
|
|
43
|
+
function unknown(id) {
|
|
44
|
+
const error = new Error((root.I18N?.lang === 'en' ? 'Result unconfirmed. Check the conversation before sending again. Operation: ' : '结果未确认,请核对会话后再决定是否重发。操作编号:') + id)
|
|
45
|
+
error.operationId = id; error.operationPending = true
|
|
46
|
+
return error
|
|
47
|
+
}
|
|
48
|
+
async function execute(config) {
|
|
49
|
+
const scope=await restore(config),intent=await digest(JSON.stringify([config.method,config.payload]))
|
|
50
|
+
if(!config.valid())throw unknown('connection-changed')
|
|
51
|
+
const existing=[...pending.values()].find(row=>row.scope===scope&&row.intent===intent)
|
|
52
|
+
const id = existing?.id || newId(), createdAt = Date.now()
|
|
53
|
+
const entry = existing || { id, scope, intent, method: config.method, sessionId: config.payload.sessionId || '', createdAt, phase: 'running', config }
|
|
54
|
+
pending.set(id, entry)
|
|
55
|
+
persist()
|
|
56
|
+
const statusUrl = config.url('/api/operations?id=' + encodeURIComponent(id))
|
|
57
|
+
const request = async (method, body) => {
|
|
58
|
+
const response = await root.fetch(statusUrl, { method, headers: config.headers,
|
|
59
|
+
...(body ? { body: JSON.stringify(body) } : {}), signal: AbortSignal.timeout(15000) })
|
|
60
|
+
if (!config.valid()) throw unknown(id)
|
|
61
|
+
if (response.status === 401) throw Error('AUTH')
|
|
62
|
+
const value = await response.json()
|
|
63
|
+
if (!config.valid()) throw unknown(id)
|
|
64
|
+
if (response.status >= 400) {
|
|
65
|
+
if (response.status >= 500) throw unknown(id)
|
|
66
|
+
if (method === 'GET' && response.status === 404) throw unknown(id)
|
|
67
|
+
const error = new Error(value.error || ('HTTP ' + response.status)); error.rpcRejected = true; throw error
|
|
68
|
+
}
|
|
69
|
+
return value
|
|
70
|
+
}
|
|
71
|
+
let status
|
|
72
|
+
try {
|
|
73
|
+
try { status = existing ? await request('GET') : await request('POST', { method: config.method, payload: config.payload }) }
|
|
74
|
+
catch (error) { if (error.message === 'AUTH' || error.rpcRejected || !config.valid()) throw error }
|
|
75
|
+
for (let attempt = 0; config.valid() && Date.now() - createdAt < 90000; attempt++) {
|
|
76
|
+
if (status?.phase === 'complete' || status?.phase === 'rejected') {
|
|
77
|
+
entry.phase = status.phase; forget(id)
|
|
78
|
+
return status.result
|
|
79
|
+
}
|
|
80
|
+
if (status?.phase === 'unknown') { entry.phase = 'unknown'; throw unknown(id) }
|
|
81
|
+
await sleep(Math.min(3000, 400 + attempt * 250))
|
|
82
|
+
try { status = await request('GET') }
|
|
83
|
+
catch (error) { if (error.message === 'AUTH' || error.rpcRejected) throw error }
|
|
84
|
+
}
|
|
85
|
+
throw unknown(id)
|
|
86
|
+
} catch (error) {
|
|
87
|
+
if (error.rpcRejected || error.message === 'AUTH') forget(id)
|
|
88
|
+
else entry.phase = 'unknown'
|
|
89
|
+
persist()
|
|
90
|
+
throw error
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
async function check(id) {
|
|
94
|
+
const entry = pending.get(id)
|
|
95
|
+
if (!entry || !entry.config.valid()) return null
|
|
96
|
+
const response = await root.fetch(entry.config.url('/api/operations?id=' + encodeURIComponent(id)), {
|
|
97
|
+
headers: entry.config.headers, signal: AbortSignal.timeout(15000) })
|
|
98
|
+
if (!entry.config.valid()) return null
|
|
99
|
+
const value = await response.json()
|
|
100
|
+
if (!entry.config.valid()) return null
|
|
101
|
+
if (response.ok) { entry.phase = value.phase; if (['complete','rejected'].includes(value.phase)) forget(id) }
|
|
102
|
+
return response.ok ? value : null
|
|
103
|
+
}
|
|
104
|
+
const api = { supports: method => methods.has(method), execute, check, restore,
|
|
105
|
+
dismiss: id => { const row=pending.get(id);if(!row||row.phase!=='unknown'||!row.config.valid())return false;forget(id);return true },
|
|
106
|
+
pending: () => [...pending.values()].filter(row => row.config.valid()).map(({id,method,sessionId,createdAt,phase}) => ({id,method,sessionId,createdAt,phase})) }
|
|
107
|
+
root.DshOperations = api
|
|
108
|
+
if (typeof module !== 'undefined') module.exports = api
|
|
109
|
+
})(typeof window === 'undefined' ? globalThis : window)
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
.relay-settings{margin:18px 0;padding:20px;border:1px solid var(--dsr-line,var(--border,#ffffff20));border-radius:16px;background:var(--dsr-panel,var(--bg-card,transparent));color:inherit;min-width:0}
|
|
2
|
+
.relay-settings [hidden]{display:none!important}.relay-heading,.relay-address,.relay-actions{display:flex;align-items:center;gap:12px;flex-wrap:wrap}.relay-heading{justify-content:space-between}.relay-heading h3{font-size:16px;line-height:1.4;margin:0}.relay-badge{font-size:12px;padding:5px 9px;border-radius:20px;background:#77889920}.relay-badge[data-phase=online]{background:#36b48522;color:var(--success,#35b58a)}.relay-badge[data-phase=quota-exceeded],.relay-badge[data-phase=error]{background:#da704522;color:var(--warning,#d98758)}.relay-muted{font-size:12px;line-height:1.65;opacity:.7;margin:10px 0}.relay-status,.relay-notice,.relay-quota p{font-size:13px;line-height:1.6}.relay-address{padding:12px 0}.relay-address a{color:var(--dsr-accent,var(--accent,#6ea9e8));overflow-wrap:anywhere;flex:1;min-width:120px}.relay-form{display:grid;gap:12px;padding:12px 0}.relay-form label{display:grid;gap:7px;font-size:13px}.relay-form input{width:100%;box-sizing:border-box;min-height:44px;border:1px solid var(--dsr-line,var(--border,#ffffff25));background:transparent;color:inherit;border-radius:9px;padding:10px 12px;font:inherit}.relay-settings button{min-height:44px;border:1px solid var(--dsr-line,var(--border,#ffffff25));border-radius:9px;padding:9px 14px;font:inherit;font-size:13px;cursor:pointer;background:transparent;color:inherit}.relay-settings .relay-primary{background:var(--dsr-accent,var(--accent,#527dab));color:var(--dsr-bg,#fff);justify-self:start;border-color:transparent}.relay-settings button:disabled{opacity:.5;cursor:default}.relay-settings :focus-visible{outline:2px solid var(--dsr-accent,var(--accent,#6ea9e8));outline-offset:3px}.relay-quota progress{display:block;width:100%;height:7px;accent-color:var(--dsr-accent,var(--accent,#6ea9e8))}.relay-notice:empty{display:none}.relay-notice{padding:10px 12px;border-radius:9px;background:#71839c16}.relay-actions{margin-top:6px}@media(max-width:480px){.relay-settings{padding:16px}.relay-heading{align-items:flex-start}.relay-address{align-items:flex-start}.relay-form .relay-primary{width:100%;justify-self:stretch}}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
/* Shared settings for the host-owned relay; no credentials enter browser storage. */
|
|
2
|
+
;(function(root) {
|
|
3
|
+
'use strict'
|
|
4
|
+
const text = (zh, en) => root.I18N?.lang === 'en' ? en : zh
|
|
5
|
+
const el = (tag, cls, value) => { const node=document.createElement(tag);if(cls)node.className=cls;if(value)node.textContent=value;return node }
|
|
6
|
+
const messages = {
|
|
7
|
+
INVALID_AUTHORIZATION:['中转密钥无效或已到期,请核对运营者发给你的密钥。','The relay key is invalid or expired.'],
|
|
8
|
+
HOST_ALREADY_BOUND:['此密钥已绑定其他主机,请申请新的密钥。','This key is already bound to another host.'],
|
|
9
|
+
RELAY_ADMIN_REQUIRED:['开通或停用需要此主机的管理令牌。','The host admin token is required.'],
|
|
10
|
+
ENROLLMENT_CONNECTION_FAILED:['暂时无法连接中转服务器,密钥未保存到浏览器。','The relay server is unreachable. The key was not saved in the browser.'],
|
|
11
|
+
GATEWAY_UNAVAILABLE:['请先在主机上启动 Remote 网关。','Start the Remote gateway on the host first.'],
|
|
12
|
+
RELAY_OPERATION_BUSY:['主机正在处理上一次操作,请稍后刷新状态。','The previous operation is still running. Refresh shortly.'],
|
|
13
|
+
unauthorized:['请先连接主机,再设置云服务器中转。','Connect to your host before configuring its relay.'],
|
|
14
|
+
}
|
|
15
|
+
function mount(target, { connection, path = '/relay', credentials } = {}) {
|
|
16
|
+
if (!target || target.dataset.relayMounted) return
|
|
17
|
+
target.dataset.relayMounted='true';target.classList.add('relay-settings')
|
|
18
|
+
const heading=el('div','relay-heading'),title=el('h3'),badge=el('span','relay-badge')
|
|
19
|
+
heading.append(title,badge)
|
|
20
|
+
const intro=el('p','relay-muted'),status=el('p','relay-status');status.setAttribute('aria-live','polite')
|
|
21
|
+
const address=el('div','relay-address'),link=el('a'),copy=el('button');copy.type='button';link.target='_blank';link.rel='noopener noreferrer';address.append(link,copy)
|
|
22
|
+
const quota=el('div','relay-quota'),meter=el('progress'),usage=el('p'),reset=el('p','relay-muted');meter.max=100;quota.append(usage,meter,reset)
|
|
23
|
+
const binding=el('p','relay-muted'),form=el('form','relay-form'),keyLabel=el('label'),keyInput=el('input')
|
|
24
|
+
keyInput.type='password';keyInput.autocomplete='off';keyInput.spellcheck=false;keyInput.maxLength=128;keyInput.name='relay-key'
|
|
25
|
+
keyLabel.append(el('span'),keyInput)
|
|
26
|
+
const adminLabel=el('label'),adminInput=el('input');adminInput.type='password';adminInput.autocomplete='off';adminInput.name='relay-admin';adminLabel.append(el('span'),adminInput)
|
|
27
|
+
const submit=el('button','relay-primary');submit.type='submit';form.append(keyLabel,adminLabel,submit)
|
|
28
|
+
const actions=el('div','relay-actions'),toggle=el('button'),refresh=el('button'),takeover=el('button');toggle.type=refresh.type=takeover.type='button';actions.append(takeover,toggle,refresh)
|
|
29
|
+
const hint=el('p','relay-muted'),notice=el('p','relay-notice');notice.setAttribute('role','status')
|
|
30
|
+
target.append(heading,intro,status,address,quota,binding,form,actions,hint,notice)
|
|
31
|
+
let identity='',value=null,lastRead=0,busy=false,loading=false,controller=null,destroyed=false
|
|
32
|
+
function context() { const ctx=connection();return { ...ctx, endpoint:ctx.url(path) } }
|
|
33
|
+
function current(ctx) { return !destroyed && ctx.valid() && identity===JSON.stringify([ctx.endpoint,ctx.headers?.authorization||'']) }
|
|
34
|
+
function syncIdentity() {
|
|
35
|
+
const ctx=context(),next=JSON.stringify([ctx.endpoint,ctx.headers?.authorization||''])
|
|
36
|
+
if(next!==identity){identity=next;controller?.abort();controller=null;keyInput.value='';adminInput.value='';value=null;notice.textContent='';lastRead=0;loading=false;busy=false;render()}
|
|
37
|
+
return ctx
|
|
38
|
+
}
|
|
39
|
+
function render() {
|
|
40
|
+
title.textContent=text('云服务器中转','Cloud relay')
|
|
41
|
+
intro.textContent=text('让手机通过公网连接这台主机。每位用户使用自己的中转密钥,首次开通会绑定此主机。','Connect to this host over the internet. Your personal relay key binds to this host when activated.')
|
|
42
|
+
const phase=value?.phase||'unconfigured'
|
|
43
|
+
const names={unconfigured:['尚未开通','Not configured'],disabled:['已停用','Disabled'],connecting:['正在连接','Connecting'],online:['已连接','Connected'],reconnecting:['正在重连','Reconnecting'],expired:['授权已到期','Expired'],'authorization-inactive':['授权已撤销或到期','Authorization inactive'],'quota-exceeded':['今日流量已用完','Daily quota reached'],'quota-unavailable':['流量服务暂不可用','Quota service unavailable'],error:['连接异常','Connection error']}
|
|
44
|
+
badge.textContent=text(...(names[phase]||names.error));badge.dataset.phase=phase
|
|
45
|
+
status.textContent=busy?text('正在保存并绑定,请稍候…','Saving and binding…'):value?.error?text('请检查主机配置或刷新状态。','Check the host configuration or refresh.'):text('开通后会随 Remote 网关启动,无需单独运行工具。','Starts with the Remote gateway after activation.')
|
|
46
|
+
let safeUrl=''
|
|
47
|
+
try { const url=new URL(value?.publicUrl);if(url.protocol==='https:'&&!url.username&&!url.password)safeUrl=url.origin } catch {}
|
|
48
|
+
address.hidden=!safeUrl;link.textContent=safeUrl;link.href=safeUrl||'#';copy.textContent=text('复制地址','Copy URL')
|
|
49
|
+
const daily=value?.daily
|
|
50
|
+
quota.hidden=!daily
|
|
51
|
+
if(daily?.unavailable){usage.textContent=text('无法确认今日额度,云端暂停传输。','Quota unavailable; cloud transfer is paused.');meter.hidden=true;reset.textContent=''}
|
|
52
|
+
else if(daily){
|
|
53
|
+
meter.hidden=false;meter.value=Math.min(100,Math.max(0,Number(daily.usedBytes)/Number(daily.limitBytes)*100))
|
|
54
|
+
const gb=bytes=>(Math.max(0,Number(bytes)||0)/1e9).toFixed(2)
|
|
55
|
+
usage.textContent=text(`今日已用 ${gb(daily.usedBytes)} / ${gb(daily.limitBytes)} GB · 剩余 ${gb(daily.remainingBytes)} GB`,`Today ${gb(daily.usedBytes)} / ${gb(daily.limitBytes)} GB · ${gb(daily.remainingBytes)} GB left`)
|
|
56
|
+
reset.textContent=text('上传与下载合计;北京时间每天 00:00 重置。','Uploads + downloads; resets daily at 00:00 Beijing time.')
|
|
57
|
+
}
|
|
58
|
+
const expires=value?.expiresAt?new Date(value.expiresAt).toLocaleString():''
|
|
59
|
+
binding.textContent=value?.fingerprint?text(`已绑定此主机 · ${value.fingerprint.slice(0,12)}${expires?' · 有效期至 '+expires:''}`,`Bound to this host · ${value.fingerprint.slice(0,12)}${expires?' · Until '+expires:''}`):''
|
|
60
|
+
keyLabel.firstChild.textContent=text(value?.configured?'更换个人中转密钥':'个人中转密钥',value?.configured?'Replace personal relay key':'Personal relay key')
|
|
61
|
+
keyInput.placeholder='dsrp_…';keyInput.setAttribute('aria-label',keyLabel.firstChild.textContent)
|
|
62
|
+
adminLabel.hidden=value?.canManage!==false
|
|
63
|
+
adminLabel.firstChild.textContent=text('主机管理令牌(仅本次操作)','Host admin token (this operation only)')
|
|
64
|
+
adminInput.setAttribute('aria-label',adminLabel.firstChild.textContent)
|
|
65
|
+
submit.textContent=busy?text('正在处理…','Working…'):text(value?.configured?'绑定新密钥':'绑定并开启',value?.configured?'Bind new key':'Bind and enable')
|
|
66
|
+
submit.disabled=busy||!value;keyInput.disabled=busy;adminInput.disabled=busy
|
|
67
|
+
toggle.hidden=!value?.configured;toggle.disabled=busy;toggle.textContent=text(value?.enabled?'停用中转':'开启中转',value?.enabled?'Disable relay':'Enable relay')
|
|
68
|
+
refresh.textContent=text('刷新状态','Refresh');refresh.disabled=busy||loading
|
|
69
|
+
takeover.hidden=!value?.legacyAvailable;takeover.disabled=busy;takeover.textContent=text('接管已有试用连接','Take over existing trial')
|
|
70
|
+
hint.textContent=value?.quotaPending?text('等待云端确认今日额度…','Waiting for cloud quota…'):text('手机使用此公网地址和原 Remote 访问令牌。停用会断开通过此入口的连接;授权到期或用满后,请通过本地地址管理。','Use this URL and your existing Remote access token. Disabling disconnects this route; use a local address after expiry or quota exhaustion.')
|
|
71
|
+
}
|
|
72
|
+
async function load(force=false) {
|
|
73
|
+
const ctx=syncIdentity()
|
|
74
|
+
if(busy||loading||!force&&(document.hidden||!target.getClientRects().length||Date.now()-lastRead<5000))return
|
|
75
|
+
loading=true;lastRead=Date.now();const abort=new AbortController();controller=abort;const timer=setTimeout(()=>abort.abort(),10000)
|
|
76
|
+
render()
|
|
77
|
+
try {
|
|
78
|
+
const response=await root.fetch(ctx.endpoint,{headers:ctx.headers,credentials,cache:'no-store',signal:abort.signal})
|
|
79
|
+
const data=await response.json()
|
|
80
|
+
if(!current(ctx))return
|
|
81
|
+
if(response.status===429&&data.daily){value={phase:'quota-exceeded',daily:data.daily,configured:false};notice.textContent=text('今日额度已用完。请用主机本地地址进入设置,或等待零点恢复。','Daily quota reached. Use the local host address or wait until reset.');return}
|
|
82
|
+
if(!response.ok)throw Object.assign(Error(data.error||'HTTP_'+response.status),{code:data.error,status:response.status})
|
|
83
|
+
if(data.supported!==true)throw Error('UNSUPPORTED_GATEWAY')
|
|
84
|
+
value=data;notice.textContent=''
|
|
85
|
+
}catch(error){
|
|
86
|
+
if(current(ctx)&&!busy&&controller===abort)notice.textContent=error.status===404?text('请将此主机 Remote 升级到 0.8.0-rc.2 后使用。','Upgrade this host Remote to 0.8.0-rc.2.'):messages[error.code]?text(...messages[error.code]):text('暂时无法读取中转状态,可稍后刷新。','Unable to read relay status. Refresh shortly.')
|
|
87
|
+
}finally{clearTimeout(timer);if(current(ctx)&&controller===abort){loading=false;render()}}
|
|
88
|
+
}
|
|
89
|
+
async function change(action) {
|
|
90
|
+
const ctx=syncIdentity();if(busy)return
|
|
91
|
+
const key=keyInput.value.trim(),admin=adminInput.value.trim()
|
|
92
|
+
if(action==='enroll'&&!/^dsrp_[a-f0-9]{16}\.[A-Za-z0-9_-]{43}$/.test(key)){notice.textContent=text('请填写完整的个人中转密钥。','Enter the complete personal relay key.');return}
|
|
93
|
+
busy=true;controller?.abort();loading=false;notice.textContent='';render()
|
|
94
|
+
const abort=new AbortController();controller=abort;const timer=setTimeout(()=>abort.abort(),20000)
|
|
95
|
+
// Clear immediately, including ambiguous network outcomes. Never store the key.
|
|
96
|
+
keyInput.value='';adminInput.value=''
|
|
97
|
+
try {
|
|
98
|
+
const response=await root.fetch(ctx.endpoint,{method:'POST',headers:{...ctx.headers,...(admin?{authorization:'Bearer '+admin}:{}),'content-type':'application/json'},credentials,body:JSON.stringify({action,...(action==='enroll'?{key}:{})}),signal:abort.signal})
|
|
99
|
+
const data=await response.json();if(!current(ctx))return
|
|
100
|
+
if(!response.ok)throw Object.assign(Error(data.error),{code:data.error})
|
|
101
|
+
value=data;notice.textContent=text(action==='disable'?'中转已停用。':'设置已保存,正在确认云端连接。',action==='disable'?'Relay disabled.':'Saved. Confirming the cloud connection.')
|
|
102
|
+
}catch(error){if(current(ctx))notice.textContent=messages[error.code]?text(...messages[error.code]):text('暂时无法确认操作结果。请刷新状态后再决定是否重试。','Result unconfirmed. Refresh status before deciding whether to retry.')}
|
|
103
|
+
finally{clearTimeout(timer);if(current(ctx)){busy=false;lastRead=0;render()}}
|
|
104
|
+
}
|
|
105
|
+
form.addEventListener('submit',event=>{event.preventDefault();void change('enroll')})
|
|
106
|
+
toggle.addEventListener('click',()=>void change(value?.enabled?'disable':'enable'))
|
|
107
|
+
takeover.addEventListener('click',()=>void change('import'))
|
|
108
|
+
refresh.addEventListener('click',()=>void load(true))
|
|
109
|
+
copy.addEventListener('click',async()=>{
|
|
110
|
+
const ctx=syncIdentity(),url=link.href
|
|
111
|
+
try{await root.navigator.clipboard.writeText(url);if(current(ctx))notice.textContent=text('地址已复制。','URL copied.')}
|
|
112
|
+
catch{if(current(ctx))notice.textContent=text('请选中上方地址复制。','Select the URL above to copy it.')}
|
|
113
|
+
})
|
|
114
|
+
function tick(){if(destroyed)return;syncIdentity();render();void load()}
|
|
115
|
+
const timer=setInterval(tick,1000);tick()
|
|
116
|
+
return { refresh:()=>load(true),destroy:()=>{destroyed=true;clearInterval(timer);controller?.abort();keyInput.value='';adminInput.value=''} }
|
|
117
|
+
}
|
|
118
|
+
root.DshRelaySettings={mount}
|
|
119
|
+
})(typeof window!=='undefined'?window:globalThis)
|
package/public/update.json
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
{
|
|
2
|
-
"version": "0.
|
|
2
|
+
"version": "0.8.0-rc.2",
|
|
3
3
|
"apkUrl": "dsh-remote.apk",
|
|
4
|
-
"sha256": "
|
|
5
|
-
"releasedAt": "2026-10-
|
|
6
|
-
"notes": "
|
|
4
|
+
"sha256": "a9cd1211f4a8fa14f183b4d8a8cea783a399d4584277d930466ba05a8240e588",
|
|
5
|
+
"releasedAt": "2026-10-16T06:50:09.362Z",
|
|
6
|
+
"notes": "0.8.0 开发者预览 rc.2:设置页新增云服务器中转,填写个人中转密钥即可绑定主机、开启公网访问,支持查看连接状态、专属地址和每日流量。云端按用户限制每日上传与下载合计 5GB,北京时间零点重置,额度持久化并覆盖实时连接。保留 Windows Remote 自更新 EPERM 修复、三入口交互重构、待办整合与弱网操作恢复。",
|
|
7
7
|
"history": [
|
|
8
8
|
{
|
|
9
9
|
"version": "0.7.6",
|
package/public/version.json
CHANGED