@fxz26284407/yuanma-gateway 0.1.11 → 0.1.12

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/dist/codex.js CHANGED
@@ -499,14 +499,25 @@ export class CodexBackend {
499
499
  requireValue(false, 'INVALID_REQUEST', 'Unknown thread action', 400);
500
500
  return this.threadMeta(projectId, threadId);
501
501
  }
502
- async navigationThreads(cursor, limit = 100) {
503
- return this.call('thread/list', { limit, useStateDbOnly: true, sortKey: 'updated_at', ...(cursor && cursor !== 'start' ? { cursor } : {}) });
502
+ async navigationThreads(cursor, limit = 100, sectionId) {
503
+ return this.call('thread/list', { limit, useStateDbOnly: true, sortKey: 'updated_at', ...(sectionId ? { sectionId } : {}), ...(cursor && cursor !== 'start' ? { cursor } : {}) });
504
504
  }
505
505
  async navigation(grants) {
506
506
  const [projects, sections, threads, state] = await Promise.all([this.call('project/list', { limit: 100 }), this.call('threadSection/list', { limit: 100 }), this.navigationThreads(), desktopSidebarState()]);
507
507
  await this.desktopSync?.recover(projects.data);
508
+ const listed = new Map(threads.data.map((t) => [t.id, t]));
509
+ const pinned = sections.data.find((s) => s.name === 'Pinned');
510
+ if (pinned) {
511
+ let cursor;
512
+ do {
513
+ const page = await this.navigationThreads(cursor, 100, pinned.id);
514
+ for (const thread of page.data)
515
+ listed.set(thread.id, thread);
516
+ cursor = page.nextCursor ?? undefined;
517
+ } while (cursor);
518
+ }
508
519
  const directoryProjects = this.projects.filter(p => p.id === 'codex:default' || this.directoryScopes.has(p.id));
509
- const assigned = await Promise.all(threads.data.map(async (t) => ({ ...t, projectId: await this.assignedProject(t) })));
520
+ const assigned = await Promise.all([...listed.values()].map(async (t) => ({ ...t, projectId: await this.assignedProject(t) })));
510
521
  const navigation = buildSidebar([...projects.data, ...directoryProjects], sections.data, assigned, state, grants, this.desktopSync?.placements());
511
522
  const defaults = navigation.projects.find(p => p.id === 'codex:default');
512
523
  if (defaults) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fxz26284407/yuanma-gateway",
3
- "version": "0.1.11",
3
+ "version": "0.1.12",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "node": "22.x || 26.x"
@@ -1,163 +0,0 @@
1
- import { execFile } from 'node:child_process';
2
- import { promisify } from 'node:util';
3
- import { readFile, writeFile, rename, lstat, unlink, open } from 'node:fs/promises';
4
- import { homedir } from 'node:os';
5
- import { join, isAbsolute } from 'node:path';
6
- import { randomUUID } from 'node:crypto';
7
- import { requireValue } from './domain.js';
8
- const execute = promisify(execFile);
9
- const statePath = join(homedir(), '.codex/.codex-global-state.json');
10
- async function desktopRunning() {
11
- const { stdout } = await execute('/bin/ps', ['-axo', 'comm=']);
12
- return stdout.split('\n').some(p => /\/(?:ChatGPT|Codex)\.app\/Contents\/MacOS\/(?:ChatGPT|Codex)$/.test(p.trim()));
13
- }
14
- async function regularFile(path, optional = false) {
15
- const st = await lstat(path).catch(e => { if (optional && e.code === 'ENOENT')
16
- return null; throw e; });
17
- requireValue(!st || (st.isFile() && !st.isSymbolicLink() && st.nlink === 1 && st.uid === process.getuid?.()), 'UNSAFE_STORAGE', '桌面同步文件必须由当前用户持有,且不能是符号链接');
18
- return st;
19
- }
20
- async function replaceFile(path, value, mode = 0o600) {
21
- const temp = path + '.' + randomUUID() + '.tmp';
22
- try {
23
- const f = await open(temp, 'wx', mode);
24
- try {
25
- await f.writeFile(value);
26
- await f.sync();
27
- }
28
- finally {
29
- await f.close();
30
- }
31
- await rename(temp, path);
32
- }
33
- finally {
34
- await unlink(temp).catch(e => { if (e.code !== 'ENOENT')
35
- throw e; });
36
- }
37
- }
38
- // Only project registration, names, order and section membership change. All other state stays intact.
39
- export function applyDesktopProjectChanges(state, changes) {
40
- const next = structuredClone(state), identity = 'local:' + join(homedir(), '.codex');
41
- const projects = next['local-projects'] ??= {};
42
- const mappings = next['app-server-project-id-by-legacy-project-id-by-host'] ??= {};
43
- const mapping = mappings[identity] ??= {};
44
- const atoms = next['electron-persisted-atom-state'] ??= {};
45
- const order = next['project-order'] ??= [];
46
- const sidebarOrder = atoms['unified-sidebar-project-order-v1'] ??= [];
47
- for (const change of changes) {
48
- requireValue(/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i.test(change.id) && change.name.trim().length > 0 && change.roots.length > 0 && change.roots.every(isAbsolute), 'INVALID_PROJECT', '待同步的项目记录不完整');
49
- const id = Object.keys(mapping).find(id => mapping[id] === change.id && projects[id]) ?? change.id;
50
- requireValue(!mapping[id] || mapping[id] === change.id, 'PROJECT_CONFLICT', '桌面项目映射已变化,请重新核对');
51
- const deletions = next['app-server-pending-project-deletions-by-host']?.[identity] ?? {};
52
- requireValue(!deletions[id] && !Object.values(deletions).some((d) => d.projectId === change.id), 'PROJECT_CONFLICT', '此项目正在桌面删除,请先在桌面处理');
53
- mapping[id] = change.id;
54
- if (!projects[id])
55
- projects[id] = { id, name: change.name, rootPaths: change.roots, createdAt: Date.now(), updatedAt: Date.now() };
56
- else if (change.rename && projects[id].name !== change.name)
57
- projects[id] = { ...projects[id], name: change.name, updatedAt: Date.now() };
58
- if (!order.includes(id))
59
- order.push(id);
60
- const key = 'codex:project:' + id;
61
- if (!sidebarOrder.includes(key))
62
- sidebarOrder.push(key);
63
- if (change.sectionId === undefined)
64
- continue;
65
- const scopes = Object.values(atoms['sidebar-custom-sections-v3'] ?? {});
66
- const belongs = (k) => k.startsWith('codex:project:') && (mapping[k.slice(14)] ?? k.slice(14)) === change.id;
67
- const matches = scopes.filter(s => s.sections?.some((g) => change.sectionId ? g.hostSectionIds?.local === change.sectionId : (g.itemKeys ?? []).some(belongs)));
68
- requireValue(change.sectionId ? matches.length === 1 : matches.length <= 1, 'SECTION_CONFLICT', '桌面分区已变化或存在多个账号归属,请重新选择分区');
69
- for (const scope of matches)
70
- for (const group of scope.sections) {
71
- group.itemKeys = (group.itemKeys ?? []).filter((k) => !belongs(k));
72
- if (change.sectionId && group.hostSectionIds?.local === change.sectionId)
73
- group.itemKeys.push(key);
74
- }
75
- }
76
- return next;
77
- }
78
- export class DesktopProjectSync {
79
- directory;
80
- journal = { version: 1, pending: {}, imported: [], appliedAt: 0 };
81
- work = Promise.resolve();
82
- timer;
83
- problem = '';
84
- closed = false;
85
- constructor(directory) {
86
- this.directory = directory;
87
- }
88
- get path() { return join(this.directory, 'desktop-project-sync.json'); }
89
- run(action) { const result = this.work.then(action); this.work = result.then(() => { }, () => { }); return result; }
90
- async start() {
91
- await regularFile(this.path, true);
92
- try {
93
- const value = JSON.parse(await readFile(this.path, 'utf8'));
94
- requireValue(value.version === 1 && value.pending && Array.isArray(value.imported) && typeof value.appliedAt === 'number', 'UNSAFE_STORAGE', '无法读取桌面待同步记录');
95
- this.journal = value;
96
- }
97
- catch (e) {
98
- if (e.code !== 'ENOENT')
99
- throw e;
100
- }
101
- // ponytail: one queue serializes this small state file; separate locks only if multiple writers are introduced.
102
- this.timer = setInterval(() => { if (Object.keys(this.journal.pending).length)
103
- this.flush().catch(e => { this.problem = e instanceof Error ? e.message : '桌面同步失败,请刷新后重试'; }); }, 2000);
104
- this.timer.unref();
105
- }
106
- async persist(value = this.journal) { await regularFile(this.path, true); await replaceFile(this.path, JSON.stringify(value)); }
107
- enqueue(change) {
108
- return this.run(async () => {
109
- const next = structuredClone(this.journal);
110
- next.pending[change.id] = { ...next.pending[change.id], ...change, rename: next.pending[change.id]?.rename || change.rename };
111
- if (!next.imported.includes(change.id))
112
- next.imported.push(change.id);
113
- await this.persist(next);
114
- this.journal = next;
115
- this.problem = '';
116
- });
117
- }
118
- recover(projects) {
119
- return this.run(async () => {
120
- let changed = false;
121
- const next = structuredClone(this.journal);
122
- for (const p of projects) {
123
- const sectionId = p.metadata?.['mobile.sectionId'];
124
- if (typeof sectionId !== 'string' || next.imported.includes(p.id))
125
- continue;
126
- if (!next.pending[p.id])
127
- next.pending[p.id] = { id: p.id, name: p.name, roots: p.roots.map((r) => r.path), sectionId };
128
- next.imported.push(p.id);
129
- changed = true;
130
- }
131
- if (changed) {
132
- await this.persist(next);
133
- this.journal = next;
134
- }
135
- });
136
- }
137
- status(grants) { const pending = Object.values(this.journal.pending).filter(p => !!grants[p.id]); return { pending: pending.length, appliedAt: this.journal.appliedAt, error: pending.length ? this.problem : '' }; }
138
- placements() { return Object.values(this.journal.pending).filter(p => p.sectionId !== undefined).map(p => ({ id: p.id, sectionId: p.sectionId })); }
139
- flush() {
140
- return this.run(async () => {
141
- if (this.closed || !Object.keys(this.journal.pending).length || await desktopRunning())
142
- return;
143
- const stat = (await regularFile(statePath));
144
- await regularFile(statePath + '.bak', true);
145
- const original = await readFile(statePath, 'utf8'), state = JSON.parse(original);
146
- requireValue(state && typeof state === 'object' && !Array.isArray(state), 'UNSAFE_STORAGE', '桌面状态格式无效');
147
- const updated = JSON.stringify(applyDesktopProjectChanges(state, Object.values(this.journal.pending)));
148
- const backup = join(this.directory, 'desktop-state-before-sync-' + Date.now() + '.json');
149
- await writeFile(backup, original, { flag: 'wx', mode: 0o600 });
150
- // Desktop must stay closed until the phone reports completion; it does not reload external file changes.
151
- if (this.closed || await desktopRunning() || await readFile(statePath, 'utf8') !== original)
152
- return;
153
- await replaceFile(statePath, updated, stat.mode & 0o777);
154
- await replaceFile(statePath + '.bak', updated, 0o600);
155
- const next = { ...this.journal, pending: {}, appliedAt: Date.now() };
156
- await this.persist(next);
157
- this.journal = next;
158
- this.problem = '';
159
- });
160
- }
161
- async close() { this.closed = true; if (this.timer)
162
- clearInterval(this.timer); await this.work; }
163
- }