root commited on
Commit
f184f08
·
1 Parent(s): fd5a459

书房栏收纳 + 书本锁(AI 一次只处理一本书)

Browse files
fanqie/agent.js CHANGED
@@ -542,6 +542,7 @@ module.exports = function buildAgent(express, projects) {
542
  '你在和另一位 AI(写作 AI)协作。写作 AI 正在一个小说写作工作台上帮一位新人作者在番茄小说平台写书,它会把任务和作品资料发给你。',
543
  '通用要求:用中文回答;只根据给你的资料和可靠信息判断,引用资料时标明出处(章号或条目);结论先行、条理清楚;拿不准的地方直接说拿不准。',
544
  '不要编造平台规则或数据;不要提供照抄现成作品的内容;涉及番茄内容红线的写法一律不建议。',
 
545
  ].join('\n')
546
  const TASK_SYSTEM = {
547
  review: [
@@ -810,10 +811,12 @@ module.exports = function buildAgent(express, projects) {
810
  }))
811
 
812
  /* ---------------- AI 工作守则(人和 AI 共读) ---------------- */
813
- async function guideMd(origin = '') {
814
  const prof = await getProfile()
815
  const cfg = await revConfig()
816
- const list = await projects.listProjects().catch(() => ({ projects: [] }))
 
 
817
  const L = []
818
  const B = origin || ''
819
  L.push('# AI 工作守则', '',
@@ -833,6 +836,14 @@ module.exports = function buildAgent(express, projects) {
833
  '- **不设置、不猜测、不索要采集室钥匙。** 钥匙只属于作者本人。',
834
  '- 不照抄、不改写任何现成作品;热榜书名、人物、情节只能当趋势参考。',
835
  '- 不批量开新书、不一次生成多本;不替作者做签约、发布等账号操作。', '')
 
 
 
 
 
 
 
 
836
  L.push('## 3. 可以读、应该读的内容', '',
837
  '| 内容 | 怎么读 | 用途 |', '|---|---|---|',
838
  '| **写新章资料包** | `GET /fanqie/api/projects/{作品ID}/writing-pack?chapter=章号&format=md` | **写新章只读这一份**:概览、圣经、大纲、目录、前三章当前正文、本章计划(取用时自动上写新章锁) |\n| 写新章锁 | `GET` / `DELETE /fanqie/api/projects/{作品ID}/write-mode` | 查看 / 解开锁;修稿模式开始前必须是解开的 |',
@@ -905,7 +916,7 @@ module.exports = function buildAgent(express, projects) {
905
  return L.filter(x => x !== null && x !== undefined).join('\n')
906
  }
907
  router.get('/guide.md', async (req, res) => {
908
- try { res.setHeader('Cache-Control', 'no-cache'); res.type('text/markdown; charset=utf-8').send(await guideMd()) }
909
  catch (e) { res.status(500).type('text/plain; charset=utf-8').send(e.message || String(e)) }
910
  })
911
  router.guideMd = guideMd
 
542
  '你在和另一位 AI(写作 AI)协作。写作 AI 正在一个小说写作工作台上帮一位新人作者在番茄小说平台写书,它会把任务和作品资料发给你。',
543
  '通用要求:用中文回答;只根据给你的资料和可靠信息判断,引用资料时标明出处(章号或条目);结论先行、条理清楚;拿不准的地方直接说拿不准。',
544
  '不要编造平台规则或数据;不要提供照抄现成作品的内容;涉及番茄内容红线的写法一律不建议。',
545
+ '只针对这次附带的这一本书判断。这位作者还写别的书,但别的书和这本无关:不要拿以前对话里见过的其他作品的人物、设定、情节来对照或建议。',
546
  ].join('\n')
547
  const TASK_SYSTEM = {
548
  review: [
 
811
  }))
812
 
813
  /* ---------------- AI 工作守则(人和 AI 共读) ---------------- */
814
+ async function guideMd(origin = '', opts = {}) {
815
  const prof = await getProfile()
816
  const cfg = await revConfig()
817
+ const focus = await projects.getFocus().catch(() => null)
818
+ let list = await projects.listProjects().catch(() => ({ projects: [] }))
819
+ if (opts.ai && focus) list = { projects: (list.projects || []).filter(p => p.project_id === focus.project_id) }
820
  const L = []
821
  const B = origin || ''
822
  L.push('# AI 工作守则', '',
 
836
  '- **不设置、不猜测、不索要采集室钥匙。** 钥匙只属于作者本人。',
837
  '- 不照抄、不改写任何现成作品;热榜书名、人物、情节只能当趋势参考。',
838
  '- 不批量开新书、不一次生成多本;不替作者做签约、发布等账号操作。', '')
839
+ L.push('## 2.1 一次只做一本书(书本锁)', '',
840
+ '> 作者会写很多本书。每本书的人物、设定、伏笔、语气都只属于它自己,**不能互相串**:写第二本时不能借第一本的人名、桥段、句子和思路,改某一本时也不能拿别的书来对照。', '',
841
+ focus ? `- **现在锁定的书:《${focus.title}》**(ID \`${focus.project_id}\`)。锁定期间,其他书的所有接口对你都返回 423,书单里也只看得到这一本。` : '- 现在没有锁定任何一本书。',
842
+ '- **开工第一步先锁书**:`POST /fanqie/api/agent/focus`,body `{"project_id":"作品ID"}`(取写新章资料包时也会自动锁上)。之后只读这本书自己的资料。',
843
+ '- **换书只听作者的**:作者明确说「去写/改《某某》」时,才 `POST /fanqie/api/agent/focus`,body `{"project_id":"新书ID","switch":true,"reason":"作者原话"}`。每次切换都会记录,作者在书房里看得到。',
844
+ '- **换书 = 清空脑子**:换书前把上一本的内容全部放下;本地临时文件(下载的正文、草稿)按书分开存,换书时删掉上一本的。最稳妥的做法是:换书就请作者开一个新对话。',
845
+ '- 不在一本书里引用、对比、借鉴另一本书;协作 AI 那边也一样——发给它的资料只来自当前这本书(`project_id` 填当前书),不把两本书的资料放进同一次提问。',
846
+ '- 番茄热榜、母题库、素材馆的摘要和改写卡是公共参考,不属于任何一本书,可以用;但用在哪本书里,就只按那本书的设定改写。', '')
847
  L.push('## 3. 可以读、应该读的内容', '',
848
  '| 内容 | 怎么读 | 用途 |', '|---|---|---|',
849
  '| **写新章资料包** | `GET /fanqie/api/projects/{作品ID}/writing-pack?chapter=章号&format=md` | **写新章只读这一份**:概览、圣经、大纲、目录、前三章当前正文、本章计划(取用时自动上写新章锁) |\n| 写新章锁 | `GET` / `DELETE /fanqie/api/projects/{作品ID}/write-mode` | 查看 / 解开锁;修稿模式开始前必须是解开的 |',
 
916
  return L.filter(x => x !== null && x !== undefined).join('\n')
917
  }
918
  router.get('/guide.md', async (req, res) => {
919
+ try { res.setHeader('Cache-Control', 'no-cache'); res.type('text/markdown; charset=utf-8').send(await guideMd('', { ai: req.get('x-client') !== 'workbench' })) }
920
  catch (e) { res.status(500).type('text/plain; charset=utf-8').send(e.message || String(e)) }
921
  })
922
  router.guideMd = guideMd
fanqie/dist/index.html CHANGED
@@ -8,8 +8,8 @@
8
  <title>小说写作台</title>
9
  <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'%3E%3Crect width='64' height='64' rx='12' fill='%23b8432f'/%3E%3Ctext x='32' y='44' font-size='34' text-anchor='middle' fill='%23fff' font-family='serif'%3E%E6%96%87%3C/text%3E%3C/svg%3E" />
10
  <script>try{var t=localStorage.getItem('xs_theme');if(t==='night')document.documentElement.dataset.theme='night'}catch(e){}</script>
11
- <script type="module" crossorigin src="/assets/index-DqeYbbLJ.js"></script>
12
- <link rel="stylesheet" crossorigin href="/assets/index-CRGf1XQf.css">
13
  </head>
14
  <body>
15
  <div id="root"></div>
 
8
  <title>小说写作台</title>
9
  <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'%3E%3Crect width='64' height='64' rx='12' fill='%23b8432f'/%3E%3Ctext x='32' y='44' font-size='34' text-anchor='middle' fill='%23fff' font-family='serif'%3E%E6%96%87%3C/text%3E%3C/svg%3E" />
10
  <script>try{var t=localStorage.getItem('xs_theme');if(t==='night')document.documentElement.dataset.theme='night'}catch(e){}</script>
11
+ <script type="module" crossorigin src="/assets/index-CZWtgNvq.js"></script>
12
+ <link rel="stylesheet" crossorigin href="/assets/index-DP2cUhfJ.css">
13
  </head>
14
  <body>
15
  <div id="root"></div>
fanqie/mount.js CHANGED
@@ -28,10 +28,29 @@ module.exports = function mountFanqie(app, passwordOk, express) {
28
  { m: 'GET', re: /^\/fanqie\/api\/agent\/(reviewer\/log(\/.*)?|audits)\/?$/, agent: true },
29
  { m: 'POST', re: /^\/fanqie\/api\/agent\/reviewer\/ask\/?$/, agent: true },
30
  ]
 
 
 
 
31
  app.use('/fanqie/api', async (req, res, next) => {
32
  try {
33
  if (req.get('x-client') === 'workbench') return next()
34
  const full = (req.baseUrl || '') + req.path
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  const hit = PROCESS_PATHS.find(x => x.m === req.method && x.re.test(full))
36
  if (!hit) return next()
37
  const mm = hit.re.exec(full)
@@ -93,6 +112,7 @@ module.exports = function mountFanqie(app, passwordOk, express) {
93
  app.delete('/fanqie/api/projects/:projectId/write-mode', projectRoute(req => projects.endWriteMode(req.params.projectId, req.get('x-client') === 'workbench' ? '作者' : '写作 AI')))
94
  app.get('/fanqie/api/projects/:projectId/writing-pack', async (req, res) => {
95
  try {
 
96
  if (req.get('x-client') !== 'workbench' && req.query.lock !== '0') await projects.startWriteMode(req.params.projectId, { chapter: req.query.chapter })
97
  const r = await projects.writingPack(req.params.projectId, req.query.chapter ? String(req.query.chapter) : '', { prev: req.query.prev, format: req.query.format === 'md' ? 'md' : 'json' })
98
  res.setHeader('Cache-Control', 'no-store')
@@ -170,7 +190,7 @@ module.exports = function mountFanqie(app, passwordOk, express) {
170
  app.get('/fanqie/feed/agent.md', async (req, res) => {
171
  const ok = passwordOk(req) || passwordOk({ headers: { 'x-app-password': String(req.query.key || '') } })
172
  if (!ok) return res.status(401).type('text/plain; charset=utf-8').send('需要访问密码:在链接后加 ?key=访问密码')
173
- try { res.setHeader('Cache-Control', 'no-cache'); res.type('text/markdown; charset=utf-8').send(await agent.guideMd()) }
174
  catch (e) { res.status(500).type('text/plain; charset=utf-8').send(e.message || String(e)) }
175
  })
176
  app.use('/fanqie', express.static(DIST, { index: false, maxAge: '1h' }))
 
28
  { m: 'GET', re: /^\/fanqie\/api\/agent\/(reviewer\/log(\/.*)?|audits)\/?$/, agent: true },
29
  { m: 'POST', re: /^\/fanqie\/api\/agent\/reviewer\/ask\/?$/, agent: true },
30
  ]
31
+ // 书本锁:写作 AI 一次只做一本书,锁定期间其他书的任何接口都对它关闭
32
+ app.get('/fanqie/api/agent/focus', projectRoute(async () => (await projects.getFocus()) || { project_id: null, history: ((await projects.readJson('agent/focus.json', null)) || {}).history || [] }))
33
+ app.post('/fanqie/api/agent/focus', projectRoute(req => projects.setFocus(String((req.body || {}).project_id || ''), req.body || {})))
34
+ app.delete('/fanqie/api/agent/focus', projectRoute(req => projects.clearFocus(req.get('x-client') === 'workbench' ? '作者' : '写作 AI')))
35
  app.use('/fanqie/api', async (req, res, next) => {
36
  try {
37
  if (req.get('x-client') === 'workbench') return next()
38
  const full = (req.baseUrl || '') + req.path
39
+ if (/^\/fanqie\/api\/agent\/focus\/?$/.test(full)) return next()
40
+ const fc = await projects.getFocus()
41
+ if (fc) {
42
+ const other = `写作 AI 现在只处理《${fc.title}》,其他书的内容一律不读。要换书,必须是作者明确要求:POST /fanqie/api/agent/focus,body {"project_id":"新书ID","switch":true,"reason":"作者原话"}。`
43
+ if (req.method === 'GET' && /^\/fanqie\/api\/projects\/?$/.test(full)) {
44
+ const p = await projects.getProject(fc.project_id).catch(() => null)
45
+ return res.json({ projects: p ? [p.project] : [], focus: { project_id: fc.project_id, title: fc.title }, note: other })
46
+ }
47
+ const pm = /^\/fanqie\/api\/projects\/([^/]+)/.exec(full)
48
+ if (pm && pm[1] !== fc.project_id) return res.status(423).json({ error: other, focus: { project_id: fc.project_id, title: fc.title } })
49
+ if (/^\/fanqie\/api\/agent\//.test(full)) {
50
+ const qp = String((req.query && req.query.project_id) || (req.body && req.body.project_id) || '')
51
+ if (qp && qp !== fc.project_id) return res.status(423).json({ error: other, focus: { project_id: fc.project_id, title: fc.title } })
52
+ }
53
+ }
54
  const hit = PROCESS_PATHS.find(x => x.m === req.method && x.re.test(full))
55
  if (!hit) return next()
56
  const mm = hit.re.exec(full)
 
112
  app.delete('/fanqie/api/projects/:projectId/write-mode', projectRoute(req => projects.endWriteMode(req.params.projectId, req.get('x-client') === 'workbench' ? '作者' : '写作 AI')))
113
  app.get('/fanqie/api/projects/:projectId/writing-pack', async (req, res) => {
114
  try {
115
+ if (req.get('x-client') !== 'workbench') await projects.setFocus(req.params.projectId, {})
116
  if (req.get('x-client') !== 'workbench' && req.query.lock !== '0') await projects.startWriteMode(req.params.projectId, { chapter: req.query.chapter })
117
  const r = await projects.writingPack(req.params.projectId, req.query.chapter ? String(req.query.chapter) : '', { prev: req.query.prev, format: req.query.format === 'md' ? 'md' : 'json' })
118
  res.setHeader('Cache-Control', 'no-store')
 
190
  app.get('/fanqie/feed/agent.md', async (req, res) => {
191
  const ok = passwordOk(req) || passwordOk({ headers: { 'x-app-password': String(req.query.key || '') } })
192
  if (!ok) return res.status(401).type('text/plain; charset=utf-8').send('需要访问密码:在链接后加 ?key=访问密码')
193
+ try { res.setHeader('Cache-Control', 'no-cache'); res.type('text/markdown; charset=utf-8').send(await agent.guideMd('', { ai: req.get('x-client') !== 'workbench' })) }
194
  catch (e) { res.status(500).type('text/plain; charset=utf-8').send(e.message || String(e)) }
195
  })
196
  app.use('/fanqie', express.static(DIST, { index: false, maxAge: '1h' }))
fanqie/projects.js CHANGED
@@ -594,6 +594,45 @@ async function anyWriteMode() {
594
  return null
595
  }
596
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
597
  /* ---------- 发布台:每章能不能发、发没发 ---------- */
598
  function publishKey(projectId) { return projectKey(projectId, 'publish.json') }
599
  async function getPublish(projectId) {
@@ -1027,7 +1066,7 @@ module.exports = {
1027
  getProgress, saveProgress, decidePeer, listChanges, ackChange, saveAuthorDraft, paraDiff,
1028
  listProjects, createProject, getProject, updateProject, deleteProject, saveBible, saveOutline, saveMaterials,
1029
  listChapters, createChapter, getChapter: getChapterOrThrow, updateChapter,
1030
- listVersions, getVersion, saveVersion, rollback, saveCheck, getCheck, basicCheck, getContext, writingPack, getPublish, setPublish, getWriteMode, startWriteMode, endWriteMode, anyWriteMode,
1031
  createRequest, listRequests, updateRequest, HttpError,
1032
  getNotes, createNote, updateNote, deleteNote, saveReview, deleteReview, listProjectNotes,
1033
  listPeer, addPeer, updatePeer, deletePeer,
 
594
  return null
595
  }
596
 
597
+ /* ---------- 一次只做一本书(书本锁) ----------
598
+ * 写作 AI 开始处理某本书时锁定这本书;锁定期间它读不到其他书的任何内容,书单里也只看得到这一本。
599
+ * 换书必须由作者明确提出(带 switch:true),每次切换都记下来给作者看。作者在工作台里不受影响。 */
600
+ const FOCUS_KEY = 'agent/focus.json'
601
+ const FOCUS_HOURS = 24
602
+ let focusCache = null
603
+ async function readFocusRaw() {
604
+ if (focusCache && Date.now() - focusCache.at < 5000) return focusCache.v
605
+ const v = await readJson(FOCUS_KEY, null).catch(() => null)
606
+ focusCache = { at: Date.now(), v }
607
+ return v
608
+ }
609
+ async function getFocus() {
610
+ const v = await readFocusRaw()
611
+ if (!v || !v.project_id || Date.parse(v.expires_at) < Date.now()) return null
612
+ return v
613
+ }
614
+ async function setFocus(projectId, body = {}) {
615
+ const project = await getProjectOrThrow(projectId)
616
+ const raw = (await readFocusRaw()) || {}
617
+ const cur = await getFocus()
618
+ if (cur && cur.project_id !== project.project_id && body.switch !== true) {
619
+ throw new HttpError(409, `写作 AI 正在专注《${cur.title}》。只有作者明确要求换书时,才能带 "switch": true 切换;换书前把上一本的内容全部放下,不要带到新书里。`)
620
+ }
621
+ const history = [...(raw.history || [])]
622
+ if (!cur || cur.project_id !== project.project_id) history.unshift({ project_id: project.project_id, title: project.title, at: now(), from: cur ? cur.title : '', reason: String(body.reason || '').slice(0, 200) })
623
+ const v = { project_id: project.project_id, title: project.title, started_at: cur && cur.project_id === project.project_id ? cur.started_at : now(), expires_at: new Date(Date.now() + FOCUS_HOURS * 3600e3).toISOString(), history: history.slice(0, 50) }
624
+ await writeJson(FOCUS_KEY, v)
625
+ focusCache = { at: Date.now(), v }
626
+ return v
627
+ }
628
+ async function clearFocus(by) {
629
+ const raw = (await readFocusRaw()) || {}
630
+ const v = { project_id: null, cleared_at: now(), cleared_by: String(by || '').slice(0, 40), history: raw.history || [] }
631
+ await writeJson(FOCUS_KEY, v)
632
+ focusCache = { at: Date.now(), v }
633
+ return { project_id: null }
634
+ }
635
+
636
  /* ---------- 发布台:每章能不能发、发没发 ---------- */
637
  function publishKey(projectId) { return projectKey(projectId, 'publish.json') }
638
  async function getPublish(projectId) {
 
1066
  getProgress, saveProgress, decidePeer, listChanges, ackChange, saveAuthorDraft, paraDiff,
1067
  listProjects, createProject, getProject, updateProject, deleteProject, saveBible, saveOutline, saveMaterials,
1068
  listChapters, createChapter, getChapter: getChapterOrThrow, updateChapter,
1069
+ listVersions, getVersion, saveVersion, rollback, saveCheck, getCheck, basicCheck, getContext, writingPack, getPublish, setPublish, getWriteMode, startWriteMode, endWriteMode, anyWriteMode, getFocus, setFocus, clearFocus,
1070
  createRequest, listRequests, updateRequest, HttpError,
1071
  getNotes, createNote, updateNote, deleteNote, saveReview, deleteReview, listProjectNotes,
1072
  listPeer, addPeer, updatePeer, deletePeer,
public/assets/{index-DqeYbbLJ.js → index-CZWtgNvq.js} RENAMED
The diff for this file is too large to render. See raw diff
 
public/assets/{index-CRGf1XQf.css → index-DP2cUhfJ.css} RENAMED
The diff for this file is too large to render. See raw diff
 
public/index.html CHANGED
@@ -8,8 +8,8 @@
8
  <title>小说写作台</title>
9
  <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'%3E%3Crect width='64' height='64' rx='12' fill='%23b8432f'/%3E%3Ctext x='32' y='44' font-size='34' text-anchor='middle' fill='%23fff' font-family='serif'%3E%E6%96%87%3C/text%3E%3C/svg%3E" />
10
  <script>try{var t=localStorage.getItem('xs_theme');if(t==='night')document.documentElement.dataset.theme='night'}catch(e){}</script>
11
- <script type="module" crossorigin src="/assets/index-DqeYbbLJ.js"></script>
12
- <link rel="stylesheet" crossorigin href="/assets/index-CRGf1XQf.css">
13
  </head>
14
  <body>
15
  <div id="root"></div>
 
8
  <title>小说写作台</title>
9
  <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'%3E%3Crect width='64' height='64' rx='12' fill='%23b8432f'/%3E%3Ctext x='32' y='44' font-size='34' text-anchor='middle' fill='%23fff' font-family='serif'%3E%E6%96%87%3C/text%3E%3C/svg%3E" />
10
  <script>try{var t=localStorage.getItem('xs_theme');if(t==='night')document.documentElement.dataset.theme='night'}catch(e){}</script>
11
+ <script type="module" crossorigin src="/assets/index-CZWtgNvq.js"></script>
12
+ <link rel="stylesheet" crossorigin href="/assets/index-DP2cUhfJ.css">
13
  </head>
14
  <body>
15
  <div id="root"></div>
ui-src/src/api.ts CHANGED
@@ -226,6 +226,7 @@ export interface ChangeItem {
226
  from_version_id: string | null; to_version_id: string; summary?: string; hunks: ChangeHunk[]; hunk_count: number; word_delta: number
227
  acks?: { by: string; note: string; at: string }[]
228
  }
 
229
  export interface WriteMode { active: boolean; chapter?: number | null; by?: string; started_at?: string; expires_at?: string }
230
  export interface PublishRow {
231
  chapter_id: string; number: number; title: string; volume: string; status: string; words: number; current_version_id: string | null; updated_at: string
@@ -299,6 +300,9 @@ export interface ReviewerCheck {
299
  }
300
  const A = '/fanqie/api/agent'
301
  export const agentApi = {
 
 
 
302
  profile: () => get<AgentProfile>(`${A}/profile`),
303
  saveProfile: (b: Partial<AgentProfile>) => put<AgentProfile>(`${A}/profile`, b),
304
  rules: () => get<{ version?: string; checked?: string; checklist: any[]; platform: any[]; ai_spec: any[] }>(`${A}/rules`),
 
226
  from_version_id: string | null; to_version_id: string; summary?: string; hunks: ChangeHunk[]; hunk_count: number; word_delta: number
227
  acks?: { by: string; note: string; at: string }[]
228
  }
229
+ export interface AgentFocus { project_id: string | null; title?: string; started_at?: string; expires_at?: string; history?: { project_id: string; title: string; at: string; from: string; reason: string }[] }
230
  export interface WriteMode { active: boolean; chapter?: number | null; by?: string; started_at?: string; expires_at?: string }
231
  export interface PublishRow {
232
  chapter_id: string; number: number; title: string; volume: string; status: string; words: number; current_version_id: string | null; updated_at: string
 
300
  }
301
  const A = '/fanqie/api/agent'
302
  export const agentApi = {
303
+ focus: () => get<AgentFocus>(`${A}/focus`),
304
+ setFocus: (project_id: string, reason = '') => post<AgentFocus>(`${A}/focus`, { project_id, switch: true, reason }),
305
+ clearFocus: () => del<{ project_id: null }>(`${A}/focus`),
306
  profile: () => get<AgentProfile>(`${A}/profile`),
307
  saveProfile: (b: Partial<AgentProfile>) => put<AgentProfile>(`${A}/profile`, b),
308
  rules: () => get<{ version?: string; checked?: string; checklist: any[]; platform: any[]; ai_spec: any[] }>(`${A}/rules`),
ui-src/src/rooms/Book.tsx CHANGED
@@ -1,5 +1,5 @@
1
  import React, { useCallback, useEffect, useMemo, useState } from 'react'
2
- import { ChevronLeft, ScrollText, Users, ListTree, Bookmark, Plus, PanelLeftClose, PanelLeftOpen, Info, FileText, BookOpenText, Highlighter, History, Send, Lock } from 'lucide-react'
3
  import { Chapter, ProjectBundle, projectsApi, WriteMode } from '../api'
4
  import { cnNum, cx, fmtAgo, fmtDate, fmtNum, go, CHAPTER_STATUS, PROJECT_STATUS, useLocal } from '../lib'
5
  import { ErrorNote, Field, Loading, useConfirm, useToast, AutoText, Empty } from '../ui'
@@ -121,28 +121,33 @@ function Binder({ ctx, sub, onAddChapter, onCollapse }: { ctx: BookCtx; sub: str
121
  return () => { alive = false }
122
  }, [pid, sub])
123
  const prog = useBookProgress(pid)
 
124
  return (
125
  <aside className="binder">
126
  <div className="binder-top">
127
- <button className="binder-back" onClick={() => go('shelf')}><ChevronLeft size={15} />书房</button>
128
- <button className="icon-btn sm" onClick={onCollapse} title="收起目录"><PanelLeftClose size={15} /></button>
 
129
  </div>
130
- <button className={cx('binder-book', sub === 'about' && 'on')} onClick={() => go(`book/${pid}/about`)}>
131
- <div className="binder-book-title">{bundle.project.title}</div>
132
- <div className="binder-book-sub">{bundle.project.genre || '未定题材'} · {PROJECT_STATUS[bundle.project.status] || bundle.project.status}</div>
133
- </button>
134
  <ContinueCard pid={pid} chapters={bundle.chapters} current={sub} />
135
 
136
- <div className="binder-section">
137
- <div className="binder-label">设定</div>
138
- <BinderLink on={sub === 'about'} icon={<Info size={15} />} onClick={() => go(`book/${pid}/about`)}>作品概览</BinderLink>
139
- <BinderLink on={sub === 'bible'} icon={<Users size={15} />} onClick={() => go(`book/${pid}/bible`)} meta={chars ? `${chars} 人` : ''}>作品圣经</BinderLink>
140
- <BinderLink on={sub === 'outline'} icon={<ListTree size={15} />} onClick={() => go(`book/${pid}/outline`)}>大纲</BinderLink>
141
- <BinderLink on={sub === 'refs'} icon={<Bookmark size={15} />} onClick={() => go(`book/${pid}/refs`)} meta={`${refs}/3`}>参考素材</BinderLink>
142
- <BinderLink on={sub === 'notes'} icon={<Highlighter size={15} />} onClick={() => go(`book/${pid}/notes`)} meta={openNotes ? `${openNotes} 待改` : ''}>批阅汇总</BinderLink>
143
- <BinderLink on={sub === 'changes'} icon={<History size={15} />} onClick={() => go(`book/${pid}/changes`)}>修改记录</BinderLink>
144
- <BinderLink on={sub === 'publish'} icon={<Send size={15} />} onClick={() => go(`book/${pid}/publish`)} meta={pubMeta}>发布台</BinderLink>
145
- <BinderLink on={sub === 'read'} icon={<BookOpenText size={15} />} onClick={() => go(`book/${pid}/read`)} meta={totalWords ? `${fmtNum(totalWords)} 字` : ''}>通读全书</BinderLink>
 
 
 
 
 
 
 
146
  </div>
147
 
148
  <div className="binder-section grow">
@@ -207,10 +212,10 @@ function ContinueCard({ pid, chapters, current, big }: { pid: string; chapters:
207
  )
208
  }
209
 
210
- function BinderLink({ on, icon, children, onClick, meta }: { on: boolean; icon: React.ReactNode; children: React.ReactNode; onClick: () => void; meta?: string }) {
211
  return (
212
- <button className={cx('binder-link', on && 'on')} onClick={onClick}>
213
- {icon}<span>{children}</span>{meta && <em>{meta}</em>}
214
  </button>
215
  )
216
  }
 
1
  import React, { useCallback, useEffect, useMemo, useState } from 'react'
2
+ import { ChevronLeft, ScrollText, Users, ListTree, Bookmark, Plus, PanelLeftClose, PanelLeftOpen, Info, FileText, BookOpenText, Highlighter, History, Send, Lock, ChevronDown } from 'lucide-react'
3
  import { Chapter, ProjectBundle, projectsApi, WriteMode } from '../api'
4
  import { cnNum, cx, fmtAgo, fmtDate, fmtNum, go, CHAPTER_STATUS, PROJECT_STATUS, useLocal } from '../lib'
5
  import { ErrorNote, Field, Loading, useConfirm, useToast, AutoText, Empty } from '../ui'
 
121
  return () => { alive = false }
122
  }, [pid, sub])
123
  const prog = useBookProgress(pid)
124
+ const [toolsOpen, setToolsOpen] = useLocal('xs_binder_tools', true)
125
  return (
126
  <aside className="binder">
127
  <div className="binder-top">
128
+ <button className="binder-back" onClick={() => go('shelf')} title="回到书房" aria-label="回到书房"><ChevronLeft size={15} />书房</button>
129
+ <button className={cx('binder-title', sub === 'about' && 'on')} onClick={() => go(`book/${pid}/about`)} title={`${bundle.project.title} · ${bundle.project.genre || '未定题材'} · ${PROJECT_STATUS[bundle.project.status] || bundle.project.status}`}>{bundle.project.title}</button>
130
+ <button className="icon-btn sm" onClick={onCollapse} title="收起目录" aria-label="收起目录"><PanelLeftClose size={15} /></button>
131
  </div>
 
 
 
 
132
  <ContinueCard pid={pid} chapters={bundle.chapters} current={sub} />
133
 
134
+ <div className="binder-section tools">
135
+ <button className="binder-label toggle" onClick={() => setToolsOpen(!toolsOpen)} aria-expanded={toolsOpen}>
136
+ 设定与工具<ChevronDown size={13} className={cx('bl-caret', !toolsOpen && 'closed')} />
137
+ {!toolsOpen && openNotes > 0 && <em className="bl-badge">{openNotes} 待改</em>}
138
+ </button>
139
+ {toolsOpen && (
140
+ <div className="binder-grid">
141
+ <BinderTile on={sub === 'about'} icon={<Info size={16} />} label="概览" tip="作品概览" onClick={() => go(`book/${pid}/about`)} />
142
+ <BinderTile on={sub === 'bible'} icon={<Users size={16} />} label="圣经" tip={`作品圣经${chars ? ` · ${chars} 人` : ''}`} onClick={() => go(`book/${pid}/bible`)} />
143
+ <BinderTile on={sub === 'outline'} icon={<ListTree size={16} />} label="大纲" tip="大纲" onClick={() => go(`book/${pid}/outline`)} />
144
+ <BinderTile on={sub === 'refs'} icon={<Bookmark size={16} />} label="素材" tip={`参考素材 · ${refs}/3`} onClick={() => go(`book/${pid}/refs`)} />
145
+ <BinderTile on={sub === 'notes'} icon={<Highlighter size={16} />} label="批阅" tip={`批阅汇总${openNotes ? ` · ${openNotes} 条待改` : ''}`} badge={openNotes} onClick={() => go(`book/${pid}/notes`)} />
146
+ <BinderTile on={sub === 'changes'} icon={<History size={16} />} label="修改" tip="修改记录" onClick={() => go(`book/${pid}/changes`)} />
147
+ <BinderTile on={sub === 'publish'} icon={<Send size={16} />} label="发布" tip={`发布台${pubMeta ? ` · 已发布 ${pubMeta}` : ''}`} onClick={() => go(`book/${pid}/publish`)} />
148
+ <BinderTile on={sub === 'read'} icon={<BookOpenText size={16} />} label="通读" tip={`通读全书${totalWords ? ` · ${fmtNum(totalWords)} 字` : ''}`} onClick={() => go(`book/${pid}/read`)} />
149
+ </div>
150
+ )}
151
  </div>
152
 
153
  <div className="binder-section grow">
 
212
  )
213
  }
214
 
215
+ function BinderTile({ on, icon, label, tip, onClick, badge }: { on: boolean; icon: React.ReactNode; label: string; tip: string; onClick: () => void; badge?: number }) {
216
  return (
217
+ <button className={cx('binder-tile', on && 'on')} onClick={onClick} title={tip} aria-label={tip}>
218
+ {icon}<span>{label}</span>{badge ? <em>{badge > 99 ? '99+' : badge}</em> : null}
219
  </button>
220
  )
221
  }
ui-src/src/rooms/Shelf.tsx CHANGED
@@ -1,14 +1,15 @@
1
  import React, { useState } from 'react'
2
- import { Plus, Shuffle, ArrowRight, BookMarked } from 'lucide-react'
3
- import { materialsApi, projectsApi, Project } from '../api'
4
  import { fmtAgo, fmtNum, go, GENRE, KIND, PROJECT_STATUS, useAsync } from '../lib'
5
- import { ErrorNote, Field, Loading, Modal, useToast, AutoText } from '../ui'
6
 
7
  const COVER_TONES = ['#7a3b2e', '#2f4a5a', '#4c5a3a', '#5b4636', '#3e3a5c', '#6b2f3f', '#2f5550', '#5a4a2a']
8
  const tone = (s: string) => COVER_TONES[[...s].reduce((a, c) => a + c.charCodeAt(0), 0) % COVER_TONES.length]
9
 
10
  export default function Shelf() {
11
  const { data, error, loading, reload } = useAsync(() => projectsApi.list(), [])
 
12
  const [creating, setCreating] = useState(false)
13
  const projects = data?.projects || []
14
  return (
@@ -25,9 +26,10 @@ export default function Shelf() {
25
  {loading && !data && <Loading />}
26
  {error && <ErrorNote error={error} onRetry={reload} />}
27
 
 
28
  {data && (
29
  <div className="bookshelf">
30
- {projects.map(p => <BookCover key={p.project_id} p={p} />)}
31
  <button className="book-new" onClick={() => setCreating(true)}>
32
  <Plus size={22} />
33
  <span>开一本新书</span>
@@ -55,7 +57,7 @@ export default function Shelf() {
55
  )
56
  }
57
 
58
- function BookCover({ p }: { p: Project }) {
59
  const progress = p.target_words ? Math.min(1, 0) : 0
60
  return (
61
  <button className="book" onClick={() => go(`book/${p.project_id}`)} style={{ ['--cover' as any]: tone(p.title) }}>
@@ -64,6 +66,7 @@ function BookCover({ p }: { p: Project }) {
64
  <div className="book-title">{p.title}</div>
65
  <div className="book-genre">{p.genre || '未定题材'}</div>
66
  <div className="book-seal">{PROJECT_STATUS[p.status] || p.status || '构思中'}</div>
 
67
  </div>
68
  <div className="book-meta">
69
  <div className="book-meta-title">{p.title}</div>
@@ -76,6 +79,40 @@ function BookCover({ p }: { p: Project }) {
76
  )
77
  }
78
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79
  function DailySpark() {
80
  const { data, loading, reload } = useAsync(() => materialsApi.random({ n: 1, q: 4, carded: 1 }), [])
81
  const it = data?.items?.[0]
 
1
  import React, { useState } from 'react'
2
+ import { Plus, Shuffle, ArrowRight, BookMarked, Lock, Unlock } from 'lucide-react'
3
+ import { agentApi, materialsApi, projectsApi, Project } from '../api'
4
  import { fmtAgo, fmtNum, go, GENRE, KIND, PROJECT_STATUS, useAsync } from '../lib'
5
+ import { ErrorNote, Field, Loading, Modal, useToast, useConfirm, AutoText } from '../ui'
6
 
7
  const COVER_TONES = ['#7a3b2e', '#2f4a5a', '#4c5a3a', '#5b4636', '#3e3a5c', '#6b2f3f', '#2f5550', '#5a4a2a']
8
  const tone = (s: string) => COVER_TONES[[...s].reduce((a, c) => a + c.charCodeAt(0), 0) % COVER_TONES.length]
9
 
10
  export default function Shelf() {
11
  const { data, error, loading, reload } = useAsync(() => projectsApi.list(), [])
12
+ const focus = useAsync(() => agentApi.focus(), [])
13
  const [creating, setCreating] = useState(false)
14
  const projects = data?.projects || []
15
  return (
 
26
  {loading && !data && <Loading />}
27
  {error && <ErrorNote error={error} onRetry={reload} />}
28
 
29
+ {data && <FocusBar projects={projects} focusId={focus.data?.project_id || null} focusTitle={focus.data?.title || ''} history={focus.data?.history || []} reload={focus.reload} />}
30
  {data && (
31
  <div className="bookshelf">
32
+ {projects.map(p => <BookCover key={p.project_id} p={p} focused={focus.data?.project_id === p.project_id} />)}
33
  <button className="book-new" onClick={() => setCreating(true)}>
34
  <Plus size={22} />
35
  <span>开一本新书</span>
 
57
  )
58
  }
59
 
60
+ function BookCover({ p, focused }: { p: Project; focused?: boolean }) {
61
  const progress = p.target_words ? Math.min(1, 0) : 0
62
  return (
63
  <button className="book" onClick={() => go(`book/${p.project_id}`)} style={{ ['--cover' as any]: tone(p.title) }}>
 
66
  <div className="book-title">{p.title}</div>
67
  <div className="book-genre">{p.genre || '未定题材'}</div>
68
  <div className="book-seal">{PROJECT_STATUS[p.status] || p.status || '构思中'}</div>
69
+ {focused && <div className="book-ai" title="写作 AI 现在只处理这本书"><Lock size={11} />AI 在这本</div>}
70
  </div>
71
  <div className="book-meta">
72
  <div className="book-meta-title">{p.title}</div>
 
79
  )
80
  }
81
 
82
+ /* 书本锁:写作 AI 一次只处理一本书,锁定期间其他书对它完全关闭 */
83
+ function FocusBar({ projects, focusId, focusTitle, history, reload }: { projects: Project[]; focusId: string | null; focusTitle: string; history: { title: string; at: string; from: string }[]; reload: () => void }) {
84
+ const toast = useToast()
85
+ const confirm = useConfirm()
86
+ const [pick, setPick] = useState('')
87
+ const lock = async (id: string) => {
88
+ const p = projects.find(x => x.project_id === id); if (!p) return
89
+ if (focusId && focusId !== id && !(await confirm({ title: `让写作 AI 换到《${p.title}》?`, body: `换过去以后,它就读不到《${focusTitle}》的任何内容了。为了不把两本书的思路混在一起,换书时最好也开一个新的对话。`, ok: '换书' }))) return
90
+ try { await agentApi.setFocus(id, '作者在书房里指定'); toast(`写作 AI 现在只处理《${p.title}》`, 'ok'); reload() } catch (e: any) { toast(e.message, 'err') }
91
+ }
92
+ const unlock = async () => {
93
+ if (!(await confirm({ title: '解除书本锁?', body: '解除后写作 AI 能看到书房里所有书。它下次开工时会重新锁定一本。', ok: '解除' }))) return
94
+ try { await agentApi.clearFocus(); toast('已解除', 'ok'); reload() } catch (e: any) { toast(e.message, 'err') }
95
+ }
96
+ const last = history[0]
97
+ return (
98
+ <div className={`focus-bar ${focusId ? 'on' : ''}`}>
99
+ {focusId ? <Lock size={15} /> : <Unlock size={15} />}
100
+ <div className="focus-text">
101
+ {focusId ? <><b>写作 AI 现在只处理《{focusTitle}》</b><span>其他书的设定、正文、批注对它全部关闭,不会把几本书的思路混在一起。{last && last.from ? ` 上次换书:从《${last.from}》换到《${last.title}》,${fmtAgo(last.at)}。` : ''}</span></>
102
+ : <><b>写作 AI 还没锁定书</b><span>它开工时会先锁定一本书,锁定期间读不到其他书。</span></>}
103
+ </div>
104
+ {projects.length > 1 && (
105
+ <select className="input auto" value={pick} onChange={e => { setPick(''); if (e.target.value) lock(e.target.value) }} aria-label="让 AI 换到哪本书">
106
+ <option value="">{focusId ? '换一本…' : '锁定一本…'}</option>
107
+ {projects.filter(p => p.project_id !== focusId).map(p => <option key={p.project_id} value={p.project_id}>{p.title}</option>)}
108
+ </select>
109
+ )}
110
+ {projects.length === 1 && !focusId && <button className="btn ghost small" onClick={() => lock(projects[0].project_id)}>锁定这本</button>}
111
+ {focusId && <button className="link-btn" onClick={unlock}>解除</button>}
112
+ </div>
113
+ )
114
+ }
115
+
116
  function DailySpark() {
117
  const { data, loading, reload } = useAsync(() => materialsApi.random({ n: 1, q: 4, carded: 1 }), [])
118
  const it = data?.items?.[0]
ui-src/src/styles.css CHANGED
@@ -1980,3 +1980,39 @@ details.older[open] { display: flex; flex-direction: column; gap: 8px; }
1980
  .wlock { display: flex; align-items: center; gap: 8px; padding: 7px 14px 7px 52px; font-size: 12.5px; background: var(--blue-soft); color: var(--blue); border-bottom: 1px solid color-mix(in srgb, var(--blue) 20%, transparent); }
1981
  .wlock span { flex: 1; min-width: 0; line-height: 1.5; }
1982
  .wlock svg { flex: none; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1980
  .wlock { display: flex; align-items: center; gap: 8px; padding: 7px 14px 7px 52px; font-size: 12.5px; background: var(--blue-soft); color: var(--blue); border-bottom: 1px solid color-mix(in srgb, var(--blue) 20%, transparent); }
1981
  .wlock span { flex: 1; min-width: 0; line-height: 1.5; }
1982
  .wlock svg { flex: none; }
1983
+
1984
+ /* ---------- 目录:顶部压缩,给章节列表留出空间 ---------- */
1985
+ .binder-top { gap: 4px; padding: 8px 8px 6px 8px; }
1986
+ .binder-back { flex: none; }
1987
+ .binder-title { flex: 1; min-width: 0; font-family: var(--serif); font-weight: 700; font-size: 14.5px; color: var(--ink); text-align: left; padding: 4px 6px; border-radius: 6px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
1988
+ .binder-title:hover { background: var(--bg-2); }
1989
+ .binder-title.on { color: var(--accent); }
1990
+ .binder .continue-card { padding: 6px 10px 7px; gap: 0; margin-bottom: 4px; }
1991
+ .binder .continue-card .cc-m { display: none; }
1992
+ .binder .continue-card .cc-t { font-size: 13.5px; }
1993
+ .binder .continue-card .cc-bar { margin-top: 4px; }
1994
+ .binder-section.tools { padding: 2px 8px 4px; }
1995
+ .binder-label.toggle { width: 100%; background: none; border: 0; cursor: pointer; font: inherit; font-size: 11.5px; letter-spacing: .1em; color: var(--ink-3); font-weight: 600; }
1996
+ .binder-label.toggle:hover { color: var(--ink); }
1997
+ .bl-caret { transition: transform .15s; }
1998
+ .bl-caret.closed { transform: rotate(-90deg); }
1999
+ .bl-badge { margin-left: auto; font-style: normal; letter-spacing: 0; font-weight: 500; color: var(--accent); }
2000
+ .binder-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 2px; padding: 0 2px; }
2001
+ .binder-tile { position: relative; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 3px; height: 46px; border-radius: 8px; color: var(--ink-2); font-size: 11.5px; }
2002
+ .binder-tile:hover { background: var(--bg-2); color: var(--ink); }
2003
+ .binder-tile.on { background: var(--accent-soft); color: var(--accent); font-weight: 500; }
2004
+ .binder-tile em { position: absolute; top: 3px; right: calc(50% - 20px); min-width: 15px; height: 15px; padding: 0 4px; border-radius: 99px; background: var(--accent); color: var(--accent-ink); font-style: normal; font-size: 10px; line-height: 15px; text-align: center; }
2005
+ .binder-section.grow { border-top: 1px solid var(--line); margin-top: 2px; }
2006
+ @media (max-width: 760px) {
2007
+ .binder-foot { display: none; }
2008
+ .binder-tile { height: 48px; }
2009
+ }
2010
+
2011
+ /* 书房:书本锁 */
2012
+ .focus-bar { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; padding: 11px 14px; border-radius: var(--r); background: var(--surface); border: 1px solid var(--line); margin: 0 0 18px; color: var(--ink-3); font-size: 13px; }
2013
+ .focus-bar.on { background: var(--blue-soft); border-color: color-mix(in srgb, var(--blue) 25%, transparent); color: var(--blue); }
2014
+ .focus-bar > svg { flex: none; }
2015
+ .focus-text { flex: 1 1 260px; min-width: 0; display: flex; flex-direction: column; gap: 2px; }
2016
+ .focus-text b { color: var(--ink); font-weight: 600; }
2017
+ .focus-text span { color: var(--ink-3); font-size: 12.5px; line-height: 1.55; }
2018
+ .book-ai { position: absolute; left: 50%; bottom: 10px; transform: translateX(-50%); display: inline-flex; align-items: center; gap: 3px; padding: 2px 7px; border-radius: 99px; background: rgba(255,255,255,.9); color: var(--blue); font-size: 10.5px; font-weight: 600; white-space: nowrap; }