@shuind/dsh-codex-harness 0.2.32-dsh-v0.2.2-rc.1 → 0.3.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/CHANGELOG.md +64 -0
- package/README.md +37 -59
- package/RELEASE.md +1 -1
- package/cordis.patch.yml +42 -11
- package/docs/preset-library.md +6 -12
- package/docs/tool-policy-benchmark.json +89 -89
- package/docs/tool-policy.md +11 -7
- package/lib/client.js +3780 -2950
- package/lib/compact-command.js +416 -0
- package/lib/compaction.js +129 -15
- package/lib/hybrid-executor.js +1196 -0
- package/lib/index.js +3554 -2841
- package/lib/preferences.js +17 -11
- package/lib/tool-policy.js +1930 -1743
- package/lib/typert.js +49 -89
- package/lib/types/client/activity.js +4 -3
- package/lib/types/client/desktop.d.ts +26 -2
- package/lib/types/client/desktop.js +143 -35
- package/lib/types/client/index.d.ts +136 -129
- package/lib/types/client/index.js +92 -466
- package/lib/types/client/policy-drafts.d.ts +1 -1
- package/lib/types/client/policy-locale.d.ts +260 -0
- package/lib/types/client/policy-locale.js +357 -0
- package/lib/types/client/preset-manager.d.ts +33 -15
- package/lib/types/client/preset-manager.js +220 -215
- package/lib/types/client/preset-requests.d.ts +2 -2
- package/lib/types/client/tool-policy.d.ts +6 -93
- package/lib/types/client/tool-policy.js +85 -143
- package/lib/types/contracts/preset-editor-schema.d.ts +78 -0
- package/lib/types/contracts/preset-editor-schema.js +95 -0
- package/lib/types/{prompt.js → contracts/prompt.js} +9 -5
- package/lib/types/{settings.d.ts → contracts/settings.d.ts} +8 -1
- package/lib/types/{settings.js → contracts/settings.js} +19 -3
- package/lib/types/{tool-policy-contract.d.ts → contracts/tool-policy-contract.d.ts} +9 -6
- package/lib/types/{tool-policy-contract.js → contracts/tool-policy-contract.js} +9 -2
- package/lib/types/contracts/ui-contracts.d.ts +92 -0
- package/lib/types/contracts/ui-contracts.js +83 -0
- package/lib/types/{client/entry.d.ts → entries/client.d.ts} +2 -2
- package/lib/types/{client/entry.js → entries/client.js} +2 -4
- package/lib/types/{compact-command.d.ts → entries/compact-command.d.ts} +2 -0
- package/lib/types/entries/compact-command.js +176 -0
- package/lib/types/{compaction.d.ts → entries/compaction.d.ts} +12 -0
- package/lib/types/{compaction.js → entries/compaction.js} +43 -11
- package/lib/types/entries/hybrid-executor.d.ts +19 -0
- package/lib/types/entries/hybrid-executor.js +57 -0
- package/lib/types/entries/index.d.ts +66 -0
- package/lib/types/entries/index.js +192 -0
- package/lib/types/{preferences.d.ts → entries/preferences.d.ts} +1 -1
- package/lib/types/{preferences.js → entries/preferences.js} +1 -1
- package/lib/types/entries/tool-policy.d.ts +97 -0
- package/lib/types/entries/tool-policy.js +158 -0
- package/lib/types/entries/typert.host.d.ts +23 -0
- package/lib/types/entries/typert.host.js +24 -0
- package/lib/types/hybrid/codex-hybrid-executor.d.ts +44 -0
- package/lib/types/hybrid/codex-hybrid-executor.js +257 -0
- package/lib/types/hybrid/hybrid-sdk.d.ts +13 -0
- package/lib/types/hybrid/hybrid-sdk.js +196 -0
- package/lib/types/hybrid/program-calls.d.ts +28 -0
- package/lib/types/hybrid/program-calls.js +193 -0
- package/lib/types/hybrid/subcall-scheduler.d.ts +90 -0
- package/lib/types/hybrid/subcall-scheduler.js +343 -0
- package/lib/types/policy/deferred-tools.d.ts +42 -0
- package/lib/types/policy/deferred-tools.js +264 -0
- package/lib/types/policy/overlay-installer.d.ts +12 -0
- package/lib/types/policy/overlay-installer.js +179 -0
- package/lib/types/policy/rule-resolver.d.ts +94 -0
- package/lib/types/policy/rule-resolver.js +114 -0
- package/lib/types/{tool-capabilities.d.ts → policy/tool-capabilities.d.ts} +3 -2
- package/lib/types/{tool-capabilities.js → policy/tool-capabilities.js} +6 -2
- package/lib/types/{activity.d.ts → presets/activity.d.ts} +2 -4
- package/lib/types/{activity.js → presets/activity.js} +2 -14
- package/lib/types/{desktop-preset.d.ts → presets/desktop-preset.d.ts} +3 -1
- package/lib/types/{desktop-preset.js → presets/desktop-preset.js} +6 -2
- package/lib/types/presets/preset-editor.d.ts +47 -0
- package/lib/types/presets/preset-editor.js +81 -0
- package/lib/types/{preset-prompt-catalog.d.ts → presets/preset-prompt-catalog.d.ts} +3 -1
- package/lib/types/{preset-prompt-catalog.js → presets/preset-prompt-catalog.js} +27 -4
- package/lib/types/{preset-tool-catalog.d.ts → presets/preset-tool-catalog.d.ts} +1 -1
- package/lib/types/{preset-tool-catalog.js → presets/preset-tool-catalog.js} +11 -4
- package/lib/types/presets/runtime-enhancements.d.ts +45 -0
- package/lib/types/presets/runtime-enhancements.js +349 -0
- package/lib/types/presets/small-window-compaction.d.ts +15 -0
- package/lib/types/presets/small-window-compaction.js +121 -0
- package/lib/types/responses/compact-checkpoint.d.ts +27 -0
- package/lib/types/responses/compact-checkpoint.js +257 -0
- package/lib/types/responses/fetch-transport.d.ts +16 -0
- package/lib/types/responses/fetch-transport.js +257 -0
- package/lib/types/responses/remote-compact.d.ts +13 -0
- package/lib/types/responses/remote-compact.js +319 -0
- package/lib/types/responses/sse-diagnostics.d.ts +9 -0
- package/lib/types/responses/sse-diagnostics.js +157 -0
- package/lib/types/responses/wire-rewrite.d.ts +35 -0
- package/lib/types/responses/wire-rewrite.js +237 -0
- package/lib/types/tools/exec-output.d.ts +58 -0
- package/lib/types/tools/exec-output.js +173 -0
- package/lib/types/tools/exec-plan-tools.d.ts +37 -0
- package/lib/types/tools/exec-plan-tools.js +265 -0
- package/lib/types/tools/exec-runner.d.ts +21 -0
- package/lib/types/tools/exec-runner.js +385 -0
- package/lib/types/tools/patch-tool.d.ts +16 -0
- package/lib/types/tools/patch-tool.js +258 -0
- package/lib/types/{patch.d.ts → tools/patch.d.ts} +1 -1
- package/lib/types/{patch.js → tools/patch.js} +96 -21
- package/locale/hybrid-executor/en.json +6 -0
- package/locale/hybrid-executor/zh.json +6 -0
- package/package.json +211 -289
- package/presets/{codex-collaboration → codex-hybrid}/agent.cordis.yml +45 -48
- package/presets/codex-hybrid/preset.yml +3 -0
- package/scripts/benchmark-tool-policy.mjs +3 -3
- package/scripts/build-preset.mjs +5 -5
- package/src/client/activity.ts +4 -3
- package/src/client/desktop.tsx +165 -51
- package/src/client/index.tsx +128 -709
- package/src/client/policy-drafts.ts +1 -1
- package/src/client/policy-locale.ts +362 -0
- package/src/client/preset-manager.tsx +331 -236
- package/src/client/preset-requests.ts +2 -2
- package/src/client/tool-policy.tsx +225 -203
- package/src/contracts/preset-editor-schema.ts +110 -0
- package/src/{prompt.ts → contracts/prompt.ts} +9 -5
- package/src/{settings.ts → contracts/settings.ts} +27 -3
- package/src/{tool-policy-contract.ts → contracts/tool-policy-contract.ts} +24 -7
- package/src/contracts/ui-contracts.ts +173 -0
- package/src/{client/entry.tsx → entries/client.tsx} +2 -4
- package/src/entries/compact-command.ts +256 -0
- package/src/{compaction.ts → entries/compaction.ts} +47 -19
- package/src/entries/hybrid-executor.ts +76 -0
- package/src/entries/index.ts +298 -0
- package/src/{preferences.ts → entries/preferences.ts} +1 -1
- package/src/entries/tool-policy.ts +162 -0
- package/src/entries/typert.host.ts +29 -0
- package/src/hybrid/codex-hybrid-executor.ts +310 -0
- package/src/hybrid/hybrid-sdk.ts +217 -0
- package/src/hybrid/program-calls.ts +202 -0
- package/src/hybrid/subcall-scheduler.ts +446 -0
- package/src/policy/deferred-tools.ts +331 -0
- package/src/policy/overlay-installer.ts +191 -0
- package/src/policy/rule-resolver.ts +128 -0
- package/src/{tool-capabilities.ts → policy/tool-capabilities.ts} +16 -4
- package/src/{activity.ts → presets/activity.ts} +4 -16
- package/src/{desktop-preset.ts → presets/desktop-preset.ts} +7 -2
- package/src/presets/preset-editor.ts +101 -0
- package/src/{preset-prompt-catalog.ts → presets/preset-prompt-catalog.ts} +35 -5
- package/src/{preset-tool-catalog.ts → presets/preset-tool-catalog.ts} +12 -5
- package/src/presets/runtime-enhancements.ts +415 -0
- package/src/presets/small-window-compaction.ts +166 -0
- package/src/responses/compact-checkpoint.ts +264 -0
- package/src/responses/fetch-transport.ts +290 -0
- package/src/responses/remote-compact.ts +393 -0
- package/src/responses/sse-diagnostics.ts +156 -0
- package/src/responses/wire-rewrite.ts +261 -0
- package/src/tools/exec-output.ts +211 -0
- package/src/tools/exec-plan-tools.ts +307 -0
- package/src/tools/exec-runner.ts +445 -0
- package/src/tools/patch-tool.ts +331 -0
- package/src/{patch.ts → tools/patch.ts} +90 -20
- package/tsdown.config.ts +8 -8
- package/lib/installer.js +0 -281
- package/lib/invariant.js +0 -23
- package/lib/types/activity-types.d.ts +0 -6
- package/lib/types/activity-types.js +0 -3
- package/lib/types/client/preset-copy.d.ts +0 -43
- package/lib/types/client/preset-copy.js +0 -83
- package/lib/types/client/session.d.ts +0 -6
- package/lib/types/client/session.js +0 -9
- package/lib/types/compact-command.js +0 -79
- package/lib/types/context.d.ts +0 -8
- package/lib/types/context.js +0 -14
- package/lib/types/exec.d.ts +0 -50
- package/lib/types/exec.js +0 -491
- package/lib/types/host-settings.d.ts +0 -4
- package/lib/types/host-settings.js +0 -13
- package/lib/types/index.d.ts +0 -113
- package/lib/types/index.js +0 -851
- package/lib/types/installer.d.ts +0 -27
- package/lib/types/installer.js +0 -155
- package/lib/types/invariant.d.ts +0 -16
- package/lib/types/invariant.js +0 -22
- package/lib/types/preset-contract.d.ts +0 -69
- package/lib/types/preset-contract.js +0 -22
- package/lib/types/preset-editor-remote.d.ts +0 -32
- package/lib/types/preset-editor-remote.js +0 -41
- package/lib/types/preset-editor.d.ts +0 -74
- package/lib/types/preset-editor.js +0 -587
- package/lib/types/preset-prompt-catalog-schema.d.ts +0 -16
- package/lib/types/preset-prompt-catalog-schema.js +0 -11
- package/lib/types/preset-prompt-contract.d.ts +0 -22
- package/lib/types/preset-prompt-contract.js +0 -3
- package/lib/types/preset-tool-catalog-schema.d.ts +0 -38
- package/lib/types/preset-tool-catalog-schema.js +0 -28
- package/lib/types/prompt-sections.d.ts +0 -15
- package/lib/types/prompt-sections.js +0 -29
- package/lib/types/remote.d.ts +0 -40
- package/lib/types/remote.js +0 -698
- package/lib/types/tool-policy.d.ts +0 -171
- package/lib/types/tool-policy.js +0 -367
- package/lib/types/typert.host.d.ts +0 -47
- package/lib/types/typert.host.js +0 -109
- package/presets/codex-collaboration/preset.yml +0 -3
- package/src/activity-types.ts +0 -7
- package/src/client/preset-copy.ts +0 -83
- package/src/client/session.ts +0 -11
- package/src/compact-command.ts +0 -112
- package/src/context.ts +0 -15
- package/src/exec.ts +0 -570
- package/src/host-settings.ts +0 -17
- package/src/index.ts +0 -1097
- package/src/installer.ts +0 -172
- package/src/invariant.ts +0 -34
- package/src/preset-contract.ts +0 -85
- package/src/preset-editor-remote.ts +0 -41
- package/src/preset-editor.ts +0 -502
- package/src/preset-prompt-catalog-schema.ts +0 -10
- package/src/preset-prompt-contract.ts +0 -21
- package/src/preset-tool-catalog-schema.ts +0 -28
- package/src/prompt-sections.ts +0 -33
- package/src/remote.ts +0 -748
- package/src/tool-policy.ts +0 -388
- package/src/typert.host.ts +0 -119
- /package/lib/types/{prompt.d.ts → contracts/prompt.d.ts} +0 -0
|
@@ -1,271 +1,105 @@
|
|
|
1
|
-
|
|
2
|
-
import
|
|
1
|
+
/** Read-only preset definition viewer and composer context-window control for Harness 0.2.2+. */
|
|
2
|
+
import { useCallback, useEffect, useId, useRef, useState, useSyncExternalStore } from 'react'
|
|
3
|
+
import { createPortal } from 'react-dom'
|
|
4
|
+
import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots'
|
|
3
5
|
import type { RemoteResult, TypertClientRemote } from '@deepseek-ai/dsh-typert-protocol'
|
|
4
|
-
import
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
6
|
+
import {
|
|
7
|
+
contextPresetsForBounds,
|
|
8
|
+
formatCompactTokens,
|
|
9
|
+
OPENAI_CODEX_MODEL_CATALOG_PATH,
|
|
10
|
+
OPENAI_CODEX_MODEL_LIMITS,
|
|
11
|
+
OPENAI_CODEX_PROVIDER,
|
|
12
|
+
parseCustomContextInput,
|
|
13
|
+
resolveContextWindowBounds,
|
|
14
|
+
} from '../contracts/ui-contracts.ts'
|
|
15
|
+
import type {
|
|
16
|
+
CodexConnectScope,
|
|
17
|
+
ModelDirectorySnapshot,
|
|
18
|
+
ModelDirectoryStore,
|
|
19
|
+
PresetCatalog,
|
|
20
|
+
PresetDefinitionDocument,
|
|
21
|
+
} from '../contracts/ui-contracts.ts'
|
|
22
|
+
import type { PresetPromptCatalog, PresetToolCatalog } from '../contracts/tool-policy-contract.ts'
|
|
23
|
+
import { readPresetWithRetry } from './preset-requests.ts'
|
|
8
24
|
|
|
9
25
|
export interface PresetClientRemote extends TypertClientRemote {
|
|
10
26
|
codexPresetEditor: {
|
|
11
27
|
catalog(): Promise<RemoteResult<PresetCatalog>>
|
|
12
28
|
tools?(id: string): Promise<RemoteResult<PresetToolCatalog>>
|
|
13
29
|
prompts?(id: string): Promise<RemoteResult<PresetPromptCatalog>>
|
|
14
|
-
read(id: string): Promise<RemoteResult<
|
|
15
|
-
update(input: PresetEditorInput): Promise<RemoteResult<PresetEditorDocument>>
|
|
16
|
-
create(input: PresetCreateInput): Promise<RemoteResult<PresetEditorDocument>>
|
|
30
|
+
read(id: string): Promise<RemoteResult<PresetDefinitionDocument>>
|
|
17
31
|
}
|
|
18
32
|
}
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
33
|
+
|
|
34
|
+
export interface PresetManagerActions {
|
|
35
|
+
remote: PresetClientRemote
|
|
36
|
+
ready: Promise<void>
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const documentCache = new WeakMap<PresetManagerActions, Map<string, { value: PresetDefinitionDocument; time: number }>>()
|
|
40
|
+
|
|
23
41
|
function unwrap<T>(result: RemoteResult<T>): T {
|
|
24
42
|
if (result.ok) return result.value
|
|
25
43
|
throw new Error((result.error as unknown as { message?: string }).message ?? 'remote-request-failed')
|
|
26
44
|
}
|
|
27
|
-
|
|
28
|
-
if (!a || !b) return a === b
|
|
29
|
-
return a.name === b.name && a.description === b.description && a.systemPrompt === b.systemPrompt
|
|
30
|
-
&& a.inheritPrompt === b.inheritPrompt && a.codex === b.codex
|
|
31
|
-
&& JSON.stringify(a.codexOptions) === JSON.stringify(b.codexOptions)
|
|
32
|
-
&& JSON.stringify(a.promptSections) === JSON.stringify(b.promptSections)
|
|
33
|
-
}
|
|
45
|
+
|
|
34
46
|
const styles = `
|
|
35
|
-
.codex-preset-editor { display:grid; gap:
|
|
36
|
-
.codex-preset-editor
|
|
37
|
-
.codex-preset-editor
|
|
38
|
-
.codex-preset-editor input:not([type=checkbox]), .codex-preset-editor textarea, .codex-preset-editor select { box-sizing:border-box; width:100%; padding:8px; border:1px solid var(--dsw-alias-border-l2); border-radius:6px; background:var(--dsw-alias-bg-layer-2); color:inherit; font:inherit; }
|
|
39
|
-
.codex-preset-editor textarea { resize:vertical; line-height:1.5; }
|
|
40
|
-
.codex-preset-editor button { font:inherit; padding:6px 12px; border:1px solid var(--dsw-alias-border-l2); border-radius:6px; background:var(--dsw-alias-bg-layer-2); color:inherit; cursor:pointer; }
|
|
47
|
+
.codex-preset-editor { display:grid; gap:10px; min-width:0; font-size:13px; border:0.5px solid var(--dsw-alias-settings-card-stroke, var(--dsw-alias-border-l2)); border-radius:var(--dsw-radius-xl, 12px); background:var(--dsw-alias-settings-card-fill, var(--dsw-alias-bg-layer-1)); padding:12px 14px; }
|
|
48
|
+
.codex-preset-editor .codex-preset-editor-head { display:flex; align-items:center; justify-content:space-between; gap:8px; }
|
|
49
|
+
.codex-preset-editor button { font:inherit; font-size:12px; height:30px; padding:0 11px; border:0.5px solid var(--dsw-alias-border-l3, var(--dsw-alias-border-l2)); border-radius:var(--dsw-radius-md, 8px); background:var(--dsw-alias-bg-layer-2); color:inherit; cursor:pointer; }
|
|
41
50
|
.codex-preset-editor button:disabled { opacity:.5; cursor:default; }
|
|
42
|
-
.codex-preset-editor .pe-primary { background:var(--dsw-alias-label-primary); border-color:var(--dsw-alias-label-primary); color:var(--dsw-alias-bg-base); }
|
|
43
|
-
.codex-preset-editor .pe-block { display:grid; gap:9px; padding-top:12px; border-top:1px solid var(--dsw-alias-border-l2); }
|
|
44
|
-
.codex-preset-editor .pe-toggle { display:flex; align-items:flex-start; gap:9px; }
|
|
45
|
-
.codex-preset-editor .pe-toggle span { display:grid; gap:2px; }
|
|
46
51
|
.codex-preset-editor p { margin:0; font-size:12px; line-height:1.55; color:var(--dsw-alias-label-secondary); }
|
|
52
|
+
.codex-preset-editor pre { white-space:pre-wrap; overflow-wrap:anywhere; margin:0; padding:10px 12px; border-radius:var(--dsw-radius-md, 8px); background:var(--dsw-alias-bg-layer-2); font-size:12px; line-height:1.5; max-height:480px; overflow:auto; }
|
|
47
53
|
`
|
|
48
54
|
|
|
49
|
-
function optionToggle(
|
|
50
|
-
key: keyof CodexPresetOptions,
|
|
51
|
-
label: string,
|
|
52
|
-
hint: string,
|
|
53
|
-
options: CodexPresetOptions,
|
|
54
|
-
setOptions: (next: CodexPresetOptions) => void,
|
|
55
|
-
disabled: boolean,
|
|
56
|
-
) {
|
|
57
|
-
return <label className="pe-toggle" key={key}>
|
|
58
|
-
<input type="checkbox" checked={options[key]} disabled={disabled} onChange={event => setOptions({ ...options, [key]: event.target.checked })} />
|
|
59
|
-
<span><strong>{label}</strong><small>{hint}</small></span>
|
|
60
|
-
</label>
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
/** Presets are peers: choose one to edit, or make an editable copy first. */
|
|
64
|
-
export function PresetManagerCard({ presetManager, t, readOnly: inspectOnly = false }: Props) {
|
|
65
|
-
const [catalog, setCatalog] = useState(() => cachedPresetCatalog(presetManager))
|
|
66
|
-
const [selectedId, setSelectedId] = useState('')
|
|
67
|
-
const [original, setOriginal] = useState<PresetEditorDocument>()
|
|
68
|
-
const [draft, setDraft] = useState<PresetEditorDocument>()
|
|
69
|
-
const [sourceId, setSourceId] = useState('')
|
|
70
|
-
const [copyMode, setCopyMode] = useState(false)
|
|
71
|
-
const [codexEnabled, setCodexEnabled] = useState(false)
|
|
72
|
-
const [busy, setBusy] = useState(false)
|
|
73
|
-
const [error, setError] = useState('')
|
|
74
|
-
const [errorAction, setErrorAction] = useState<'catalog' | 'read' | 'save'>('read')
|
|
75
|
-
const [notice, setNotice] = useState('')
|
|
76
|
-
const alive = useRef(true)
|
|
77
|
-
const request = useRef(0)
|
|
78
|
-
if (!documentCache.has(presetManager)) documentCache.set(presetManager, new Map())
|
|
79
|
-
const cache = documentCache.get(presetManager)!
|
|
80
|
-
const remote = presetManager.remote.codexPresetEditor
|
|
81
|
-
const dirty = !!draft && (!original || !equalEditorState(draft, original) || codexEnabled !== draft.codex)
|
|
82
|
-
|
|
83
|
-
async function run(work: () => Promise<void>) {
|
|
84
|
-
setBusy(true); setError(''); setNotice('')
|
|
85
|
-
try { await presetManager.ready; if (alive.current) await work() }
|
|
86
|
-
catch (cause) { if (alive.current) setError(cause instanceof Error ? cause.message : String(cause)) }
|
|
87
|
-
finally { if (alive.current) setBusy(false) }
|
|
88
|
-
}
|
|
89
|
-
async function load(id: string, confirmDirty = true): Promise<void> {
|
|
90
|
-
if (!id) return
|
|
91
|
-
if (confirmDirty && dirty && !window.confirm(t('pmDiscard'))) return
|
|
92
|
-
const ticket = ++request.current
|
|
93
|
-
setSelectedId(id); setError(''); setNotice(''); setErrorAction('read')
|
|
94
|
-
const accept = (value: PresetEditorDocument) => {
|
|
95
|
-
if (!alive.current || ticket !== request.current) return
|
|
96
|
-
setSelectedId(id); setSourceId(id); setOriginal(value); setDraft(value)
|
|
97
|
-
setCopyMode(false); setCodexEnabled(value.codex)
|
|
98
|
-
}
|
|
99
|
-
const cached = cache.get(id)
|
|
100
|
-
if (cached && Date.now() - cached.time < 60_000) { accept(cached.value); return }
|
|
101
|
-
setDraft(undefined); setOriginal(undefined); setBusy(true)
|
|
102
|
-
try {
|
|
103
|
-
await presetManager.ready
|
|
104
|
-
const value = await readPresetWithRetry(() => remote.read(id).then(unwrap), () => alive.current && ticket === request.current)
|
|
105
|
-
cache.set(id, { value, time: Date.now() }); accept(value)
|
|
106
|
-
} catch (cause) { if (alive.current && ticket === request.current) setError(String(cause)) }
|
|
107
|
-
finally { if (alive.current && ticket === request.current) setBusy(false) }
|
|
108
|
-
}
|
|
109
|
-
async function refresh(): Promise<void> {
|
|
110
|
-
setErrorAction('catalog')
|
|
111
|
-
const value = await readPresetWithRetry(() => requestPresetCatalog(presetManager, true), () => alive.current)
|
|
112
|
-
if (!alive.current) return
|
|
113
|
-
setCatalog(value)
|
|
114
|
-
const current = value.presets.some(row => row.id === selectedId) ? selectedId
|
|
115
|
-
: value.presets.some(row => row.id === CODEX_DEFAULT_ID) ? CODEX_DEFAULT_ID : value.presets[0]?.id ?? ''
|
|
116
|
-
if (current) await load(current, false)
|
|
117
|
-
else { setSelectedId(''); setOriginal(undefined); setDraft(undefined) }
|
|
118
|
-
}
|
|
119
|
-
useEffect(() => {
|
|
120
|
-
alive.current = true
|
|
121
|
-
const cached = cachedPresetCatalog(presetManager)
|
|
122
|
-
if (cached === undefined) void run(refresh)
|
|
123
|
-
else if (!selectedId) void load(cached.presets.some(row => row.id === CODEX_DEFAULT_ID) ? CODEX_DEFAULT_ID : cached.presets[0]?.id ?? '', false)
|
|
124
|
-
return () => { alive.current = false }
|
|
125
|
-
}, [presetManager])
|
|
126
|
-
useEffect(() => {
|
|
127
|
-
if (!dirty) return
|
|
128
|
-
const guard = (event: BeforeUnloadEvent) => { event.preventDefault(); event.returnValue = '' }
|
|
129
|
-
window.addEventListener('beforeunload', guard)
|
|
130
|
-
return () => window.removeEventListener('beforeunload', guard)
|
|
131
|
-
}, [dirty])
|
|
132
|
-
function patch(value: Partial<PresetEditorDocument>) { if (draft) setDraft({ ...draft, ...value }) }
|
|
133
|
-
function beginCopy(): void {
|
|
134
|
-
if (inspectOnly || !draft || !sourceId) return
|
|
135
|
-
setCopyMode(true); setCodexEnabled(draft.codex)
|
|
136
|
-
setOriginal({ ...draft })
|
|
137
|
-
setDraft({ ...draft, id: '', revision: '', editable: true, name: `${draft.name} · ${t('pmCustom')}` })
|
|
138
|
-
}
|
|
139
|
-
function save(): void {
|
|
140
|
-
if (inspectOnly || !draft || busy || !draft.name.trim()) return
|
|
141
|
-
setErrorAction('save')
|
|
142
|
-
void run(async () => {
|
|
143
|
-
const options = codexEnabled ? draft.codexOptions : undefined
|
|
144
|
-
const payload = { name: draft.name, description: draft.description, systemPrompt: draft.systemPrompt,
|
|
145
|
-
promptSections: draft.promptSections.filter(section => section.editable && (codexEnabled || section.id !== 'codex:base')),
|
|
146
|
-
inheritPrompt: draft.inheritPrompt, enableCodex: codexEnabled, ...(options === undefined ? {} : { codexOptions: options }) }
|
|
147
|
-
const value = unwrap(await (copyMode
|
|
148
|
-
? remote.create({ ...payload, sourceId })
|
|
149
|
-
: remote.update({ ...payload, id: draft.id, revision: draft.revision })))
|
|
150
|
-
if (!alive.current) return
|
|
151
|
-
setSelectedId(value.id); setSourceId(value.id); setOriginal(value); setDraft(value)
|
|
152
|
-
cache.set(value.id, { value, time: Date.now() })
|
|
153
|
-
setCopyMode(false); setCodexEnabled(value.codex); setNotice(t('peSaved'))
|
|
154
|
-
if (catalog) {
|
|
155
|
-
const row = { id: value.id, name: value.name, description: value.description, editable: value.editable,
|
|
156
|
-
isDefault: catalog.presets.find(item => item.id === value.id)?.isDefault ?? false }
|
|
157
|
-
const presets = catalog.presets.some(item => item.id === value.id)
|
|
158
|
-
? catalog.presets.map(item => item.id === value.id ? row : item) : [...catalog.presets, row]
|
|
159
|
-
cachePresetCatalog(presetManager, { ...catalog, presets }); setCatalog({ ...catalog, presets })
|
|
160
|
-
}
|
|
161
|
-
})
|
|
162
|
-
}
|
|
163
|
-
const selectedRow = catalog?.presets.find(row => row.id === selectedId)
|
|
164
|
-
const readOnly = inspectOnly || (!!draft && !draft.editable && !copyMode)
|
|
165
|
-
const options = draft?.codexOptions
|
|
166
|
-
return <section className="codex-preset-editor" aria-label={t('peTitle')} aria-busy={busy}>
|
|
167
|
-
<style>{styles}</style>
|
|
168
|
-
<div className="pe-row" style={{ justifyContent:'space-between' }}>
|
|
169
|
-
<strong>{t('peTitle')}</strong>
|
|
170
|
-
<button type="button" disabled={busy} onClick={() => { if (dirty && !window.confirm(t('pmDiscard'))) return; cache.clear(); void run(refresh) }}>{t('pmRefresh')}</button>
|
|
171
|
-
</div>
|
|
172
|
-
<p>{t('peHierarchy')}</p>
|
|
173
|
-
<label>{t('peSelect')}<select value={selectedId} disabled={busy || !catalog} onChange={event => { void load(event.target.value) }}>
|
|
174
|
-
<option value="">{t('peSelectPlaceholder')}</option>
|
|
175
|
-
{catalog?.presets.map(row => <option key={row.id} value={row.id}>{row.name}{row.editable ? '' : ` · ${t('pmBuiltIn')}`}</option>)}
|
|
176
|
-
</select></label>
|
|
177
|
-
{selectedRow && <p>{selectedRow.editable ? t('peEditable') : t(catalog?.authorable ? 'peBuiltinEdit' : 'pmRegistryReadOnly')}</p>}
|
|
178
|
-
{error && <div role="alert">
|
|
179
|
-
<p>{errorAction !== 'save'
|
|
180
|
-
? t(isPresetConnectionError(error) ? 'peConnectionError' : 'peReadError')
|
|
181
|
-
: error.includes('preset-conflict') ? t('pmConflict') : error.includes('invalid-preset-yaml') ? t('pmYamlError') : t('pmSaveError')}</p>
|
|
182
|
-
{errorAction !== 'save' && <div className="pe-row">
|
|
183
|
-
<button type="button" disabled={busy} onClick={() => { if (errorAction === 'catalog' || !selectedId) void run(refresh); else { cache.delete(selectedId); void load(selectedId, false) } }}>{t('peRetryRead')}</button>
|
|
184
|
-
{!draft && isPresetConnectionError(error) && <button type="button" onClick={() => window.location.reload()}>{t('peReconnect')}</button>}
|
|
185
|
-
</div>}
|
|
186
|
-
<details><summary>{t('pmErrorDetails')}</summary><pre style={{ whiteSpace:'pre-wrap' }}>{error}</pre></details>
|
|
187
|
-
</div>}
|
|
188
|
-
{notice && <p role="status">{notice}</p>}
|
|
189
|
-
{busy && !draft && <p role="status">{t('peLoading')}</p>}
|
|
190
|
-
{draft && <>
|
|
191
|
-
<label>{t('pmName')}<input value={draft.name} maxLength={200} disabled={busy || readOnly} onChange={event => patch({ name:event.target.value })} /></label>
|
|
192
|
-
<label>{t('pmDescription')}<input value={draft.description} maxLength={4000} disabled={busy || readOnly} onChange={event => patch({ description:event.target.value })} /></label>
|
|
193
|
-
{!inspectOnly && !copyMode && catalog?.authorable && <button type="button" disabled={busy} onClick={beginCopy}>{t('peCreateCopy')}</button>}
|
|
194
|
-
<div className="pe-block">
|
|
195
|
-
<strong>{t('peSystemPrompt')}</strong>
|
|
196
|
-
<p>{t('peSectionsHint')}</p>
|
|
197
|
-
{draft.promptSections.map(section => <details key={section.id}>
|
|
198
|
-
<summary style={{ cursor: 'pointer', padding: '6px 0' }}>{section.label}{section.suppressed ? ` · ${t('peSuppressed')}` : ''}</summary>
|
|
199
|
-
{section.id === 'harness:source' && <p>{t('peDshSourcePrompt')}</p>}
|
|
200
|
-
{section.id === 'app:web-surface' && <p>{t('peDshWebPrompt')}</p>}
|
|
201
|
-
<textarea aria-label={section.label} rows={section.id === 'codex:base' ? 12 : 5} value={section.text}
|
|
202
|
-
disabled={busy || readOnly || !section.editable}
|
|
203
|
-
onChange={event => patch({ promptSections: draft.promptSections.map(item => item.id === section.id ? { ...item, text: event.target.value } : item),
|
|
204
|
-
...(section.id === 'codex:base' ? { systemPrompt: event.target.value, inheritPrompt: false } : {}) })} />
|
|
205
|
-
{section.suppressed ? <p>{t('peCompletePersona')}</p> : !section.editable && <p>{t('peDynamicPrompt')}</p>}
|
|
206
|
-
</details>)}
|
|
207
|
-
</div>
|
|
208
|
-
{!readOnly && <>
|
|
209
|
-
<div className="pe-block">
|
|
210
|
-
<strong>{t('peCodexSection')}</strong>
|
|
211
|
-
{!draft.codex && <label className="pe-toggle"><input type="checkbox" checked={codexEnabled} disabled={busy} onChange={event => {
|
|
212
|
-
const enabled = event.target.checked
|
|
213
|
-
setCodexEnabled(enabled)
|
|
214
|
-
if (enabled) {
|
|
215
|
-
const extras = [
|
|
216
|
-
{ id: 'codex:base', label: 'Codex 操作提示词', text: DEFAULT_CODEX_SYSTEM_PROMPT, editable: true },
|
|
217
|
-
]
|
|
218
|
-
patch({ promptSections: [...draft.promptSections.map(s => s.suppressed ? { ...s, suppressed: undefined, editable: true } : s), ...extras.filter(item => !draft.promptSections.some(s => s.id === item.id))] })
|
|
219
|
-
} else patch({ promptSections: draft.promptSections.filter(s => original?.promptSections.some(item => item.id === s.id)).map(s => {
|
|
220
|
-
const source = original?.promptSections.find(item => item.id === s.id)
|
|
221
|
-
return source?.suppressed ? { ...s, suppressed: true, editable: false } : s
|
|
222
|
-
}) })
|
|
223
|
-
}} /><span><strong>{t('peAddCodex')}</strong><small>{t('peAddCodexHint')}</small></span></label>}
|
|
224
|
-
{codexEnabled && options && <>
|
|
225
|
-
{optionToggle('hostedWebSearchEnabled', t('capabilityWebSearch'), t('capabilityWebSearchHint'), options, next => patch({ codexOptions: next }), busy)}
|
|
226
|
-
{optionToggle('remoteCompactionEnabled', t('capabilityCompaction'), t('capabilityCompactionHint'), options, next => patch({ codexOptions: next }), busy)}
|
|
227
|
-
{optionToggle('terminalToolsEnabled', t('capabilityTerminal'), t('capabilityTerminalHint'), options, next => patch({ codexOptions: next }), busy)}
|
|
228
|
-
{optionToggle('patchToolEnabled', t('capabilityPatch'), t('capabilityPatchHint'), options, next => patch({ codexOptions: next }), busy)}
|
|
229
|
-
{optionToggle('planToolEnabled', t('capabilityPlan'), t('capabilityPlanHint'), options, next => patch({ codexOptions: next }), busy)}
|
|
230
|
-
{optionToggle('promptEnabled', t('capabilityPrompt'), t('capabilityPromptHint'), options, next => patch({ codexOptions: next }), busy)}
|
|
231
|
-
<p>{t('peActivityGlobal')}</p>
|
|
232
|
-
</>}
|
|
233
|
-
</div>
|
|
234
|
-
<div className="pe-row"><button type="button" className="pe-primary" disabled={busy || !catalog?.authorable || !draft.name.trim() || !dirty} onClick={save}>{copyMode ? t('peSaveCopy') : t('pmSave')}</button>
|
|
235
|
-
{copyMode && <button type="button" disabled={busy} onClick={() => { void load(sourceId, false) }}>{t('pmCancel')}</button>}
|
|
236
|
-
{!copyMode && <button type="button" disabled={busy} onClick={() => { void load(draft.id, false) }}>{t('pmCancel')}</button>}
|
|
237
|
-
</div>
|
|
238
|
-
</>}
|
|
239
|
-
</>}
|
|
240
|
-
</section>
|
|
241
|
-
}
|
|
242
55
|
/** A fixed-ID declaration viewer: no second picker and no write/copy actions. */
|
|
243
|
-
export function PresetDefinitionCard({
|
|
244
|
-
|
|
56
|
+
export function PresetDefinitionCard({
|
|
57
|
+
presetManager,
|
|
58
|
+
id,
|
|
59
|
+
t,
|
|
60
|
+
}: { presetManager: PresetManagerActions; id: string } & PropsLocale<'codex'>) {
|
|
61
|
+
const [value, setValue] = useState<PresetDefinitionDocument>()
|
|
245
62
|
const [loading, setLoading] = useState(true)
|
|
246
63
|
const [error, setError] = useState('')
|
|
247
64
|
const request = useRef(0)
|
|
248
65
|
const alive = useRef(true)
|
|
66
|
+
|
|
249
67
|
async function load(refresh = false): Promise<void> {
|
|
250
68
|
const ticket = ++request.current
|
|
251
|
-
setLoading(true)
|
|
69
|
+
setLoading(true)
|
|
70
|
+
setError('')
|
|
252
71
|
try {
|
|
253
72
|
await presetManager.ready
|
|
254
|
-
const cache = documentCache.get(presetManager) ?? new Map<string, { value:
|
|
73
|
+
const cache = documentCache.get(presetManager) ?? new Map<string, { value: PresetDefinitionDocument; time: number }>()
|
|
255
74
|
documentCache.set(presetManager, cache)
|
|
256
75
|
const cached = cache.get(id)
|
|
257
|
-
const document = !refresh && cached && Date.now() - cached.time < 60_000
|
|
258
|
-
|
|
76
|
+
const document = !refresh && cached && Date.now() - cached.time < 60_000
|
|
77
|
+
? cached.value
|
|
78
|
+
: await readPresetWithRetry(
|
|
79
|
+
() => presetManager.remote.codexPresetEditor.read(id).then(unwrap),
|
|
80
|
+
() => alive.current && ticket === request.current,
|
|
81
|
+
)
|
|
259
82
|
if (document.id !== id) throw new Error('preset-document-mismatch')
|
|
260
83
|
cache.set(id, { value: document, time: Date.now() })
|
|
261
84
|
if (alive.current && ticket === request.current) setValue(document)
|
|
262
|
-
} catch (cause) {
|
|
263
|
-
|
|
85
|
+
} catch (cause) {
|
|
86
|
+
if (alive.current && ticket === request.current) {
|
|
87
|
+
setError(cause instanceof Error ? cause.message : String(cause))
|
|
88
|
+
}
|
|
89
|
+
} finally {
|
|
90
|
+
if (alive.current && ticket === request.current) setLoading(false)
|
|
91
|
+
}
|
|
264
92
|
}
|
|
93
|
+
|
|
265
94
|
useEffect(() => {
|
|
266
|
-
alive.current = true
|
|
267
|
-
|
|
95
|
+
alive.current = true
|
|
96
|
+
void load()
|
|
97
|
+
return () => {
|
|
98
|
+
alive.current = false
|
|
99
|
+
request.current++
|
|
100
|
+
}
|
|
268
101
|
}, [presetManager, id])
|
|
102
|
+
|
|
269
103
|
const shown = value?.id === id ? value : undefined
|
|
270
104
|
return <section className="codex-preset-editor" aria-label={t('settingsDefinition')} aria-busy={loading}>
|
|
271
105
|
<style>{styles}</style>
|
|
@@ -273,9 +107,270 @@ export function PresetDefinitionCard({ presetManager, id, t }: { presetManager:
|
|
|
273
107
|
<button type="button" disabled={loading} onClick={() => { void load(true) }}>{t('pmRefresh')}</button>
|
|
274
108
|
{loading && !shown && <p role="status">{t('peLoading')}</p>}
|
|
275
109
|
{error && <p role="alert">{t('peReadError')}</p>}
|
|
276
|
-
{shown &&
|
|
277
|
-
<
|
|
110
|
+
{shown && <>
|
|
111
|
+
<strong>{shown.name}</strong>
|
|
112
|
+
<p>{shown.description}</p>
|
|
113
|
+
<pre style={{ whiteSpace: 'pre-wrap', overflowWrap: 'anywhere', margin: 0 }}>{shown.composition}</pre>
|
|
278
114
|
</>}
|
|
279
115
|
</section>
|
|
280
116
|
}
|
|
281
|
-
|
|
117
|
+
|
|
118
|
+
const NOOP_SUBSCRIBE = () => () => {}
|
|
119
|
+
|
|
120
|
+
export const isGptModelName = (model: unknown): model is string =>
|
|
121
|
+
typeof model === 'string' && /(?:^|\/)(?:gpt|chatgpt)(?:[-_.]|\d|$)/i.test(model)
|
|
122
|
+
|
|
123
|
+
export function useModelDirectory(modelDirectory: ModelDirectoryStore | undefined): ModelDirectorySnapshot | undefined {
|
|
124
|
+
const subscribe = useCallback(
|
|
125
|
+
(listener: () => void) => modelDirectory !== undefined ? modelDirectory.subscribe(listener) : NOOP_SUBSCRIBE(),
|
|
126
|
+
[modelDirectory],
|
|
127
|
+
)
|
|
128
|
+
const getSnapshot = useCallback(() => modelDirectory?.getSnapshot(), [modelDirectory])
|
|
129
|
+
return useSyncExternalStore(subscribe, getSnapshot, getSnapshot)
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export function pillStyle(active: boolean, writable: boolean) {
|
|
133
|
+
return {
|
|
134
|
+
boxSizing: 'border-box' as const,
|
|
135
|
+
display: 'inline-flex',
|
|
136
|
+
alignItems: 'center',
|
|
137
|
+
gap: 5,
|
|
138
|
+
height: 28,
|
|
139
|
+
border: 0,
|
|
140
|
+
borderRadius: 7,
|
|
141
|
+
padding: '0 6px',
|
|
142
|
+
font: 'inherit',
|
|
143
|
+
fontSize: 12,
|
|
144
|
+
lineHeight: '20px',
|
|
145
|
+
whiteSpace: 'nowrap' as const,
|
|
146
|
+
color: active ? 'var(--dsw-static-blue-500)' : 'var(--dsw-alias-label-secondary)',
|
|
147
|
+
background: active ? 'var(--dsw-alias-interactive-bg-selected)' : 'transparent',
|
|
148
|
+
cursor: writable ? 'pointer' : 'default',
|
|
149
|
+
fontWeight: active ? 600 : 400,
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
type DynamicCatalogMap = Readonly<Record<string, { readonly defaultTokens: number; readonly maxTokens: number }>>
|
|
154
|
+
let cachedConnectCatalog: DynamicCatalogMap | undefined
|
|
155
|
+
let catalogFetchPromise: Promise<DynamicCatalogMap | undefined> | undefined
|
|
156
|
+
|
|
157
|
+
async function loadConnectCatalog(): Promise<DynamicCatalogMap | undefined> {
|
|
158
|
+
if (cachedConnectCatalog !== undefined) return cachedConnectCatalog
|
|
159
|
+
if (typeof fetch !== 'function') return undefined
|
|
160
|
+
return catalogFetchPromise ??= fetch(OPENAI_CODEX_MODEL_CATALOG_PATH, {
|
|
161
|
+
headers: { accept: 'application/json' },
|
|
162
|
+
credentials: 'same-origin',
|
|
163
|
+
}).then(async res => {
|
|
164
|
+
if (!res.ok) return undefined
|
|
165
|
+
const rows = await res.json() as unknown
|
|
166
|
+
if (!Array.isArray(rows)) return undefined
|
|
167
|
+
const map: Record<string, { defaultTokens: number; maxTokens: number }> = {}
|
|
168
|
+
for (const row of rows) {
|
|
169
|
+
const rec = typeof row === 'object' && row !== null ? row as Record<string, unknown> : undefined
|
|
170
|
+
if (rec !== undefined && typeof rec.id === 'string' && typeof rec.contextWindow === 'number' && typeof rec.maxContextWindow === 'number') {
|
|
171
|
+
map[rec.id] = { defaultTokens: rec.contextWindow, maxTokens: rec.maxContextWindow }
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
return cachedConnectCatalog = map
|
|
175
|
+
}).catch(() => undefined).finally(() => { catalogFetchPromise = undefined })
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const contextMenuCss = `
|
|
179
|
+
.codex-ctx-menu { position:fixed; z-index:1200; width:196px; padding:6px; border-radius:10px; font-size:12px; color:var(--dsw-alias-label-primary); background:var(--dsw-alias-bg-layer-1, #1f2329); border:0.5px solid var(--dsw-alias-border-l2); box-shadow:var(--dsw-shadow-lv2, 0 6px 20px rgb(0 0 0 / 16%)); box-sizing:border-box; }
|
|
180
|
+
.codex-ctx-head { padding:4px 8px 6px; font-size:11px; color:var(--dsw-alias-label-secondary); border-bottom:0.5px solid var(--dsw-alias-border-l2); margin-bottom:4px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
|
|
181
|
+
.codex-ctx-item { display:flex; align-items:center; gap:6px; width:100%; border:0; border-radius:6px; padding:5px 8px; background:transparent; color:inherit; font:inherit; text-align:left; cursor:pointer; }
|
|
182
|
+
.codex-ctx-item:hover:not(:disabled) { background:var(--dsw-alias-interactive-bg-hover, rgb(128 128 128 / 12%)); }
|
|
183
|
+
.codex-ctx-item[aria-checked=true] { color:var(--dsw-static-blue-500); font-weight:600; }
|
|
184
|
+
.codex-ctx-item:disabled { opacity:.5; cursor:default; }
|
|
185
|
+
.codex-ctx-form { display:flex; gap:4px; margin-top:4px; padding-top:6px; border-top:0.5px solid var(--dsw-alias-border-l2); }
|
|
186
|
+
.codex-ctx-form input { flex:1; min-width:0; height:26px; padding:0 7px; border-radius:6px; border:0.5px solid var(--dsw-alias-border-l3, var(--dsw-alias-border-l2)); background:var(--dsw-alias-bg-layer-2); color:inherit; font:inherit; font-variant-numeric:tabular-nums; }
|
|
187
|
+
.codex-ctx-form input[aria-invalid=true] { border-color:var(--dsw-alias-state-error-primary, #e5484d); }
|
|
188
|
+
.codex-ctx-form button { height:26px; padding:0 9px; border-radius:6px; border:0.5px solid var(--dsw-alias-border-l3, var(--dsw-alias-border-l2)); background:var(--dsw-alias-bg-layer-2); color:inherit; font:inherit; cursor:pointer; }
|
|
189
|
+
`
|
|
190
|
+
|
|
191
|
+
export interface ContextControlProps extends PropsLocale<'codex'> {
|
|
192
|
+
useSettings: (select: (state: unknown) => unknown) => unknown
|
|
193
|
+
setSetting: (field: string, value: unknown) => Promise<void>
|
|
194
|
+
unsetSetting: (field: string) => Promise<void>
|
|
195
|
+
modelDirectory?: ModelDirectoryStore | undefined
|
|
196
|
+
getCodexConnectScope?: (() => CodexConnectScope | undefined) | undefined
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
export function ContextWindowControl(props: ContextControlProps) {
|
|
200
|
+
const { useSettings, setSetting, unsetSetting, modelDirectory, getCodexConnectScope, t } = props
|
|
201
|
+
const dirSnapshot = useModelDirectory(modelDirectory)
|
|
202
|
+
const settings = useSettings(state => state) as {
|
|
203
|
+
value?: { contextWindow?: number; contextWindowControlEnabled?: boolean }
|
|
204
|
+
writable: boolean
|
|
205
|
+
}
|
|
206
|
+
const hasDirectory = modelDirectory !== undefined
|
|
207
|
+
const provider = dirSnapshot?.current?.provider
|
|
208
|
+
const currentModel = dirSnapshot?.current?.model
|
|
209
|
+
const eligible = hasDirectory ? dirSnapshot?.status === 'ready' && isGptModelName(currentModel) : true
|
|
210
|
+
const isCodexConnect = hasDirectory && eligible && provider === OPENAI_CODEX_PROVIDER
|
|
211
|
+
const connectScope = isCodexConnect ? getCodexConnectScope?.() : undefined
|
|
212
|
+
const subscribeConnect = useCallback(
|
|
213
|
+
(listener: () => void) => connectScope !== undefined ? connectScope.subscribe(listener) : NOOP_SUBSCRIBE(),
|
|
214
|
+
[connectScope],
|
|
215
|
+
)
|
|
216
|
+
const getConnectSnapshot = useCallback(() => connectScope?.getSnapshot(), [connectScope])
|
|
217
|
+
const connectSnap = useSyncExternalStore(subscribeConnect, getConnectSnapshot, getConnectSnapshot)
|
|
218
|
+
|
|
219
|
+
const [open, setOpen] = useState(false)
|
|
220
|
+
const [customInput, setCustomInput] = useState('')
|
|
221
|
+
const [customInvalid, setCustomInvalid] = useState(false)
|
|
222
|
+
const [anchorRect, setAnchorRect] = useState<{ bottom: number; right: number }>()
|
|
223
|
+
const [dynamicCatalog, setDynamicCatalog] = useState<DynamicCatalogMap | undefined>(() => cachedConnectCatalog)
|
|
224
|
+
const fetchedModelsRef = useRef<Set<string>>(new Set())
|
|
225
|
+
const buttonRef = useRef<HTMLButtonElement>(null)
|
|
226
|
+
const menuRef = useRef<HTMLDivElement>(null)
|
|
227
|
+
const menuId = useId()
|
|
228
|
+
|
|
229
|
+
useEffect(() => {
|
|
230
|
+
if (!isCodexConnect || currentModel === undefined) return
|
|
231
|
+
if (OPENAI_CODEX_MODEL_LIMITS[currentModel] !== undefined || dynamicCatalog?.[currentModel] !== undefined) return
|
|
232
|
+
if (fetchedModelsRef.current.has(currentModel)) return
|
|
233
|
+
fetchedModelsRef.current.add(currentModel)
|
|
234
|
+
let cancelled = false
|
|
235
|
+
void loadConnectCatalog().then(catalog => {
|
|
236
|
+
if (!cancelled && catalog !== undefined) setDynamicCatalog(catalog)
|
|
237
|
+
})
|
|
238
|
+
return () => { cancelled = true }
|
|
239
|
+
}, [isCodexConnect, currentModel, dynamicCatalog])
|
|
240
|
+
|
|
241
|
+
useEffect(() => { setOpen(false); setCustomInvalid(false); setCustomInput('') }, [provider, currentModel])
|
|
242
|
+
|
|
243
|
+
useEffect(() => {
|
|
244
|
+
if (!open) return undefined
|
|
245
|
+
const updateAnchor = () => {
|
|
246
|
+
const rect = buttonRef.current?.getBoundingClientRect()
|
|
247
|
+
if (rect === undefined) return
|
|
248
|
+
setAnchorRect({
|
|
249
|
+
bottom: Math.max(8, window.innerHeight - rect.top + 6),
|
|
250
|
+
right: Math.max(8, window.innerWidth - rect.right),
|
|
251
|
+
})
|
|
252
|
+
}
|
|
253
|
+
const onKeyDown = (event: KeyboardEvent) => {
|
|
254
|
+
if (event.key !== 'Escape') return
|
|
255
|
+
setOpen(false); setCustomInvalid(false); buttonRef.current?.focus()
|
|
256
|
+
}
|
|
257
|
+
const onPointerDown = (event: PointerEvent) => {
|
|
258
|
+
const target = event.target as Node | null
|
|
259
|
+
if (target !== null && (buttonRef.current?.contains(target) || menuRef.current?.contains(target))) return
|
|
260
|
+
setOpen(false); setCustomInvalid(false)
|
|
261
|
+
}
|
|
262
|
+
updateAnchor()
|
|
263
|
+
window.addEventListener('resize', updateAnchor)
|
|
264
|
+
window.addEventListener('scroll', updateAnchor, true)
|
|
265
|
+
window.addEventListener('keydown', onKeyDown)
|
|
266
|
+
document.addEventListener('pointerdown', onPointerDown)
|
|
267
|
+
return () => {
|
|
268
|
+
window.removeEventListener('resize', updateAnchor)
|
|
269
|
+
window.removeEventListener('scroll', updateAnchor, true)
|
|
270
|
+
window.removeEventListener('keydown', onKeyDown)
|
|
271
|
+
document.removeEventListener('pointerdown', onPointerDown)
|
|
272
|
+
}
|
|
273
|
+
}, [open])
|
|
274
|
+
|
|
275
|
+
if (!(settings.value?.contextWindowControlEnabled ?? true) || !eligible) return null
|
|
276
|
+
if (isCodexConnect && connectSnap?.status === 'unavailable') return null
|
|
277
|
+
|
|
278
|
+
const bounds = resolveContextWindowBounds(provider, currentModel, dynamicCatalog)
|
|
279
|
+
const rawConnectOverride = isCodexConnect && typeof currentModel === 'string'
|
|
280
|
+
? connectSnap?.overrides?.[currentModel]
|
|
281
|
+
: undefined
|
|
282
|
+
const overrideTokens = isCodexConnect
|
|
283
|
+
? (typeof rawConnectOverride === 'number' && rawConnectOverride > 0 ? rawConnectOverride : undefined)
|
|
284
|
+
: settings.value?.contextWindow
|
|
285
|
+
const effectiveTokens = overrideTokens ?? bounds.defaultTokens
|
|
286
|
+
const writable = isCodexConnect ? connectSnap?.writable !== false : settings.writable !== false
|
|
287
|
+
const label = effectiveTokens !== undefined ? formatCompactTokens(effectiveTokens) : t('contextShortDefault')
|
|
288
|
+
const fullLabel = `${t('contextSize')}: ${effectiveTokens !== undefined ? `${effectiveTokens.toLocaleString()} tokens` : t('contextDefaultOption')}`
|
|
289
|
+
|
|
290
|
+
const applyBudget = (tokens: number | undefined): void => {
|
|
291
|
+
if (!writable) return
|
|
292
|
+
if (isCodexConnect) {
|
|
293
|
+
if (connectScope !== undefined && typeof currentModel === 'string') {
|
|
294
|
+
void connectScope.setModelOverride(currentModel, tokens).catch(() => {})
|
|
295
|
+
}
|
|
296
|
+
} else if (tokens === undefined) {
|
|
297
|
+
void unsetSetting('contextWindow').catch(() => {})
|
|
298
|
+
} else {
|
|
299
|
+
void setSetting('contextWindow', tokens).catch(() => {})
|
|
300
|
+
}
|
|
301
|
+
setOpen(false); setCustomInvalid(false); setCustomInput(''); buttonRef.current?.focus()
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
return <>
|
|
305
|
+
<button
|
|
306
|
+
ref={buttonRef}
|
|
307
|
+
type="button"
|
|
308
|
+
data-codex-context-control={overrideTokens !== undefined ? 'override' : 'default'}
|
|
309
|
+
aria-haspopup="menu"
|
|
310
|
+
aria-expanded={open}
|
|
311
|
+
aria-controls={open ? menuId : undefined}
|
|
312
|
+
aria-label={fullLabel}
|
|
313
|
+
title={fullLabel}
|
|
314
|
+
disabled={!writable}
|
|
315
|
+
onClick={() => {
|
|
316
|
+
if (!writable) return
|
|
317
|
+
if (!open && typeof window !== 'undefined') {
|
|
318
|
+
const rect = buttonRef.current?.getBoundingClientRect()
|
|
319
|
+
if (rect !== undefined) {
|
|
320
|
+
setAnchorRect({
|
|
321
|
+
bottom: Math.max(8, window.innerHeight - rect.top + 6),
|
|
322
|
+
right: Math.max(8, window.innerWidth - rect.right),
|
|
323
|
+
})
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
setOpen(current => !current); setCustomInvalid(false)
|
|
327
|
+
}}
|
|
328
|
+
style={{ ...pillStyle(overrideTokens !== undefined, writable), fontVariantNumeric: 'tabular-nums' }}
|
|
329
|
+
>{label}</button>
|
|
330
|
+
{open && typeof document !== 'undefined' ? createPortal(
|
|
331
|
+
<div
|
|
332
|
+
id={menuId}
|
|
333
|
+
ref={menuRef}
|
|
334
|
+
role="menu"
|
|
335
|
+
aria-label={t('contextSize')}
|
|
336
|
+
data-codex-context-menu
|
|
337
|
+
className="codex-ctx-menu"
|
|
338
|
+
style={{ bottom: anchorRect?.bottom ?? 48, right: anchorRect?.right ?? 16 }}
|
|
339
|
+
>
|
|
340
|
+
<style>{contextMenuCss}</style>
|
|
341
|
+
<div className="codex-ctx-head">{`${currentModel ?? 'GPT'} · ≤${formatCompactTokens(bounds.maxTokens)}`}</div>
|
|
342
|
+
<button
|
|
343
|
+
type="button" role="menuitemradio" className="codex-ctx-item"
|
|
344
|
+
aria-checked={overrideTokens === undefined} disabled={!writable} onClick={() => applyBudget(undefined)}
|
|
345
|
+
>
|
|
346
|
+
<span aria-hidden="true" style={{ width: 14, textAlign: 'center' }}>{overrideTokens === undefined ? '✓' : ''}</span>
|
|
347
|
+
<span>{bounds.defaultTokens !== undefined ? `${t('contextDefaultOption')} (${formatCompactTokens(bounds.defaultTokens)})` : t('contextDefaultOption')}</span>
|
|
348
|
+
</button>
|
|
349
|
+
{contextPresetsForBounds(bounds).map(tier => <button
|
|
350
|
+
key={tier}
|
|
351
|
+
type="button" role="menuitemradio" className="codex-ctx-item"
|
|
352
|
+
aria-checked={overrideTokens === tier} disabled={!writable} onClick={() => applyBudget(tier)}
|
|
353
|
+
style={{ fontVariantNumeric: 'tabular-nums' }}
|
|
354
|
+
>
|
|
355
|
+
<span aria-hidden="true" style={{ width: 14, textAlign: 'center' }}>{overrideTokens === tier ? '✓' : ''}</span>
|
|
356
|
+
<span>{formatCompactTokens(tier)}</span>
|
|
357
|
+
</button>)}
|
|
358
|
+
<form className="codex-ctx-form" onSubmit={event => {
|
|
359
|
+
event.preventDefault()
|
|
360
|
+
const parsed = parseCustomContextInput(customInput, bounds.maxTokens)
|
|
361
|
+
if (parsed === undefined) { setCustomInvalid(true); return }
|
|
362
|
+
applyBudget(parsed)
|
|
363
|
+
}}>
|
|
364
|
+
<input
|
|
365
|
+
type="text" inputMode="numeric"
|
|
366
|
+
placeholder={t('contextCustomPlaceholder')} aria-label={t('contextCustomPlaceholder')}
|
|
367
|
+
aria-invalid={customInvalid} value={customInput}
|
|
368
|
+
onChange={event => { setCustomInput(event.currentTarget.value); if (customInvalid) setCustomInvalid(false) }}
|
|
369
|
+
/>
|
|
370
|
+
<button type="submit" disabled={!writable}>{t('contextApply')}</button>
|
|
371
|
+
</form>
|
|
372
|
+
</div>,
|
|
373
|
+
document.body,
|
|
374
|
+
) : null}
|
|
375
|
+
</>
|
|
376
|
+
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import type { PresetCatalog } from '../
|
|
1
|
+
import type { PresetCatalog } from '../contracts/ui-contracts.ts'
|
|
2
2
|
import type { PresetManagerActions } from './preset-manager.tsx'
|
|
3
|
-
import type { PresetPromptCatalog, PresetToolCatalog } from '../tool-policy-contract.ts'
|
|
3
|
+
import type { PresetPromptCatalog, PresetToolCatalog } from '../contracts/tool-policy-contract.ts'
|
|
4
4
|
|
|
5
5
|
const catalogs = new WeakMap<PresetManagerActions, PresetCatalog>()
|
|
6
6
|
const catalogRequests = new WeakMap<PresetManagerActions, Promise<PresetCatalog>>()
|