Files
deepseek-harness/packages/session/session-title/tests/session-title.spec.ts
T
_KermanandTianyi Cui fb79a944f5 refactor(llm): separate durable producer sources from request inputs
Give durable user context its producer-owned source kind instead of a generic plugin wrapper. The V3-to-V4 conversion preserves the frozen rename and collision rules, all own JSON metadata, event coordinates, and historical request-only kinds. Native catalog and JSONL admission retain source validation so unknown attribution can survive without its producer while malformed owned sources are refused.

Use an explicit user-only RequestUserInput for auxiliary LLM prompts that do not own durable message identity. Auto Review and compaction remove their request-only source registrations while retaining prompt content and freezing; provider serializers and projections keep the same wire data, assistant replay isolation, image ordering, and tool correlation. Session writes, Agent delivery, and recorded title requests continue to require identified durable messages.

Bind the saved compatibility policy only to user sources and qualify tmux location attribution without weakening fixed system, model, or tool semantics. Rebuild the current inventory and unpublished V4 acknowledgement on the actual tool-role parent, preserving its rationale and all accepted historical records. The catalog format version records tooling metadata; Session remains V4. Developer-role policy and activation belong to their own feature.

The latest-master Messages adapter, serialization, request-input typing, EpochHeader reservation, and attribution checks pass 103 tests across five files. The retained V3 Messages input-history snapshot passes through the source profile; Host/Client typechecks and all 41 documentation gates pass. The generated comparison records four changed roots and 447 unchanged type fingerprints. Latest-master ARIA changes are retained, with producer source labels applied independently; new Messages fixtures retain their producer names as declared source kinds and use the fixed system-message helper; recorded Session generations are unchanged by this regrouping.

Co-authored-by: Tianyi Cui <[email protected]>
2026-09-18 19:07:12 +08:00

189 lines
6.7 KiB
TypeScript

import { createUserMessage } from '@deepseek-ai/dsh-llm'
import type { ContextFormed } from '@deepseek-ai/dsh-llm'
import { Context } from '@deepseek-ai/cordis'
import { describe, expect, it } from 'vitest'
import SessionStore, { Session, SessionId, SessionSeq } from '@deepseek-ai/dsh-session'
import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
import SessionTitleService, {
SessionTitleProviderId,
fallbackSessionTitle,
foldSessionTitle,
normalizeSessionTitle,
truncateTitleUtf8,
} from '@deepseek-ai/dsh-session-title'
declare module '@deepseek-ai/dsh-llm' {
interface MessageSourceMap {
'seed': { kind: 'seed' } & ContextFormed
}
}
const CONFIG = {
fallbackMaxWords: 5,
fallbackMaxBytes: 40,
maxTitleBytes: 80,
} as const
async function settleTitles(): Promise<void> {
await new Promise(resolve => setTimeout(resolve, 0))
}
describe('session title normalization', () => {
it('removes terminal controls, collapses whitespace, and applies word and UTF-8 byte caps', () => {
expect(normalizeSessionTitle('\u001B]0;stolen\u0007 Hello\t brave\nnew world ', 80))
.toBe('Hello brave new world')
expect(fallbackSessionTitle('one two three four', 3, 80)).toBe('one two three')
expect(fallbackSessionTitle('你好世界', 5, 7)).toBe('你好')
expect(Buffer.byteLength(fallbackSessionTitle('😀😀', 5, 5), 'utf8')).toBe(4)
})
it('rejects non-positive and fractional public limits', () => {
expect(() => truncateTitleUtf8('title', 0)).toThrow(/maxBytes must be a positive integer/)
expect(() => fallbackSessionTitle('title', 1.5, 10)).toThrow(/maxWords must be a positive integer/)
})
})
describe('SessionTitleService', () => {
it('logs and folds an immediate fallback after the first eligible human text message', async () => {
const ctx = new Context()
await ctx.plugin(SessionStore)
await ctx.plugin(SessionProjectionRegistry)
await ctx.plugin(SessionTitleService, CONFIG)
const session = ctx.sessions.create(SessionId('fresh'))
session.append('turn/start', {
turn: 1,
})
const message = session.append('user/message', createUserMessage({
content: [{ type: 'text', text: ' Build\nlog-backed session titles please ' }],
source: { kind: 'user' },
}), { surfaceOp: 'append' })
await settleTitles()
const titleEvent = session.snapshotEvents().findLast(event => event.type === 'session/title')
expect(titleEvent).toMatchObject({
type: 'session/title',
seq: 2,
data: {
title: 'Build log-backed session titles please',
messageSeqs: [message.seq],
source: { kind: 'fallback' },
},
})
expect(ctx.sessionTitle.get(session)).toEqual({
title: 'Build log-backed session titles please',
messageSeqs: [message.seq],
source: { kind: 'fallback' },
eventSeq: 2,
updatedAt: titleEvent?.time,
})
expect(session.deriveMessages()).toHaveLength(1)
expect(session.surface.nodes).toEqual([message.seq])
})
it('derives a fallback title from the direct prompt instead of injected context', async () => {
const ctx = new Context()
await ctx.plugin(SessionStore)
await ctx.plugin(SessionProjectionRegistry)
await ctx.plugin(SessionTitleService, CONFIG)
const session = ctx.sessions.create(SessionId('prefixed-title'))
session.append('user/message', createUserMessage({
content: [{ type: 'text', text: 'Referenced session snapshot' }],
source: {
kind: 'session-reference',
form: 'recall',
version: 1,
references: [],
},
}), { surfaceOp: 'append' })
session.append('turn/start', {
turn: 1,
})
session.append('user/message', createUserMessage({
content: [{ type: 'text', text: 'Explain this referenced session' }],
source: { kind: 'user' },
}), { surfaceOp: 'append' })
await settleTitles()
expect(ctx.sessionTitle.get(session)?.title).toBe('Explain this referenced session')
})
it('waits through synthetic, empty, and non-text messages, then keeps the first fallback', async () => {
const ctx = new Context()
await ctx.plugin(SessionStore)
await ctx.plugin(SessionProjectionRegistry)
await ctx.plugin(SessionTitleService, CONFIG)
const session = ctx.sessions.create(SessionId('eligibility'))
session.append('turn/start', {
turn: 1,
})
session.append('user/message', createUserMessage({
content: [{ type: 'text', text: 'plugin text' }],
source: { kind: 'seed' },
}), { surfaceOp: 'append' })
session.append('user/message', createUserMessage({
content: [{ type: 'reasoning', text: 'not visible text' }],
source: { kind: 'user' },
}), { surfaceOp: 'append' })
session.append('user/message', createUserMessage({
content: [{ type: 'text', text: ' \n\t ' }],
source: { kind: 'user' },
}), { surfaceOp: 'append' })
await settleTitles()
expect(ctx.sessionTitle.get(session)).toBeUndefined()
const eligible = session.append('user/message', createUserMessage({
content: [{ type: 'text', text: 'first real prompt' }],
source: { kind: 'user' },
}), { surfaceOp: 'append' })
await settleTitles()
const first = ctx.sessionTitle.get(session)
session.append('user/message', createUserMessage({
content: [{ type: 'text', text: 'later prompt' }],
source: { kind: 'user' },
}), { surfaceOp: 'append' })
await settleTitles()
expect(first?.messageSeqs).toEqual([eligible.seq])
expect(ctx.sessionTitle.get(session)).toEqual(first)
expect(session.snapshotEvents().filter(event => event.type === 'session/title')).toHaveLength(1)
})
it('folds the latest title event during replay', () => {
const seed = Session.create(SessionId('source'))
seed.append('session/title', {
title: 'Earlier',
messageSeqs: [SessionSeq(1)],
source: { kind: 'fallback' },
})
seed.append('session/title', {
title: 'Later',
messageSeqs: [SessionSeq(1), SessionSeq(4)],
source: {
kind: 'provider',
provider: SessionTitleProviderId('test-provider'),
model: { provider: 'mock', model: 'title-model' },
},
})
expect(foldSessionTitle(seed.snapshotEvents())).toEqual({
title: 'Later',
messageSeqs: [1, 4],
source: {
kind: 'provider',
provider: SessionTitleProviderId('test-provider'),
model: { provider: 'mock', model: 'title-model' },
},
eventSeq: 1,
updatedAt: seed.snapshotEvents()[1]?.time,
})
})
it('folds an empty or title-less log to undefined', () => {
expect(foldSessionTitle([])).toBeUndefined()
const empty = Session.create(SessionId('no-title'))
expect(foldSessionTitle(empty.snapshotEvents())).toBeUndefined()
})
})