dsh-mcviseron-plugin 0.6.5 → 0.6.6

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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-mcviseron-plugin",
3
- "version": "0.6.5",
4
- "description": "DeepSeek Harness (DSH) master plugin — one package hosting MCviseron's DSH components as separate bundle entries: a time-based light/dark Appearance schedule, an Auto-review fix (shutdown preset guard + Chinese approval-reason translation), and a todo plan guard that keeps multi-stage work advancing, and one-shot after-session restart/close actions with task-aware waiting.",
3
+ "version": "0.6.6",
4
+ "description": "DeepSeek Harness (DSH) master plugin — one package hosting MCviseron's DSH components as separate bundle entries: a time-based light/dark Appearance schedule, an Auto-review fix (shutdown preset guard + Chinese approval-reason translation), and a todo plan guard that keeps multi-stage work advancing, one-shot after-session restart/close actions with task-aware waiting, and automatic auth-cookie hygiene for repeated desktop restarts.",
5
5
  "license": "Apache-2.0",
6
6
  "author": {
7
7
  "name": "MCviseron",
@@ -78,7 +78,7 @@
78
78
  "scripts": {
79
79
  "build": "node build.mjs",
80
80
  "typecheck": "tsc --noEmit",
81
- "test": "node --experimental-strip-types test/schedule.test.ts && node --experimental-strip-types test/routes.test.ts && node --experimental-strip-types test/config.test.ts && node --experimental-strip-types test/auto-review-fix.test.ts && node --experimental-strip-types test/auto-review-fix-cordis.test.ts && node --experimental-strip-types test/task-guard.test.ts && node --experimental-strip-types test/task-guard-cordis.test.ts && node --experimental-strip-types test/session-end.test.ts && node --experimental-strip-types test/restart.test.ts && node --experimental-strip-types test/plugin.test.ts",
81
+ "test": "node --experimental-strip-types test/schedule.test.ts && node --experimental-strip-types test/routes.test.ts && node --experimental-strip-types test/config.test.ts && node --experimental-strip-types test/auto-review-fix.test.ts && node --experimental-strip-types test/auto-review-fix-cordis.test.ts && node --experimental-strip-types test/review-context.test.ts && node --experimental-strip-types test/global-notice.test.ts && node --experimental-strip-types test/task-guard.test.ts && node --experimental-strip-types test/task-guard-cordis.test.ts && node --experimental-strip-types test/session-end.test.ts && node --experimental-strip-types test/auth-cookie.test.ts && node --experimental-strip-types test/restart.test.ts && node --experimental-strip-types test/plugin.test.ts",
82
82
  "check": "pnpm typecheck && pnpm test && pnpm build",
83
83
  "prepare": "pnpm build",
84
84
  "prepublishOnly": "pnpm check",
package/src/api.ts CHANGED
@@ -8,4 +8,10 @@ export const MCVISERON_API = {
8
8
  export const SESSION_END_API = {
9
9
  state: '/api/dsh-mcviseron/session-end/state',
10
10
  set: '/api/dsh-mcviseron/session-end/set',
11
+ global: '/api/dsh-mcviseron/session-end/global',
12
+ } as const
13
+
14
+ /** Auth-cookie hygiene shared by the index script and the client fallback. */
15
+ export const AUTH_COOKIE_API = {
16
+ prune: '/api/dsh-mcviseron/auth-cookies/prune',
11
17
  } as const
@@ -0,0 +1,175 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { appendFileSync } from 'node:fs'
3
+ import { tmpdir } from 'node:os'
4
+ import { join } from 'node:path'
5
+ import type { Context } from '@deepseek-ai/cordis'
6
+ import type { IncomingMessage, ServerResponse } from 'node:http'
7
+ import type { WebRoute } from '@deepseek-ai/dsh-host-webserver'
8
+ import { AUTH_COOKIE_API } from '../api.ts'
9
+ import { isLoopbackRequest } from '../loopback.ts'
10
+
11
+ export const AUTH_COOKIE_PREFIX = 'dsh-auth-'
12
+ const EXPIRED_AT = 'Thu, 01 Jan 1970 00:00:00 GMT'
13
+
14
+ function logPrune(authority: string, pruned: number): void {
15
+ try {
16
+ appendFileSync(
17
+ join(tmpdir(), 'dsh-mcviseron-auth-cookie.log'),
18
+ new Date().toISOString() + ' pruned=' + pruned + ' authority=' + authority + '\n',
19
+ 'utf8',
20
+ )
21
+ } catch {
22
+ /* diagnostics must never break cookie hygiene */
23
+ }
24
+ }
25
+
26
+ /** Mirror DSH's browser-auth cookie name for one request authority. */
27
+ export function authCookieName(authority: string): string {
28
+ return AUTH_COOKIE_PREFIX + createHash('sha256').update(authority).digest('base64url')
29
+ }
30
+
31
+ /**
32
+ * Mirror dsh-client-connection's requestAudience: HTTP cookies are keyed by
33
+ * host:port, TLS cookies by the origin. Chromium itself ignores the port.
34
+ */
35
+ export function requestAuthority(host: unknown, secure: boolean): string | undefined {
36
+ if (typeof host !== 'string' || host === '') return undefined
37
+ try {
38
+ const url = new URL((secure ? 'https:' : 'http:') + '//' + host)
39
+ return secure ? url.origin : url.host
40
+ } catch {
41
+ return undefined
42
+ }
43
+ }
44
+
45
+ function validAuthCookieName(name: string): boolean {
46
+ if (!name.startsWith(AUTH_COOKIE_PREFIX)) return false
47
+ return /^[A-Za-z0-9_-]+$/.test(name.slice(AUTH_COOKIE_PREFIX.length))
48
+ }
49
+
50
+ /** Extract only syntactically valid dsh-auth-* names from a Cookie header. */
51
+ export function authCookieNames(header: unknown): string[] {
52
+ if (typeof header !== 'string' || header === '') return []
53
+ const names = new Set<string>()
54
+ for (const segment of header.split(';')) {
55
+ const at = segment.indexOf('=')
56
+ const name = (at === -1 ? segment : segment.slice(0, at)).trim()
57
+ if (validAuthCookieName(name)) names.add(name)
58
+ }
59
+ return [...names]
60
+ }
61
+
62
+ /** Names that are not the cookie this launch just minted. */
63
+ export function staleAuthCookieNames(header: unknown, currentName: string): string[] {
64
+ return authCookieNames(header).filter(name => name !== currentName)
65
+ }
66
+
67
+ /** A deletion Set-Cookie matching the generated cookie's Path/host-only scope. */
68
+ export function expiredAuthCookie(name: string, secure: boolean): string {
69
+ return name + '=; Max-Age=0; Path=/; Expires=' + EXPIRED_AT
70
+ + '; HttpOnly; SameSite=Strict' + (secure ? '; Secure' : '')
71
+ }
72
+
73
+ /** Build the deletion headers for one request, keeping the current cookie. */
74
+ export function pruneCookieHeaders(req: IncomingMessage, secure: boolean): string[] {
75
+ const authority = requestAuthority(req.headers.host, secure)
76
+ if (authority === undefined) return []
77
+ const current = authCookieName(authority)
78
+ return staleAuthCookieNames(req.headers.cookie, current).map(name => expiredAuthCookie(name, secure))
79
+ }
80
+
81
+ /** Head script: prune before the application's modules issue their own calls. */
82
+ export function pruneScript(): string {
83
+ return '(function(){try{fetch(' + JSON.stringify(AUTH_COOKIE_API.prune)
84
+ + ',{method:"POST",credentials:"same-origin",cache:"no-store"}).catch(function(){})}catch(e){}})()'
85
+ }
86
+
87
+ function json(res: ServerResponse, status: number, body: unknown, extra: Record<string, string | string[]> = {}): void {
88
+ res.writeHead(status, {
89
+ 'content-type': 'application/json; charset=utf-8',
90
+ 'cache-control': 'no-store',
91
+ ...extra,
92
+ })
93
+ res.end(JSON.stringify(body))
94
+ }
95
+
96
+ /** Host route used by the head script and the client fallback. */
97
+ export function makeAuthCookieRoutes(options: { secure: () => boolean }): WebRoute[] {
98
+ const route: WebRoute = {
99
+ kind: 'exact',
100
+ path: AUTH_COOKIE_API.prune,
101
+ handler: (req, res): void => {
102
+ if (req.method !== 'POST') {
103
+ json(res, 405, { ok: false, error: 'method-not-allowed' })
104
+ return
105
+ }
106
+ if (!isLoopbackRequest(req)) {
107
+ json(res, 403, { ok: false, error: 'forbidden' })
108
+ return
109
+ }
110
+ const secure = options.secure()
111
+ const authority = requestAuthority(req.headers.host, secure)
112
+ if (authority === undefined) {
113
+ json(res, 400, { ok: false, error: 'host-required' })
114
+ return
115
+ }
116
+ const stale = staleAuthCookieNames(req.headers.cookie, authCookieName(authority))
117
+ logPrune(authority, stale.length)
118
+ const extra: Record<string, string | string[]> = stale.length === 0
119
+ ? {}
120
+ : { 'set-cookie': stale.map(name => expiredAuthCookie(name, secure)) }
121
+ json(res, 200, { ok: true, pruned: stale.length }, extra)
122
+ },
123
+ }
124
+ return [route]
125
+ }
126
+
127
+ function eventBusOf(ctx: Context): { on?: (event: string, handler: (table: unknown) => void) => unknown } {
128
+ const root = (ctx as unknown as { root?: unknown }).root
129
+ return (root ?? ctx) as { on?: (event: string, handler: (table: unknown) => void) => unknown }
130
+ }
131
+
132
+ function installIndexInjection(ctx: Context): void {
133
+ const bus = eventBusOf(ctx)
134
+ if (typeof bus.on !== 'function') return
135
+ try {
136
+ ctx.effect(() => {
137
+ const dispose = bus.on?.('webserver/index-inject', (table) => {
138
+ if (!Array.isArray(table)) return
139
+ table.push({ kind: 'script', placement: 'head', text: pruneScript() })
140
+ })
141
+ return () => {
142
+ if (typeof dispose === 'function') dispose()
143
+ }
144
+ }, 'mcviseron-auth-cookie: index injection')
145
+ } catch {
146
+ /* a host without effects still gets the route */
147
+ }
148
+ }
149
+
150
+ export const inject = ['webServer']
151
+
152
+ /**
153
+ * DSH's per-launch dsh-auth-<hash(host:port)> cookie is host-scoped in
154
+ * Chromium, so every restart otherwise leaves another 30-day cookie behind.
155
+ * This component expires every old dsh-auth-* cookie while keeping the one for
156
+ * the current authority. It runs entirely inside the plugin and survives DSH
157
+ * upgrades; it does not change the desktop application.
158
+ */
159
+ export function apply(ctx: Context): void {
160
+ const secure = (): boolean => {
161
+ try {
162
+ return ctx.webServer.protocol === 'https:'
163
+ } catch {
164
+ return false
165
+ }
166
+ }
167
+ const routes = makeAuthCookieRoutes({ secure })
168
+ ctx.effect(() => {
169
+ const disposers = routes.map(route => ctx.webServer.register(route))
170
+ return () => {
171
+ for (const dispose of disposers) dispose()
172
+ }
173
+ }, 'mcviseron-auth-cookie: prune route')
174
+ installIndexInjection(ctx)
175
+ }
@@ -15,6 +15,9 @@ export const DEFAULT_AUTO_REVIEW_CONFIG = {
15
15
  translateMaxChars: 4000,
16
16
  translateProvider: '',
17
17
  translateModel: '',
18
+ reviewContextGuard: true,
19
+ reviewMaxHistoryChars: 120000,
20
+ reviewKeepRecentEntries: 16,
18
21
  } as const
19
22
 
20
23
  export const Config = z.object({
@@ -24,6 +27,9 @@ export const Config = z.object({
24
27
  translateMaxChars: z.number().min(100).max(20000).default(DEFAULT_AUTO_REVIEW_CONFIG.translateMaxChars).volatile(),
25
28
  translateProvider: z.string().default(DEFAULT_AUTO_REVIEW_CONFIG.translateProvider).volatile(),
26
29
  translateModel: z.string().default(DEFAULT_AUTO_REVIEW_CONFIG.translateModel).volatile(),
30
+ reviewContextGuard: z.boolean().default(DEFAULT_AUTO_REVIEW_CONFIG.reviewContextGuard).volatile(),
31
+ reviewMaxHistoryChars: z.number().min(20000).max(600000).default(DEFAULT_AUTO_REVIEW_CONFIG.reviewMaxHistoryChars).volatile(),
32
+ reviewKeepRecentEntries: z.number().min(4).max(64).default(DEFAULT_AUTO_REVIEW_CONFIG.reviewKeepRecentEntries).volatile(),
27
33
  }).default(DEFAULT_AUTO_REVIEW_CONFIG)
28
34
 
29
35
  export interface AutoReviewConfig {
@@ -33,6 +39,9 @@ export interface AutoReviewConfig {
33
39
  translateMaxChars?: number
34
40
  translateProvider?: string
35
41
  translateModel?: string
42
+ reviewContextGuard?: boolean
43
+ reviewMaxHistoryChars?: number
44
+ reviewKeepRecentEntries?: number
36
45
  }
37
46
 
38
47
  /**
@@ -262,6 +262,9 @@ export function ConfigForm({ t, title, description, fields }: ConfigFormProps) {
262
262
 
263
263
  /** Auto-review component fields. */
264
264
  export const AUTO_REVIEW_FIELDS: readonly ConfigField[] = [
265
+ { path: ['autoReviewFix', 'reviewContextGuard'], label: 'form.autoReview.reviewGuard', hint: 'form.autoReview.reviewGuardHint', kind: 'switch' },
266
+ { path: ['autoReviewFix', 'reviewMaxHistoryChars'], label: 'form.autoReview.reviewMaxHistory', hint: 'form.autoReview.reviewMaxHistoryHint', kind: 'number', min: 20000, max: 600000 },
267
+ { path: ['autoReviewFix', 'reviewKeepRecentEntries'], label: 'form.autoReview.reviewKeepRecent', kind: 'number', min: 4, max: 64 },
265
268
  { path: ['autoReviewFix', 'translateApprovalReason'], label: 'form.autoReview.translate', hint: 'form.autoReview.translateHint', kind: 'switch' },
266
269
  { path: ['autoReviewFix', 'keepPresetGuard'], label: 'form.autoReview.keepPreset', hint: 'form.autoReview.keepPresetHint', kind: 'switch' },
267
270
  { path: ['autoReviewFix', 'translateTimeoutMs'], label: 'form.autoReview.timeout', kind: 'number', min: 500, max: 60000 },
@@ -9,6 +9,7 @@ import {
9
9
  } from '@deepseek-ai/dsh-client-ui-primitives'
10
10
  import type { PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'
11
11
  import { SESSION_END_API } from '../api.ts'
12
+ import { startSessionEndGlobalNotice } from './SessionEndGlobalNotice.ts'
12
13
  import type { McviseronKey } from './locales.ts'
13
14
 
14
15
  type Mode = 'off' | 'restart' | 'close' | 'shutdown'
@@ -152,6 +153,8 @@ export function SessionEndControl(props: SessionEndControlProps) {
152
153
  }
153
154
  }, [sessionId])
154
155
 
156
+ useEffect(() => startSessionEndGlobalNotice(), [])
157
+
155
158
  if (sessionId === undefined || sessionId === '') return null
156
159
 
157
160
  const change = (mode: Mode): void => {
@@ -0,0 +1,183 @@
1
+ import { SESSION_END_API } from '../api.ts'
2
+
3
+ export interface GlobalSessionEndAction {
4
+ sessionId: string
5
+ label: string
6
+ mode: 'restart' | 'close' | 'shutdown'
7
+ requestedBy: 'ai'
8
+ armedAt: number
9
+ waiting: boolean
10
+ runningAgents: number
11
+ runningJobs: number
12
+ }
13
+
14
+ const HOST_ID = 'mcviseron-session-end-global'
15
+ const FALLBACK_TOP = 56
16
+ const MIN_TOP = 120
17
+
18
+ /** Human label for one AI-armed process action. */
19
+ export function globalNoticeText(action: GlobalSessionEndAction): string {
20
+ const name = action.label.trim() !== '' ? action.label : '会话 …' + action.sessionId.slice(-6)
21
+ const mode = action.mode === 'restart' ? '自动重启' : action.mode === 'close' ? '自动关闭 DSH' : '关闭电脑'
22
+ return '「' + name + '」已启用 AI 会话' + mode
23
+ }
24
+
25
+ export function globalNoticeKey(action: GlobalSessionEndAction): string {
26
+ return action.sessionId + ':' + action.mode + ':' + String(action.armedAt)
27
+ }
28
+
29
+ function navigationBottom(): number {
30
+ for (const selector of ['header', '[role="banner"]']) {
31
+ const element = document.querySelector(selector)
32
+ if (element === null) continue
33
+ const rect = element.getBoundingClientRect()
34
+ if (rect.height > 0 && rect.top <= 8) return Math.round(rect.bottom)
35
+ }
36
+ return FALLBACK_TOP
37
+ }
38
+
39
+ function placeBelowNavigation(host: HTMLDivElement): void {
40
+ // A header that spans the whole app would otherwise put the fixed card below
41
+ // the viewport. Use a bounded nav measurement and a fixed floor; the card is
42
+ // always visibly below the top bar.
43
+ const measured = navigationBottom()
44
+ const nav = measured > 0 && measured < 240 ? measured : 56
45
+ host.style.top = String(Math.max(nav + 48, MIN_TOP)) + 'px'
46
+ }
47
+
48
+ function ensureHost(): HTMLDivElement | undefined {
49
+ if (typeof document === 'undefined') return undefined
50
+ const existing = document.getElementById(HOST_ID)
51
+ if (existing !== null) return existing as HTMLDivElement
52
+ const host = document.createElement('div')
53
+ host.id = HOST_ID
54
+ host.setAttribute('role', 'status')
55
+ host.setAttribute('aria-live', 'polite')
56
+ host.style.cssText = [
57
+ 'position:fixed',
58
+ 'top:56px',
59
+ 'right:12px',
60
+ 'z-index:10000',
61
+ 'display:flex',
62
+ 'flex-direction:column',
63
+ 'gap:8px',
64
+ 'max-width:min(380px,calc(100vw - 24px))',
65
+ 'pointer-events:none',
66
+ ].join(';')
67
+ placeBelowNavigation(host)
68
+ document.body.appendChild(host)
69
+ return host
70
+ }
71
+
72
+ function card(action: GlobalSessionEndAction, dismiss: () => void): HTMLDivElement {
73
+ const element = document.createElement('div')
74
+ element.style.cssText = [
75
+ 'pointer-events:auto',
76
+ 'display:flex',
77
+ 'align-items:flex-start',
78
+ 'gap:9px',
79
+ 'padding:10px 11px',
80
+ 'border-radius:12px',
81
+ 'border:1px solid var(--dsw-alias-state-warn-primary, rgba(227,179,65,.65))',
82
+ 'background:var(--dsw-alias-bg-layer-2, #1f2023)',
83
+ 'color:var(--dsw-alias-label-primary, #f2f3f5)',
84
+ 'box-shadow:var(--dsw-elevation-prominent, 0 8px 28px rgba(0,0,0,.35))',
85
+ 'font-size:12px',
86
+ 'line-height:1.45',
87
+ ].join(';')
88
+
89
+ const dot = document.createElement('span')
90
+ dot.setAttribute('aria-hidden', 'true')
91
+ dot.style.cssText = 'flex:none;width:8px;height:8px;margin-top:4px;border-radius:50%;background:var(--dsw-alias-state-warn-primary,#e3b341)'
92
+
93
+ const body = document.createElement('div')
94
+ body.style.cssText = 'flex:1;min-width:0'
95
+ const title = document.createElement('div')
96
+ title.textContent = globalNoticeText(action)
97
+ title.style.cssText = 'font-weight:600'
98
+ const hint = document.createElement('div')
99
+ hint.textContent = action.waiting
100
+ ? '正在等待任务结束' + (action.runningAgents + action.runningJobs > 0
101
+ ? ' · ' + String(action.runningAgents) + ' 个会话 / ' + String(action.runningJobs) + ' 个任务'
102
+ : '')
103
+ : '本轮最终回复后执行'
104
+ hint.style.cssText = 'margin-top:2px;color:var(--dsw-alias-label-secondary,#a8adb7);font-size:11px'
105
+ body.append(title, hint)
106
+
107
+ const close = document.createElement('button')
108
+ close.type = 'button'
109
+ close.setAttribute('aria-label', '关闭提示')
110
+ close.textContent = '×'
111
+ close.style.cssText = [
112
+ 'flex:none',
113
+ 'border:0',
114
+ 'background:transparent',
115
+ 'color:var(--dsw-alias-label-tertiary,#8b919c)',
116
+ 'cursor:pointer',
117
+ 'font-size:16px',
118
+ 'line-height:1',
119
+ 'padding:0 2px',
120
+ ].join(';')
121
+ close.addEventListener('click', dismiss)
122
+
123
+ element.append(dot, body, close)
124
+ return element
125
+ }
126
+
127
+ export function startSessionEndGlobalNotice(): () => void {
128
+ if (typeof document === 'undefined' || typeof fetch !== 'function') return () => {}
129
+ let stopped = false
130
+ let timer: ReturnType<typeof setInterval> | undefined
131
+ const dismissed = new Set<string>()
132
+
133
+ const clear = (): void => {
134
+ document.getElementById(HOST_ID)?.remove()
135
+ }
136
+
137
+ const render = (actions: GlobalSessionEndAction[]): void => {
138
+ const active = new Set(actions.map(globalNoticeKey))
139
+ for (const key of dismissed) if (!active.has(key)) dismissed.delete(key)
140
+ const visible = actions.filter(action => !dismissed.has(globalNoticeKey(action)))
141
+ if (visible.length === 0) {
142
+ clear()
143
+ return
144
+ }
145
+ const host = ensureHost()
146
+ if (host === undefined) return
147
+ placeBelowNavigation(host)
148
+ host.replaceChildren(...visible.map(action => card(action, () => {
149
+ dismissed.add(globalNoticeKey(action))
150
+ render(actions)
151
+ })))
152
+ }
153
+
154
+ const poll = async (): Promise<void> => {
155
+ try {
156
+ const response = await fetch(SESSION_END_API.global, {
157
+ method: 'POST',
158
+ credentials: 'same-origin',
159
+ cache: 'no-store',
160
+ })
161
+ if (stopped) return
162
+ const body = await response.json() as { ok?: boolean; actions?: GlobalSessionEndAction[] }
163
+ if (stopped || body.ok !== true || !Array.isArray(body.actions)) return
164
+ render(body.actions.filter(action => action.requestedBy === 'ai'))
165
+ } catch {
166
+ /* a transient poll failure leaves the last notice in place */
167
+ }
168
+ }
169
+
170
+ const onResize = (): void => {
171
+ const host = document.getElementById(HOST_ID) as HTMLDivElement | null
172
+ if (host !== null) placeBelowNavigation(host)
173
+ }
174
+ window.addEventListener('resize', onResize)
175
+ void poll()
176
+ timer = setInterval(() => { void poll() }, 2000)
177
+ return () => {
178
+ stopped = true
179
+ if (timer !== undefined) clearInterval(timer)
180
+ window.removeEventListener('resize', onResize)
181
+ clear()
182
+ }
183
+ }
@@ -120,6 +120,10 @@ export function SettingsSection({ t }: SettingsSectionProps) {
120
120
  <span style={pageStyles.componentName}>{t('page.components.restart')}</span>
121
121
  <span style={pageStyles.componentHint}>{t('page.components.restartHint')}</span>
122
122
  </div>
123
+ <div style={pageStyles.componentRow}>
124
+ <span style={pageStyles.componentName}>{t('page.components.authCookie')}</span>
125
+ <span style={pageStyles.componentHint}>{t('page.components.authCookieHint')}</span>
126
+ </div>
123
127
  <div style={pageStyles.componentRow}>
124
128
  <span style={pageStyles.componentName}>{t('page.components.sessionEnd')}</span>
125
129
  <span style={pageStyles.componentHint}>{t('page.components.sessionEndHint')}</span>
@@ -3,6 +3,7 @@ import type {} from '@deepseek-ai/dsh-client-locale/client'
3
3
  import type {} from '@deepseek-ai/dsh-client-ui-renderer/client'
4
4
  import type {} from '@deepseek-ai/dsh-client-ui-settings/client'
5
5
  import type {} from '@deepseek-ai/dsh-client-ui-slots'
6
+ import { AUTH_COOKIE_API } from '../api.ts'
6
7
  import { AppearanceScheduleRow } from './AppearanceScheduleRow.tsx'
7
8
  import { FallbackRestartRow } from './FallbackRestartRow.tsx'
8
9
  import { SessionEndControl } from './SessionEndControl.tsx'
@@ -12,6 +13,7 @@ import { en, zh, type McviseronKey } from './locales.ts'
12
13
  import { sectionPresence } from './section-presence.ts'
13
14
 
14
15
  const NS = 'mcviseron'
16
+ let authCookiePruneStarted = false
15
17
 
16
18
  declare module '@deepseek-ai/dsh-client-ui-slots' {
17
19
  interface LocaleNamespaceMap {
@@ -77,6 +79,19 @@ function registerSafely(
77
79
  * @param ctx - client cordis context.
78
80
  */
79
81
  export function apply(ctx: ClientContext): void {
82
+ if (!authCookiePruneStarted) {
83
+ authCookiePruneStarted = true
84
+ try {
85
+ void fetch(AUTH_COOKIE_API.prune, {
86
+ method: 'POST',
87
+ credentials: 'same-origin',
88
+ cache: 'no-store',
89
+ }).catch(() => {})
90
+ } catch {
91
+ /* a shell without fetch still loads the rest of the plugin */
92
+ }
93
+ }
94
+
80
95
  try {
81
96
  ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'mcviseron: dictionaries')
82
97
  } catch (error) {
@@ -73,6 +73,11 @@ export const zh = {
73
73
  'form.failed': '保存失败',
74
74
  'form.unavailable': '无法读取插件设置:请确认 profile 中的插件条目 id 为 mcviseron',
75
75
  'form.autoSave': '修改后自动保存',
76
+ 'form.autoReview.reviewGuard': '裁剪 Auto review 上下文',
77
+ 'form.autoReview.reviewGuardHint': '只压缩 reviewer 的历史;当前动作、工程约束和人类指令保留,避免长会话把审查模型撑爆',
78
+ 'form.autoReview.reviewMaxHistory': '审查历史上限(字符)',
79
+ 'form.autoReview.reviewMaxHistoryHint': '默认 120000;超出后旧工具调用会折叠成摘要',
80
+ 'form.autoReview.reviewKeepRecent': '保留最近历史条数',
76
81
  'form.autoReview.translate': '翻译审批理由',
77
82
  'form.autoReview.translateHint': '英文审查理由会附上中文翻译,并写入审批事件;转手动后被拒时,自动审查理由会作为 notice 交回 AI',
78
83
  'form.autoReview.keepPreset': '退出时保持权限预设',
@@ -108,6 +113,8 @@ export const zh = {
108
113
  'page.tab.sessionEnd': '会话后动作',
109
114
  'page.sessionEnd.title': '会话后动作',
110
115
  'page.sessionEnd.description': '本轮最终回复完整显示后执行一次动作;重启会等待所有会话与后台任务结束,设置页的重启不受此约束。',
116
+ 'page.components.authCookie': '认证 cookie 清理',
117
+ 'page.components.authCookieHint': '自动运行,无设置',
111
118
  'page.components.sessionEnd': '会话后动作',
112
119
  'page.components.sessionEndHint': '输入框左侧的「会话后重启」下拉',
113
120
  'form.sessionEnd.enabled': '启用会话后动作',
@@ -197,6 +204,11 @@ export const en = {
197
204
  'form.failed': 'Save failed',
198
205
  'form.unavailable': 'Cannot read the plugin settings: check that the profile entry id is mcviseron',
199
206
  'form.autoSave': 'Changes save automatically',
207
+ 'form.autoReview.reviewGuard': 'Trim the Auto-review context',
208
+ 'form.autoReview.reviewGuardHint': 'Compacts only the reviewer history; the pending action, project constraints and human instructions stay',
209
+ 'form.autoReview.reviewMaxHistory': 'Reviewer history limit (chars)',
210
+ 'form.autoReview.reviewMaxHistoryHint': 'Defaults to 120000; older tool calls collapse into a summary',
211
+ 'form.autoReview.reviewKeepRecent': 'Recent entries to keep',
200
212
  'form.autoReview.translate': 'Translate the approval reason',
201
213
  'form.autoReview.translateHint': 'Appends a Chinese translation to the reviewer note and writes it into the approval event; a manual rejection returns the auto-review reason to the AI',
202
214
  'form.autoReview.keepPreset': 'Keep the permission preset on shutdown',
@@ -232,6 +244,8 @@ export const en = {
232
244
  'page.tab.sessionEnd': 'After-session action',
233
245
  'page.sessionEnd.title': 'After-session action',
234
246
  'page.sessionEnd.description': 'One action after the final reply is fully displayed. A restart waits for every running conversation and background job; the Settings restart button is not delayed.',
247
+ 'page.components.authCookie': 'Auth-cookie cleanup',
248
+ 'page.components.authCookieHint': 'Runs automatically; no settings',
235
249
  'page.components.sessionEnd': 'After-session action',
236
250
  'page.components.sessionEndHint': 'The “Restart after session” dropdown left of the composer',
237
251
  'form.sessionEnd.enabled': 'Enable after-session actions',
@@ -1,5 +1,6 @@
1
1
  import { randomUUID } from 'node:crypto'
2
2
  import type { Context } from '@deepseek-ai/cordis'
3
+ import { installReviewContextGuard, type ReviewContextSettings } from './review-context.ts'
3
4
  import {
4
5
  chineseKey,
5
6
  cleanTranslation,
@@ -42,6 +43,7 @@ const FIBER_STATE_ACTIVE = 2
42
43
  /** Settings actually used at runtime. */
43
44
  export interface AutoReviewSettings extends TranslationSettings {
44
45
  keepPresetGuard: boolean
46
+ reviewContext: ReviewContextSettings
45
47
  }
46
48
 
47
49
  /** Service objects already guarded in this process (survives plugin reloads). */
@@ -87,6 +89,11 @@ export function normalizeConfig(config?: unknown): AutoReviewSettings {
87
89
  maxChars: numberSetting(source, 'translateMaxChars', 4000, 100, 20000),
88
90
  provider: stringSetting(source, 'translateProvider', ''),
89
91
  model: stringSetting(source, 'translateModel', ''),
92
+ reviewContext: {
93
+ enabled: boolSetting(source, 'reviewContextGuard', true),
94
+ maxHistoryChars: numberSetting(source, 'reviewMaxHistoryChars', 120000, 20000, 600000),
95
+ keepRecentEntries: numberSetting(source, 'reviewKeepRecentEntries', 16, 4, 64),
96
+ },
90
97
  }
91
98
  }
92
99
 
@@ -410,6 +417,7 @@ function installApprovalTranslation(ctx: Context, settings: AutoReviewSettings,
410
417
  export function installAutoReview(ctx: Context, config?: unknown): void {
411
418
  const settings = normalizeConfig(config)
412
419
  if (settings.keepPresetGuard) installPresetGuard(ctx)
420
+ if (settings.reviewContext.enabled) installReviewContextGuard(ctx, settings.reviewContext)
413
421
  if (settings.enabled) {
414
422
  const relay = createRejectionRelay()
415
423
  installRejectionRelay(ctx, relay)