dsh-app-controls 0.5.1 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +30 -18
- package/assets/dsh-tray.png +0 -0
- package/lib/client.js +332 -8
- package/lib/index.js +246 -11
- package/lib/settings.js +21 -0
- package/lib/update.js +640 -0
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +3 -2
- package/tray/dsh-tray.py +432 -39
package/lib/update.js
CHANGED
|
@@ -16,6 +16,7 @@ import { spawn } from 'node:child_process'
|
|
|
16
16
|
import fs from 'node:fs'
|
|
17
17
|
import os from 'node:os'
|
|
18
18
|
import path from 'node:path'
|
|
19
|
+
import { pathToFileURL } from 'node:url'
|
|
19
20
|
|
|
20
21
|
export const PACKAGE_NAME = '@deepseek-ai/dsh'
|
|
21
22
|
|
|
@@ -33,6 +34,15 @@ const DEFAULT_INSTALL_MS = 5 * 60 * 1000
|
|
|
33
34
|
const MIN_EXPECTED_MS = 20 * 1000
|
|
34
35
|
const MAX_EXPECTED_MS = 30 * 60 * 1000
|
|
35
36
|
const ANSI = /\u001b\[[0-9;]*m/gu
|
|
37
|
+
const LAST_GOOD_FILE = path.join(STATE_DIR, 'last-good.json')
|
|
38
|
+
const DEFAULT_RELEASE_TIMEOUT_MS = 5000
|
|
39
|
+
const MAX_RELEASE_TIMEOUT_MS = 30_000
|
|
40
|
+
const RELEASE_NOTES_LIMIT = 4000
|
|
41
|
+
const GITHUB_API = 'https://api.github.com'
|
|
42
|
+
const RELEASE_USER_AGENT = 'dsh-app-controls-update-check'
|
|
43
|
+
|
|
44
|
+
/** Public repository used when package.json carries no usable repository. */
|
|
45
|
+
export const DEFAULT_REPOSITORY = 'https://github.com/MiraculousGu/dsh-app-controls'
|
|
36
46
|
|
|
37
47
|
/**
|
|
38
48
|
* Locate the running DSH installation.
|
|
@@ -516,3 +526,633 @@ export async function updateTo(candidate, argv1 = process.argv[1], onProgress) {
|
|
|
516
526
|
if (ticker !== undefined) clearInterval(ticker)
|
|
517
527
|
}
|
|
518
528
|
}
|
|
529
|
+
|
|
530
|
+
// ---------------------------------------------------------------------------
|
|
531
|
+
// Release notes (GitHub releases / tags)
|
|
532
|
+
// ---------------------------------------------------------------------------
|
|
533
|
+
|
|
534
|
+
function cleanRepositorySlug(owner, repo) {
|
|
535
|
+
const name = repo.replace(/\.git$/iu, '')
|
|
536
|
+
const valid = (part) => /^[A-Za-z0-9_.-]+$/u.test(part) && part !== '.' && part !== '..'
|
|
537
|
+
if (!valid(owner) || !valid(name)) return null
|
|
538
|
+
return `${owner}/${name}`
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
/**
|
|
542
|
+
* Normalize a repository reference to `owner/repo` for GitHub API calls.
|
|
543
|
+
*
|
|
544
|
+
* Accepts package.json `repository` objects, `git+https://…`, `git@…:…`,
|
|
545
|
+
* `github:owner/repo` and plain `owner/repo` shorthands. Non-GitHub hosts and
|
|
546
|
+
* malformed values return `null`, so callers skip notes instead of failing.
|
|
547
|
+
*
|
|
548
|
+
* @param {string | { url?: string } | null | undefined} repository
|
|
549
|
+
* @returns {string | null} `owner/repo` or `null`.
|
|
550
|
+
*/
|
|
551
|
+
export function normalizeRepository(repository = DEFAULT_REPOSITORY) {
|
|
552
|
+
const raw = repository !== null && typeof repository === 'object' ? repository.url : repository
|
|
553
|
+
if (typeof raw !== 'string') return null
|
|
554
|
+
let value = raw.trim()
|
|
555
|
+
if (value === '') return null
|
|
556
|
+
value = value.replace(/[?#].*$/u, '').replace(/\/+$/u, '')
|
|
557
|
+
if (value.toLowerCase().startsWith('github:')) value = value.slice('github:'.length)
|
|
558
|
+
if (/^github\.com\//iu.test(value)) value = value.slice('github.com/'.length)
|
|
559
|
+
if (value.startsWith('git@github.com:')) value = value.slice('git@github.com:'.length)
|
|
560
|
+
if (/^[a-z][a-z+.-]*:\/\//iu.test(value)) {
|
|
561
|
+
let url
|
|
562
|
+
try {
|
|
563
|
+
url = new URL(value.replace(/^git\+/iu, ''))
|
|
564
|
+
} catch {
|
|
565
|
+
return null
|
|
566
|
+
}
|
|
567
|
+
const host = url.hostname.toLowerCase()
|
|
568
|
+
if (host !== 'github.com' && host !== 'www.github.com') return null
|
|
569
|
+
value = url.pathname.replace(/^\/+/u, '')
|
|
570
|
+
}
|
|
571
|
+
const parts = value.split('/').filter((part) => part !== '')
|
|
572
|
+
if (parts.length !== 2) return null
|
|
573
|
+
return cleanRepositorySlug(parts[0], parts[1])
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
/** Read `repository` (or `homepage`) from the plugin's own package.json. */
|
|
577
|
+
function packageRepository() {
|
|
578
|
+
try {
|
|
579
|
+
const data = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8'))
|
|
580
|
+
if (data !== null && typeof data === 'object') {
|
|
581
|
+
return data.repository ?? data.homepage ?? DEFAULT_REPOSITORY
|
|
582
|
+
}
|
|
583
|
+
} catch {
|
|
584
|
+
// packaged files may not ship package.json next to lib/; fall back below
|
|
585
|
+
}
|
|
586
|
+
return DEFAULT_REPOSITORY
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
function clampReleaseTimeout(value) {
|
|
590
|
+
const number = Number(value)
|
|
591
|
+
if (!Number.isFinite(number)) return DEFAULT_RELEASE_TIMEOUT_MS
|
|
592
|
+
return Math.min(MAX_RELEASE_TIMEOUT_MS, Math.max(50, Math.round(number)))
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
/** `v1.4.0` -> `1.4.0`, `null` for empty/non-string input. */
|
|
596
|
+
function normalizeTag(value) {
|
|
597
|
+
if (typeof value !== 'string') return null
|
|
598
|
+
const text = value.trim().replace(/^[vV]/u, '')
|
|
599
|
+
return text === '' ? null : text
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
function trimmed(value) {
|
|
603
|
+
return typeof value === 'string' ? value.trim() : ''
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
function safeCompare(left, right) {
|
|
607
|
+
try {
|
|
608
|
+
return compareVersions(left, right)
|
|
609
|
+
} catch {
|
|
610
|
+
return null
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
function versionOfEntry(entry) {
|
|
615
|
+
if (entry === null || typeof entry !== 'object') return null
|
|
616
|
+
return normalizeTag(entry.tag_name ?? entry.name)
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
function pickNewest(entries) {
|
|
620
|
+
let best = entries[0]
|
|
621
|
+
let bestVersion = versionOfEntry(best)
|
|
622
|
+
for (let index = 1; index < entries.length; index += 1) {
|
|
623
|
+
const entry = entries[index]
|
|
624
|
+
const version = versionOfEntry(entry)
|
|
625
|
+
if (version === null) continue
|
|
626
|
+
if (bestVersion === null || (safeCompare(version, bestVersion) ?? 0) > 0) {
|
|
627
|
+
best = entry
|
|
628
|
+
bestVersion = version
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
return best
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
function pickEntry(entries, { from, want }) {
|
|
635
|
+
if (want !== null) {
|
|
636
|
+
return entries.find((entry) => versionOfEntry(entry) === want) ?? null
|
|
637
|
+
}
|
|
638
|
+
if (from === null) return entries[0] ?? null
|
|
639
|
+
const newer = entries.filter((entry) => {
|
|
640
|
+
const version = versionOfEntry(entry)
|
|
641
|
+
return version !== null && (safeCompare(version, from) ?? 0) > 0
|
|
642
|
+
})
|
|
643
|
+
return newer.length === 0 ? null : pickNewest(newer)
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
function truncateNotes(value) {
|
|
647
|
+
const text = trimmed(value)
|
|
648
|
+
if (text.length <= RELEASE_NOTES_LIMIT) return text
|
|
649
|
+
return `${text.slice(0, RELEASE_NOTES_LIMIT - 1).trimEnd()}…`
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
function tagCandidates(version) {
|
|
653
|
+
return [version, `v${version}`]
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
function tagPageUrl(slug, name) {
|
|
657
|
+
const encoded = name.split('/').map((part) => encodeURIComponent(part)).join('/')
|
|
658
|
+
return `https://github.com/${slug}/tree/${encoded}`
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
function releaseResult(release) {
|
|
662
|
+
if (release === null || typeof release !== 'object') return null
|
|
663
|
+
const tag = typeof release.tag_name === 'string' ? release.tag_name : ''
|
|
664
|
+
const version = normalizeTag(tag) ?? normalizeTag(release.name)
|
|
665
|
+
if (version === null) return null
|
|
666
|
+
const url = typeof release.html_url === 'string' && /^https?:\/\//u.test(release.html_url)
|
|
667
|
+
? release.html_url
|
|
668
|
+
: null
|
|
669
|
+
return {
|
|
670
|
+
version,
|
|
671
|
+
title: trimmed(release.name) || tag || version,
|
|
672
|
+
notes: truncateNotes(release.body),
|
|
673
|
+
url,
|
|
674
|
+
publishedAt: trimmed(release.published_at) || trimmed(release.created_at) || null,
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
async function tagResult(tag, slug, getJson) {
|
|
679
|
+
if (tag === null || typeof tag !== 'object' || typeof tag.name !== 'string') return null
|
|
680
|
+
const version = normalizeTag(tag.name) ?? tag.name
|
|
681
|
+
let notes = ''
|
|
682
|
+
let url = tagPageUrl(slug, tag.name)
|
|
683
|
+
const commitUrl = typeof tag.commit?.url === 'string' ? tag.commit.url : null
|
|
684
|
+
if (commitUrl !== null) {
|
|
685
|
+
const commit = await getJson(commitUrl)
|
|
686
|
+
if (commit !== null && typeof commit === 'object') {
|
|
687
|
+
if (typeof commit.commit?.message === 'string') notes = commit.commit.message
|
|
688
|
+
if (typeof commit.html_url === 'string' && /^https?:\/\//u.test(commit.html_url)) url = commit.html_url
|
|
689
|
+
}
|
|
690
|
+
}
|
|
691
|
+
return {
|
|
692
|
+
version,
|
|
693
|
+
title: tag.name,
|
|
694
|
+
notes: truncateNotes(notes),
|
|
695
|
+
url,
|
|
696
|
+
publishedAt: null,
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
/**
|
|
701
|
+
* Fetch the GitHub release notes for an update.
|
|
702
|
+
*
|
|
703
|
+
* Queries releases first and falls back to tags (using the tag commit message
|
|
704
|
+
* as notes). Every network, parsing and timeout problem resolves to `null`:
|
|
705
|
+
* release notes must never block or fail an update. The whole call is bounded
|
|
706
|
+
* by `timeoutMs` (default 5 s, capped at 30 s).
|
|
707
|
+
*
|
|
708
|
+
* @param {{
|
|
709
|
+
* from?: string,
|
|
710
|
+
* to?: string,
|
|
711
|
+
* repository?: string | { url?: string } | null,
|
|
712
|
+
* timeoutMs?: number,
|
|
713
|
+
* apiBase?: string,
|
|
714
|
+
* }} [options] - `to` picks an exact release/tag; without it the newest release
|
|
715
|
+
* newer than `from` is used. `repository` defaults to this package's
|
|
716
|
+
* `repository` field, then `DEFAULT_REPOSITORY`. `apiBase` is for tests or
|
|
717
|
+
* GitHub Enterprise.
|
|
718
|
+
* @returns {Promise<{ version: string, title: string, notes: string, url: string | null, publishedAt: string | null } | null>}
|
|
719
|
+
*/
|
|
720
|
+
export async function fetchReleaseNotes(options = {}) {
|
|
721
|
+
const settings = options !== null && typeof options === 'object' ? options : {}
|
|
722
|
+
const slug = normalizeRepository(settings.repository == null ? packageRepository() : settings.repository)
|
|
723
|
+
if (slug === null) return null
|
|
724
|
+
const base = String(settings.apiBase ?? GITHUB_API).replace(/\/+$/u, '')
|
|
725
|
+
const deadline = Date.now() + clampReleaseTimeout(settings.timeoutMs)
|
|
726
|
+
const want = normalizeTag(settings.to)
|
|
727
|
+
const from = normalizeTag(settings.from)
|
|
728
|
+
const getJson = async (url) => {
|
|
729
|
+
const remaining = deadline - Date.now()
|
|
730
|
+
if (remaining <= 0) return undefined
|
|
731
|
+
try {
|
|
732
|
+
const response = await fetch(url, {
|
|
733
|
+
headers: {
|
|
734
|
+
Accept: 'application/vnd.github+json',
|
|
735
|
+
'User-Agent': RELEASE_USER_AGENT,
|
|
736
|
+
'X-GitHub-Api-Version': '2022-11-28',
|
|
737
|
+
},
|
|
738
|
+
signal: AbortSignal.timeout(remaining),
|
|
739
|
+
})
|
|
740
|
+
if (!response.ok) return undefined
|
|
741
|
+
return await response.json()
|
|
742
|
+
} catch {
|
|
743
|
+
return undefined
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
try {
|
|
747
|
+
const releases = await getJson(`${base}/repos/${slug}/releases?per_page=50`)
|
|
748
|
+
if (Array.isArray(releases)) {
|
|
749
|
+
const rows = releases.filter((release) =>
|
|
750
|
+
release !== null && typeof release === 'object' && release.draft !== true && versionOfEntry(release) !== null)
|
|
751
|
+
const picked = pickEntry(rows, { from, want })
|
|
752
|
+
if (picked !== null) {
|
|
753
|
+
const result = releaseResult(picked)
|
|
754
|
+
if (result !== null) return result
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
if (want !== null) {
|
|
758
|
+
for (const candidate of tagCandidates(want)) {
|
|
759
|
+
const release = await getJson(`${base}/repos/${slug}/releases/tags/${encodeURIComponent(candidate)}`)
|
|
760
|
+
if (release !== null && typeof release === 'object' && release.draft !== true) {
|
|
761
|
+
const result = releaseResult(release)
|
|
762
|
+
if (result !== null) return result
|
|
763
|
+
}
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
const tags = await getJson(`${base}/repos/${slug}/tags?per_page=100`)
|
|
767
|
+
if (Array.isArray(tags)) {
|
|
768
|
+
const rows = tags.filter((tag) => tag !== null && typeof tag === 'object' && versionOfEntry(tag) !== null)
|
|
769
|
+
const picked = pickEntry(rows, { from, want })
|
|
770
|
+
if (picked !== null) return await tagResult(picked, slug, getJson)
|
|
771
|
+
}
|
|
772
|
+
} catch {
|
|
773
|
+
// release notes are a display nicety only
|
|
774
|
+
}
|
|
775
|
+
return null
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
// ---------------------------------------------------------------------------
|
|
779
|
+
// Backup discovery, rollback and last-good bookkeeping
|
|
780
|
+
// ---------------------------------------------------------------------------
|
|
781
|
+
|
|
782
|
+
function requirePath(value, label) {
|
|
783
|
+
if (typeof value !== 'string' || value.trim() === '') {
|
|
784
|
+
throw new TypeError(`${label} 必须是非空路径字符串`)
|
|
785
|
+
}
|
|
786
|
+
if (value.includes('\0')) throw new TypeError(`${label} 不能包含空字符`)
|
|
787
|
+
return path.resolve(value.trim())
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
function isInside(child, parent) {
|
|
791
|
+
const relative = path.relative(parent, child)
|
|
792
|
+
return relative !== '' && relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative)
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
function readInstalledVersion(root) {
|
|
796
|
+
for (const file of [path.join(root, 'package.json'), path.join(root, 'node_modules', PACKAGE_NAME, 'package.json')]) {
|
|
797
|
+
try {
|
|
798
|
+
const data = JSON.parse(fs.readFileSync(file, 'utf8'))
|
|
799
|
+
const version = trimmed(data?.version)
|
|
800
|
+
if (version !== '') return version
|
|
801
|
+
} catch {
|
|
802
|
+
// try the next candidate
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
return null
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
/**
|
|
809
|
+
* Find the newest `«installRoot».backup-<timestamp>` sibling left on disk.
|
|
810
|
+
*
|
|
811
|
+
* Read-only. `updateTo` deletes its backup after a successful atomic swap, so
|
|
812
|
+
* this normally finds nothing then; it recovers backups left behind by an
|
|
813
|
+
* interrupted/failed swap (or retained by a future updater). It returns the
|
|
814
|
+
* newest candidate sorted by the timestamp embedded in the directory name.
|
|
815
|
+
*
|
|
816
|
+
* @param {string} installRoot - installation root the updater swaps.
|
|
817
|
+
* @returns {{ path: string, name: string, timestamp: number, mtimeMs: number, version: string | null } | null}
|
|
818
|
+
*/
|
|
819
|
+
export function findLatestBackup(installRoot) {
|
|
820
|
+
const root = requirePath(installRoot, 'installRoot')
|
|
821
|
+
const parent = path.dirname(root)
|
|
822
|
+
const base = path.basename(root)
|
|
823
|
+
const prefix = `${base}.backup-`
|
|
824
|
+
let entries
|
|
825
|
+
try {
|
|
826
|
+
entries = fs.readdirSync(parent, { withFileTypes: true })
|
|
827
|
+
} catch {
|
|
828
|
+
return null
|
|
829
|
+
}
|
|
830
|
+
const backups = []
|
|
831
|
+
for (const entry of entries) {
|
|
832
|
+
if (!entry.name.startsWith(prefix)) continue
|
|
833
|
+
const suffix = entry.name.slice(prefix.length)
|
|
834
|
+
if (!/^\d+$/u.test(suffix)) continue
|
|
835
|
+
const backupPath = path.join(parent, entry.name)
|
|
836
|
+
let stat
|
|
837
|
+
try {
|
|
838
|
+
stat = fs.statSync(backupPath)
|
|
839
|
+
} catch {
|
|
840
|
+
continue
|
|
841
|
+
}
|
|
842
|
+
if (!stat.isDirectory()) continue
|
|
843
|
+
backups.push({ path: backupPath, name: entry.name, timestamp: Number(suffix), mtimeMs: stat.mtimeMs })
|
|
844
|
+
}
|
|
845
|
+
if (backups.length === 0) return null
|
|
846
|
+
backups.sort((left, right) => right.timestamp - left.timestamp || right.mtimeMs - left.mtimeMs || right.name.localeCompare(left.name))
|
|
847
|
+
const latest = backups[0]
|
|
848
|
+
return { ...latest, version: readInstalledVersion(latest.path) }
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
/**
|
|
852
|
+
* Restore a sibling backup directory produced by `swapInstallRoot`.
|
|
853
|
+
*
|
|
854
|
+
* Safety checks: both arguments must be non-empty paths, the backup must be a
|
|
855
|
+
* directory next to the installation root and must be named
|
|
856
|
+
* `«installRoot».backup-…`; the two paths must not overlap. The current
|
|
857
|
+
* installation root (if present) is renamed aside rather than deleted and is
|
|
858
|
+
* returned as `displaced`, so a failed restore never destroys data. `updateTo`
|
|
859
|
+
* never calls this; rollback is an explicit host action.
|
|
860
|
+
*
|
|
861
|
+
* @param {string} backupRoot - absolute or relative path of `*.backup-*`.
|
|
862
|
+
* @param {string} installRoot - installation root to restore into.
|
|
863
|
+
* @returns {{ ok: true, installRoot: string, backupRoot: string, displaced: string | null, version: string | null }}
|
|
864
|
+
* @throws {TypeError | Error} with a readable message when validation or the
|
|
865
|
+
* rename fails.
|
|
866
|
+
*/
|
|
867
|
+
export function restoreBackup(backupRoot, installRoot) {
|
|
868
|
+
const backup = requirePath(backupRoot, 'backupRoot')
|
|
869
|
+
const root = requirePath(installRoot, 'installRoot')
|
|
870
|
+
if (backup === root) throw new Error(`备份目录与安装目录不能相同:${backup}`)
|
|
871
|
+
if (isInside(backup, root) || isInside(root, backup)) {
|
|
872
|
+
throw new Error(`备份目录与安装目录不能互相包含:${backup} / ${root}`)
|
|
873
|
+
}
|
|
874
|
+
const base = path.basename(root)
|
|
875
|
+
if (path.dirname(backup) !== path.dirname(root)) {
|
|
876
|
+
throw new Error(`备份目录必须与安装目录同级:${backup}`)
|
|
877
|
+
}
|
|
878
|
+
if (!path.basename(backup).startsWith(`${base}.backup-`) || !/^\d+$/u.test(path.basename(backup).slice(base.length + '.backup-'.length))) {
|
|
879
|
+
throw new Error(`备份目录必须是由 ${base} 生成的 .backup-<时间戳> 目录:${backup}`)
|
|
880
|
+
}
|
|
881
|
+
let stat
|
|
882
|
+
try {
|
|
883
|
+
stat = fs.statSync(backup)
|
|
884
|
+
} catch {
|
|
885
|
+
throw new Error(`备份目录不存在:${backup}`)
|
|
886
|
+
}
|
|
887
|
+
if (!stat.isDirectory()) throw new Error(`备份路径不是目录:${backup}`)
|
|
888
|
+
let hasRoot = false
|
|
889
|
+
try {
|
|
890
|
+
fs.lstatSync(root)
|
|
891
|
+
hasRoot = true
|
|
892
|
+
} catch {
|
|
893
|
+
// a missing live root is fine: the backup simply fills the gap
|
|
894
|
+
}
|
|
895
|
+
let displaced = null
|
|
896
|
+
if (hasRoot) {
|
|
897
|
+
displaced = `${root}.pre-restore-${Date.now()}`
|
|
898
|
+
try {
|
|
899
|
+
fs.renameSync(root, displaced)
|
|
900
|
+
} catch (error) {
|
|
901
|
+
throw new Error(`无法移开当前安装目录:${error.message}`)
|
|
902
|
+
}
|
|
903
|
+
}
|
|
904
|
+
try {
|
|
905
|
+
fs.renameSync(backup, root)
|
|
906
|
+
} catch (error) {
|
|
907
|
+
if (displaced !== null) {
|
|
908
|
+
try {
|
|
909
|
+
fs.renameSync(displaced, root)
|
|
910
|
+
} catch {
|
|
911
|
+
// keep the displaced copy on disk; the thrown error names it below
|
|
912
|
+
}
|
|
913
|
+
}
|
|
914
|
+
throw new Error(`无法恢复备份:${error.message}`)
|
|
915
|
+
}
|
|
916
|
+
return { ok: true, installRoot: root, backupRoot: backup, displaced, version: readInstalledVersion(root) }
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
/**
|
|
920
|
+
* Persist the last known-good version (and installation root). Non-throwing:
|
|
921
|
+
* returns `null` when the version is unknown or the state file is unwritable.
|
|
922
|
+
* `updateTo` does not write this; a host should record it after it has seen the
|
|
923
|
+
* running version boot successfully.
|
|
924
|
+
*
|
|
925
|
+
* @param {string | { version?: string, root?: string }} [input] - version string
|
|
926
|
+
* or object; missing fields fall back to the running installation.
|
|
927
|
+
* @returns {{ version: string, root: string | null, recordedAt: string } | null}
|
|
928
|
+
*/
|
|
929
|
+
export function recordLastGood(input = {}) {
|
|
930
|
+
let version
|
|
931
|
+
let root
|
|
932
|
+
if (typeof input === 'string') {
|
|
933
|
+
version = input.trim()
|
|
934
|
+
} else if (input !== null && typeof input === 'object') {
|
|
935
|
+
version = trimmed(input.version)
|
|
936
|
+
if (typeof input.root === 'string' && input.root.trim() !== '') root = path.resolve(input.root.trim())
|
|
937
|
+
}
|
|
938
|
+
let install
|
|
939
|
+
if (version === '' || version === undefined || root === undefined) {
|
|
940
|
+
try {
|
|
941
|
+
install = locateInstall()
|
|
942
|
+
} catch {
|
|
943
|
+
install = null
|
|
944
|
+
}
|
|
945
|
+
}
|
|
946
|
+
if (version === '' || version === undefined) version = install?.version
|
|
947
|
+
if (root === undefined) root = install?.root
|
|
948
|
+
if (version === undefined || version === '') return null
|
|
949
|
+
const record = { version, root: root ?? null, recordedAt: new Date().toISOString() }
|
|
950
|
+
try {
|
|
951
|
+
fs.mkdirSync(STATE_DIR, { recursive: true, mode: 0o700 })
|
|
952
|
+
const temporary = `${LAST_GOOD_FILE}.${process.pid}.tmp`
|
|
953
|
+
fs.writeFileSync(temporary, `${JSON.stringify(record)}\n`, { mode: 0o600 })
|
|
954
|
+
fs.renameSync(temporary, LAST_GOOD_FILE)
|
|
955
|
+
} catch {
|
|
956
|
+
return null
|
|
957
|
+
}
|
|
958
|
+
return record
|
|
959
|
+
}
|
|
960
|
+
|
|
961
|
+
/**
|
|
962
|
+
* Read the record written by `recordLastGood`.
|
|
963
|
+
*
|
|
964
|
+
* @returns {{ version: string, root: string | null, recordedAt: string | null } | null}
|
|
965
|
+
*/
|
|
966
|
+
export function readLastGood() {
|
|
967
|
+
try {
|
|
968
|
+
const data = JSON.parse(fs.readFileSync(LAST_GOOD_FILE, 'utf8'))
|
|
969
|
+
if (data === null || typeof data !== 'object') return null
|
|
970
|
+
const version = trimmed(data.version)
|
|
971
|
+
if (version === '') return null
|
|
972
|
+
return {
|
|
973
|
+
version,
|
|
974
|
+
root: typeof data.root === 'string' && data.root !== '' ? data.root : null,
|
|
975
|
+
recordedAt: typeof data.recordedAt === 'string' && data.recordedAt !== '' ? data.recordedAt : null,
|
|
976
|
+
}
|
|
977
|
+
} catch {
|
|
978
|
+
return null
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
|
|
982
|
+
// ---------------------------------------------------------------------------
|
|
983
|
+
// Background update-check policy (pure, no I/O)
|
|
984
|
+
// ---------------------------------------------------------------------------
|
|
985
|
+
|
|
986
|
+
/**
|
|
987
|
+
* Decide what a background update check should do. Pure function; no state,
|
|
988
|
+
* timers or filesystem access, so the host and the tray can share the policy.
|
|
989
|
+
*
|
|
990
|
+
* @param {object | null | undefined} checkResult - `checkUpdates()` payload.
|
|
991
|
+
* @param {{ deferUntil?: number, now?: number }} [options] - persisted
|
|
992
|
+
* "remind me later" timestamp and injectable clock (tests).
|
|
993
|
+
* @returns {{ available: boolean, version: string | null, deferred: boolean, reason: 'no-result' | 'up-to-date' | 'deferred' | 'available' }}
|
|
994
|
+
*/
|
|
995
|
+
export function evaluateUpdate(checkResult, options = {}) {
|
|
996
|
+
const parsedNow = Number(options?.now)
|
|
997
|
+
const now = Number.isFinite(parsedNow) ? parsedNow : Date.now()
|
|
998
|
+
const parsedUntil = Number(options?.deferUntil)
|
|
999
|
+
const deferUntil = Number.isFinite(parsedUntil) ? parsedUntil : 0
|
|
1000
|
+
const result = checkResult !== null && typeof checkResult === 'object' ? checkResult : null
|
|
1001
|
+
if (result === null) return { available: false, version: null, deferred: false, reason: 'no-result' }
|
|
1002
|
+
const candidate = trimmed(result.candidate) || null
|
|
1003
|
+
const current = trimmed(result.current) || null
|
|
1004
|
+
let available = result.updateAvailable === true
|
|
1005
|
+
if (typeof result.updateAvailable !== 'boolean' && candidate !== null && current !== null) {
|
|
1006
|
+
available = (safeCompare(candidate, current) ?? 0) > 0
|
|
1007
|
+
}
|
|
1008
|
+
const version = candidate ?? current
|
|
1009
|
+
if (!available) return { available: false, version, deferred: false, reason: 'up-to-date' }
|
|
1010
|
+
const deferred = deferUntil > now
|
|
1011
|
+
return { available: true, version, deferred, reason: deferred ? 'deferred' : 'available' }
|
|
1012
|
+
}
|
|
1013
|
+
|
|
1014
|
+
// ---------------------------------------------------------------------------
|
|
1015
|
+
// Self-test (`node lib/update.js`), no network required
|
|
1016
|
+
// ---------------------------------------------------------------------------
|
|
1017
|
+
|
|
1018
|
+
async function runSelfTest() {
|
|
1019
|
+
const assert = (await import('node:assert/strict')).default
|
|
1020
|
+
const net = await import('node:net')
|
|
1021
|
+
const { execFile } = await import('node:child_process')
|
|
1022
|
+
const { promisify } = await import('node:util')
|
|
1023
|
+
const execFileAsync = promisify(execFile)
|
|
1024
|
+
let passed = 0
|
|
1025
|
+
const run = async (name, fn) => {
|
|
1026
|
+
try {
|
|
1027
|
+
await fn()
|
|
1028
|
+
} catch (error) {
|
|
1029
|
+
console.error(`not ok - ${name}`)
|
|
1030
|
+
throw error
|
|
1031
|
+
}
|
|
1032
|
+
passed += 1
|
|
1033
|
+
console.log(`ok ${passed} - ${name}`)
|
|
1034
|
+
}
|
|
1035
|
+
|
|
1036
|
+
await run('evaluateUpdate: deferred while reminder is pending', () => {
|
|
1037
|
+
assert.deepEqual(
|
|
1038
|
+
evaluateUpdate({ updateAvailable: true, candidate: '0.6.0', current: '0.5.2' }, { deferUntil: 2000, now: 1000 }),
|
|
1039
|
+
{ available: true, version: '0.6.0', deferred: true, reason: 'deferred' },
|
|
1040
|
+
)
|
|
1041
|
+
})
|
|
1042
|
+
await run('evaluateUpdate: available once the reminder expired', () => {
|
|
1043
|
+
assert.deepEqual(
|
|
1044
|
+
evaluateUpdate({ updateAvailable: true, candidate: 'v0.6.0', current: '0.5.2' }, { deferUntil: 1000, now: 2000 }),
|
|
1045
|
+
{ available: true, version: 'v0.6.0', deferred: false, reason: 'available' },
|
|
1046
|
+
)
|
|
1047
|
+
})
|
|
1048
|
+
await run('evaluateUpdate: up to date and no result', () => {
|
|
1049
|
+
assert.deepEqual(
|
|
1050
|
+
evaluateUpdate({ updateAvailable: false, candidate: '0.5.2', current: '0.5.2' }),
|
|
1051
|
+
{ available: false, version: '0.5.2', deferred: false, reason: 'up-to-date' },
|
|
1052
|
+
)
|
|
1053
|
+
assert.deepEqual(evaluateUpdate(null), { available: false, version: null, deferred: false, reason: 'no-result' })
|
|
1054
|
+
})
|
|
1055
|
+
await run('evaluateUpdate: infers availability and ignores bad defer values', () => {
|
|
1056
|
+
assert.deepEqual(
|
|
1057
|
+
evaluateUpdate({ candidate: '0.6.0', current: '0.5.2' }, { deferUntil: Number.NaN }),
|
|
1058
|
+
{ available: true, version: '0.6.0', deferred: false, reason: 'available' },
|
|
1059
|
+
)
|
|
1060
|
+
})
|
|
1061
|
+
await run('normalizeRepository: supported shapes', () => {
|
|
1062
|
+
assert.equal(normalizeRepository('git+https://github.com/MiraculousGu/dsh-app-controls.git'), 'MiraculousGu/dsh-app-controls')
|
|
1063
|
+
assert.equal(normalizeRepository({ url: 'git@github.com:MiraculousGu/dsh-app-controls.git' }), 'MiraculousGu/dsh-app-controls')
|
|
1064
|
+
assert.equal(normalizeRepository('github:MiraculousGu/dsh-app-controls'), 'MiraculousGu/dsh-app-controls')
|
|
1065
|
+
assert.equal(normalizeRepository('https://github.com/MiraculousGu/dsh-app-controls#readme'), 'MiraculousGu/dsh-app-controls')
|
|
1066
|
+
assert.equal(normalizeRepository('https://gitlab.com/MiraculousGu/dsh-app-controls'), null)
|
|
1067
|
+
assert.equal(normalizeRepository('not a repo'), null)
|
|
1068
|
+
})
|
|
1069
|
+
|
|
1070
|
+
const temp = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-update-selftest-'))
|
|
1071
|
+
try {
|
|
1072
|
+
await run('findLatestBackup: newest sibling backup, version and validation', () => {
|
|
1073
|
+
const root = path.join(temp, 'root')
|
|
1074
|
+
fs.mkdirSync(path.join(root, 'node_modules', PACKAGE_NAME), { recursive: true })
|
|
1075
|
+
fs.writeFileSync(path.join(root, 'node_modules', PACKAGE_NAME, 'package.json'), JSON.stringify({ version: '1.0.0' }))
|
|
1076
|
+
fs.mkdirSync(path.join(temp, 'root.backup-1000'))
|
|
1077
|
+
const newer = path.join(temp, 'root.backup-2000')
|
|
1078
|
+
fs.mkdirSync(newer)
|
|
1079
|
+
fs.writeFileSync(path.join(newer, 'package.json'), JSON.stringify({ version: '0.9.0' }))
|
|
1080
|
+
fs.mkdirSync(path.join(temp, 'root.backup-not-a-number'))
|
|
1081
|
+
const found = findLatestBackup(root)
|
|
1082
|
+
assert.equal(found?.path, newer)
|
|
1083
|
+
assert.equal(found?.timestamp, 2000)
|
|
1084
|
+
assert.equal(found?.version, '0.9.0')
|
|
1085
|
+
assert.equal(findLatestBackup(path.join(temp, 'missing-root')), null)
|
|
1086
|
+
assert.throws(() => findLatestBackup(' '), TypeError)
|
|
1087
|
+
assert.throws(() => findLatestBackup(path.join(temp, 'bad\0root')), TypeError)
|
|
1088
|
+
})
|
|
1089
|
+
|
|
1090
|
+
await run('restoreBackup: rejects unsafe paths and repairs the install root', () => {
|
|
1091
|
+
const root = path.join(temp, 'install')
|
|
1092
|
+
fs.mkdirSync(root)
|
|
1093
|
+
fs.writeFileSync(path.join(root, 'marker.txt'), 'new')
|
|
1094
|
+
const backup = path.join(temp, 'install.backup-3000')
|
|
1095
|
+
fs.mkdirSync(backup)
|
|
1096
|
+
fs.writeFileSync(path.join(backup, 'marker.txt'), 'old')
|
|
1097
|
+
assert.throws(() => restoreBackup('', root), TypeError)
|
|
1098
|
+
assert.throws(() => restoreBackup(path.join(temp, 'other', 'install.backup-1'), root), /同级/u)
|
|
1099
|
+
assert.throws(() => restoreBackup(path.join(temp, 'wrong.backup-1'), path.join(temp, 'other-install')), /必须是由/u)
|
|
1100
|
+
assert.throws(() => restoreBackup(path.join(temp, 'install.backup-9999'), root), /不存在/u)
|
|
1101
|
+
assert.throws(() => restoreBackup(path.join(temp, 'install.backup-file'), root), /必须是由/u)
|
|
1102
|
+
fs.writeFileSync(path.join(temp, 'install.backup-4000'), 'not a directory')
|
|
1103
|
+
assert.throws(() => restoreBackup(path.join(temp, 'install.backup-4000'), root), /备份目录必须是由|不是目录/u)
|
|
1104
|
+
const restored = restoreBackup(backup, root)
|
|
1105
|
+
assert.equal(restored.ok, true)
|
|
1106
|
+
assert.equal(fs.readFileSync(path.join(root, 'marker.txt'), 'utf8'), 'old')
|
|
1107
|
+
assert.equal(fs.existsSync(backup), false)
|
|
1108
|
+
assert.ok(restored.displaced !== null && fs.readFileSync(path.join(restored.displaced, 'marker.txt'), 'utf8') === 'new')
|
|
1109
|
+
})
|
|
1110
|
+
|
|
1111
|
+
await run('recordLastGood/readLastGood: isolated state round-trip', async () => {
|
|
1112
|
+
const script = [
|
|
1113
|
+
`import { recordLastGood, readLastGood } from ${JSON.stringify(new URL(import.meta.url).href)}`,
|
|
1114
|
+
"const written = recordLastGood({ version: '9.9.9', root: '/tmp/dsh-selftest-root' })",
|
|
1115
|
+
'const read = readLastGood()',
|
|
1116
|
+
"if (written === null || read === null || read.version !== '9.9.9' || read.root !== '/tmp/dsh-selftest-root') process.exit(1)",
|
|
1117
|
+
].join('\n')
|
|
1118
|
+
await execFileAsync(process.execPath, ['--input-type=module', '--eval', script], {
|
|
1119
|
+
env: { ...process.env, XDG_STATE_HOME: path.join(temp, 'state') },
|
|
1120
|
+
})
|
|
1121
|
+
})
|
|
1122
|
+
|
|
1123
|
+
await run('fetchReleaseNotes: timeout and unreachable endpoint return null', async () => {
|
|
1124
|
+
const sockets = new Set()
|
|
1125
|
+
const server = net.createServer((socket) => {
|
|
1126
|
+
sockets.add(socket)
|
|
1127
|
+
socket.on('close', () => sockets.delete(socket))
|
|
1128
|
+
})
|
|
1129
|
+
await new Promise((resolve, reject) => {
|
|
1130
|
+
server.once('error', reject)
|
|
1131
|
+
server.listen(0, '127.0.0.1', resolve)
|
|
1132
|
+
})
|
|
1133
|
+
const port = server.address().port
|
|
1134
|
+
const started = Date.now()
|
|
1135
|
+
try {
|
|
1136
|
+
const hanging = await fetchReleaseNotes({
|
|
1137
|
+
repository: DEFAULT_REPOSITORY,
|
|
1138
|
+
timeoutMs: 150,
|
|
1139
|
+
apiBase: `http://127.0.0.1:${port}`,
|
|
1140
|
+
})
|
|
1141
|
+
assert.equal(hanging, null)
|
|
1142
|
+
assert.ok(Date.now() - started < 5000)
|
|
1143
|
+
assert.equal(await fetchReleaseNotes({ repository: DEFAULT_REPOSITORY, timeoutMs: 200, apiBase: 'http://127.0.0.1:9' }), null)
|
|
1144
|
+
assert.equal(await fetchReleaseNotes({ repository: 'https://gitlab.com/a/b' }), null)
|
|
1145
|
+
} finally {
|
|
1146
|
+
for (const socket of sockets) socket.destroy()
|
|
1147
|
+
await new Promise((resolve) => server.close(resolve))
|
|
1148
|
+
}
|
|
1149
|
+
})
|
|
1150
|
+
} finally {
|
|
1151
|
+
fs.rmSync(temp, { recursive: true, force: true })
|
|
1152
|
+
}
|
|
1153
|
+
|
|
1154
|
+
console.log(`update.js self-test: ${passed} passed`)
|
|
1155
|
+
}
|
|
1156
|
+
|
|
1157
|
+
const isMain = typeof process.argv[1] === 'string' && pathToFileURL(path.resolve(process.argv[1])).href === import.meta.url
|
|
1158
|
+
if (isMain) await runSelfTest()
|
package/locale/en.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"meta": {
|
|
3
3
|
"title": "DeepSeek Harness app controls",
|
|
4
|
-
"description": "Adds check/update and quit buttons to the DeepSeek Harness Web GUI, plus a KDE system-tray controller and a settings panel in Plugins. Settings cover the tray icon, per-feature show/hide controls, and a remembered default startup window size; they are stored locally and applied on the next DSH start. The buttons check/update DSH with a progress dialog, or gracefully stop the service and close the window;
|
|
4
|
+
"description": "Adds check/update and quit buttons to the DeepSeek Harness Web GUI, plus a KDE system-tray controller and a settings panel in Plugins. Settings cover the tray icon (DeepSeek, classic or custom), per-feature show/hide controls, update policy, and a remembered default startup window size; they are stored locally and applied on the next DSH start. The buttons check/update DSH with running-task warnings, deferral, release notes and a minimizable progress dialog, or gracefully stop the service and close the window; a single-instance tray shows status and offers open, same-window plugins/settings navigation, update, restart, stop, logs and copy URL. Applicable to DeepSeek Harness 0.2.2-rc.x Web profile on Linux/KDE (Chrome app window) and Node.js 20+; the tray needs PyQt5. It also offers optional cache cleanup (application, npx/npm/pnpm, update leftovers) that never removes the running DSH, plugin source, installed plugins, settings, sessions or sign-in state. The tray menu follows the DSH light/dark theme; background update checks run every 30 minutes, notify only when an update exists, and show a toast in the app; updates can be deferred for a configurable period."
|
|
5
5
|
}
|
|
6
6
|
}
|
package/locale/zh.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"meta": {
|
|
3
3
|
"title": "DeepSeek Harness 应用控制",
|
|
4
|
-
"description": "为 DeepSeek Harness Web 界面增加「检查并更新」与「退出」按钮,并提供 KDE
|
|
4
|
+
"description": "为 DeepSeek Harness Web 界面增加「检查并更新」与「退出」按钮,并提供 KDE 系统托盘控制器和插件设置面板。设置包括系统托盘开关与图标(DeepSeek/经典/自定义)、各功能显示/隐藏、更新策略、默认启动窗口大小(可记住当前窗口大小);设置保存在本机并在下次启动 DSH 时自动生效。按钮支持带运行任务风险提示、可推迟、含更新说明且可最小化进度弹窗的检查更新,以及优雅停止服务并自动关窗;单实例托盘提供打开、同窗插件管理/设置、检查/更新、重启、停止、日志和复制地址。适用于 DeepSeek Harness 0.2.2-rc.x 的 Web profile(Linux/KDE、Chrome 应用窗口),需要 Node.js 20+;托盘需要 PyQt5。此外提供按类型清理缓存(应用缓存、npx/npm/pnpm 缓存、更新残留);清理不会删除运行中的 DSH、插件源码、已安装插件、设置、会话或登录状态。 托盘菜单会跟随 DSH 明暗主题切换;后台每 30 分钟检查更新,仅在发现新版本时提示,并在应用内弹出提示;支持按设置推迟更新。"
|
|
5
5
|
}
|
|
6
6
|
}
|