Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ All notable changes to DreamCoder will be documented in this file.

### Fixed

- A deleted session no longer comes back as an empty session in the sidebar. It happened to sessions with a title you had set that were deleted while their agent was still running.
- Terminal text is no longer spaced out. The terminal measured its character width with a fallback font instead of the mono font it draws with.
- A terminal tab starts one shell. When a terminal was started again before the first start finished, for example because its working folder arrived late or Restart was clicked twice, two terminals and two shells were created, the second showing as a dark strip under the first.
- The reply-to-selection button appears when a text selection in a message ends outside the message.
Expand Down
1 change: 1 addition & 0 deletions docs/features/session-state/tech-design.md
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,7 @@ reducer 是纯函数,不做 IO,不调用 CLI,便于单测。所有副作
统一负责会话状态与 transcript 的读写。

- **写**:订阅 store 的变化,只处理标为持久化的字段,写成对应的 transcript 条目。所有写入(追加、整体重写、改名)经过同一个按会话排队的写队列,扩展现在只给权限模式用的 `permissionModeWrites`(`sessionService.ts:358`)。
- **删除也在这个队列里**(`SessionService` 的 `removeSessionFile`,`deleteSession` 和 `deleteSessionFile` 都走它)。写入是「找到文件、读、追加」几步,追加用的 `appendFile` 会把不存在的文件建出来;删除如果不排队,落在某次写入的「找到文件」和「追加」之间,刚删掉的文件就被写回来,变成一个只有一两行元数据、没有父子关系的空会话出现在列表里。最常见的触发是下面的「CLI 退出后补写标题」:删除会话时先停 CLI,CLI 退出触发补写,紧接着就是删除。排队之后两者不会交错:写入先到就完整写完再删,删除先到写入就找不到文件、什么也不做。
- **定位**:会话文件的位置在会话创建时确定,之后所有写入都写到这个文件,不再按当前工作目录重新计算。
- **读**:会话第一次进入内存时,从 transcript 按固定顺序恢复持久化字段,见「数据模型」。
- **CLI 退出后补写标题**:CLI 退出或压缩上下文时,会把它缓存的自定义标题重新追加到文件末尾(`src/utils/sessionStorage.ts` 的 `reAppendSessionMetadata`),目的是让标题留在读取时扫描的末尾窗口内(量级几十 KB)。它会先读末尾吸收外部改名,但改名之后又输出超过这个量级才退出时读不到,会写回旧标题。所以 `ProcessSupervisor` 报告进程退出后,`SessionPersistence` 检查文件末尾最后一条 `custom-title`,与状态里的标题不一致时再追加一条。不改 CLI 的写回,因为服务端读列表也只扫末尾窗口(#138),这个重写对我们同样有用。权限模式不受影响:CLI 只在会话文件还没建出来时缓存权限模式,退出时不重写。
Expand Down
2 changes: 1 addition & 1 deletion docs/features/side-chat/tech-design.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
- 显示在父会话右侧面板里,作为一个标签页,和终端、浏览器、文件并列。一个会话可以开多个。
- side chat 页面只显示它自己的消息,不显示从父会话继承来的部分。模型的上下文仍然是完整的分叉。
- 两个入口:面板新标签页里的 "Side chat";在主会话里选中文字,弹出条点 "Start a side chat",选中的内容作为引用放进 side chat 的输入框。
- 标签菜单可以重命名、Detach(变成普通的分叉会话,出现在左侧列表),以及关闭。关闭就是删除,不二次确认,正在运行的会先停掉。
- 标签菜单可以重命名、Detach(变成普通的分叉会话,出现在左侧列表),以及关闭。关闭就是删除,不二次确认,正在运行的会先停掉。删除和会话文件的其它写入在同一个按会话排队的队列里(见[会话状态设计](../session-state/tech-design.md)的「SessionPersistence」),所以停掉 CLI 时触发的补写标题不会把刚删的文件写回来。
- 删除父会话时,它的 side chat 一起删除,不做归档。
- 标题是 `btw: <第一条用户输入>`。
- 会话之间互发消息走现有路径,见[会话关系技术设计](../session-links/tech-design.md)。
Expand Down
62 changes: 61 additions & 1 deletion src/server/__tests__/sessions.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { describe, it, expect, beforeEach, afterEach } from 'bun:test'
import { describe, it, expect, beforeEach, afterEach, spyOn } from 'bun:test'
import * as fs from 'node:fs/promises'
import { execFileSync } from 'node:child_process'
import * as path from 'node:path'
Expand Down Expand Up @@ -1305,6 +1305,66 @@ describe('SessionService', () => {
expect((await service.getSessionLaunchInfo(sessionId))?.worktreeSession).toMatchObject({ worktreePath: path.join(workDir, 'wt') })
})

describe('a session deleted while something is being written to it', () => {
type FileStep = 'readJsonlFile' | 'appendJsonlEntry'
type FileSteps = Record<FileStep, (filePath: string, ...rest: unknown[]) => Promise<unknown>>

function holdNext(step: FileStep) {
const steps = service as unknown as FileSteps
const run = steps[step].bind(service)
let reach!: () => void
let release!: () => void
const reached = new Promise<void>((resolve) => { reach = resolve })
const released = new Promise<void>((resolve) => { release = resolve })
const spy = spyOn(steps, step).mockImplementationOnce(async (filePath, ...rest) => {
reach()
await released
return run(filePath, ...rest)
})
return { reached, release, restore: () => spy.mockRestore() }
}

const writes: Array<[string, FileStep, (sessionId: string) => Promise<unknown>]> = [
['its process exits and its unchanged custom title is checked', 'readJsonlFile', (sessionId) => service.restoreCustomTitle(sessionId, 'Mine')],
['its process exits and its custom title is written again', 'appendJsonlEntry', (sessionId) => service.restoreCustomTitle(sessionId, 'Renamed')],
['it is renamed', 'appendJsonlEntry', (sessionId) => service.renameSession(sessionId, 'Renamed')],
['its permission mode is recorded', 'appendJsonlEntry', (sessionId) => service.appendSessionPermissionMode(sessionId, 'acceptEdits')],
]
const removals: Array<['deleteSession' | 'deleteSessionFile', (sessionId: string) => Promise<void>]> = [
['deleteSession', (sessionId) => service.deleteSession(sessionId)],
['deleteSessionFile', (sessionId) => service.deleteSessionFile(sessionId)],
]

for (const [what, step, write] of writes) {
for (const [how, remove] of removals) {
it(`stays deleted when ${what} at that moment (${how})`, async () => {
const workDir = path.join(tmpDir, 'workspace', 'deleted-while-written')
await fs.mkdir(workDir, { recursive: true })
const { sessionId } = await service.createSession(workDir)
await service.renameSession(sessionId, 'Mine')
const hold = holdNext(step)
const lookups = spyOn(service, 'findSessionFile')
try {
const writing = write(sessionId)
await hold.reached
lookups.mockClear()
const removing = remove(sessionId)
const startedAtOnce = lookups.mock.calls.length > 0
if (startedAtOnce) await removing
hold.release()
await Promise.all([writing, removing])
} finally {
hold.restore()
lookups.mockRestore()
}

expect(await service.findSessionFile(sessionId)).toBeNull()
expect((await service.listSessions()).sessions.map((session) => session.id)).not.toContain(sessionId)
})
}
}
})

it('appends the custom title again only when the file ends with a different one', async () => {
const workDir = path.join(tmpDir, 'workspace', 'title-restore')
await fs.mkdir(workDir, { recursive: true })
Expand Down
18 changes: 11 additions & 7 deletions src/server/services/sessionService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1360,13 +1360,19 @@ export class SessionService {
return { sessionId, workDir: absWorkDir }
}

private removeSessionFile(sessionId: string): Promise<boolean> {
return this.enqueueSessionWrite(sessionId, async () => {
const found = await this.findSessionFile(sessionId)
if (!found) return false
await fs.unlink(found.filePath)
return true
})
}

async deleteSession(sessionId: string): Promise<void> {
const found = await this.findSessionFile(sessionId)
if (!found) {
if (!(await this.removeSessionFile(sessionId))) {
throw ApiError.notFound(`Session not found: ${sessionId}`)
}

await fs.unlink(found.filePath)
}

async deleteSessions(sessionIds: string[]): Promise<DeleteSessionsResult> {
Expand Down Expand Up @@ -1522,9 +1528,7 @@ export class SessionService {
}

async deleteSessionFile(sessionId: string): Promise<void> {
const found = await this.findSessionFile(sessionId)
if (!found) return
await fs.unlink(found.filePath)
await this.removeSessionFile(sessionId)
}

setSessionParent(sessionId: string, parent: SessionParent): Promise<void> {
Expand Down
Loading