Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

fix(extensions): refuse a tool call approved for a replaced handler binding

Akarshan Biswas2c242661c766
diff --git a/web-app/src/hooks/__tests__/useTools.test.ts b/web-app/src/hooks/__tests__/useTools.test.ts
index 172e2d3ea..99a786172 100644
--- a/web-app/src/hooks/__tests__/useTools.test.ts
+++ b/web-app/src/hooks/__tests__/useTools.test.ts
@@ -235,7 +235,7 @@ describe('useTools', () => {
useContributions.setState({
tools: {
'acme.one': {
- echo: { ...declared, handler: async () => ({ content: [] }) },
+ echo: { ...declared, handler: async () => ({ content: [] }), generation: 1 },
},
},
})
diff --git a/web-app/src/lib/extensions/__tests__/contributions.test.ts b/web-app/src/lib/extensions/__tests__/contributions.test.ts
index 15e4afc45..72eba363e 100644
--- a/web-app/src/lib/extensions/__tests__/contributions.test.ts
+++ b/web-app/src/lib/extensions/__tests__/contributions.test.ts
@@ -119,6 +119,42 @@ describe('ContributionStore', () => {
expect(store.getState().providers['acme.one'].p.handler).toBeUndefined()
})
+ it('stamps each tool binding with a fresh host-owned generation', () => {
+ const store = new ContributionStore()
+ store.registerExtension(helloManifest('acme.one'))
+ const gen = () => store.getState().tools['acme.one'].echo.generation
+ expect(gen()).toBeUndefined()
+ const first = store.registerTool('acme.one', 'echo', vi.fn())
+ const a = gen()
+ expect(a).toEqual(expect.any(Number))
+ first.dispose()
+ expect(gen()).toBeUndefined()
+ store.registerTool('acme.one', 'echo', vi.fn())
+ expect(gen()).not.toBe(a)
+ expect(gen()).toBeGreaterThan(a!)
+ })
+
+ it('ignores a generation carried by the manifest declaration', () => {
+ const store = new ContributionStore()
+ store.registerExtension(
+ manifest('acme.two', {
+ permissions: ['tools'],
+ contributes: {
+ tools: [
+ {
+ name: 'echo',
+ description: 'Echo',
+ inputSchema: { type: 'object' },
+ generation: 1,
+ } as never,
+ ],
+ },
+ })
+ )
+ store.registerTool('acme.two', 'echo', vi.fn())
+ expect(store.getState().tools['acme.two'].echo.generation).not.toBe(1)
+ })
+
it('treats inherited property names as undeclared', async () => {
const store = new ContributionStore()
store.registerExtension(helloManifest('acme.one'))
diff --git a/web-app/src/lib/extensions/__tests__/host.test.ts b/web-app/src/lib/extensions/__tests__/host.test.ts
index fa9ab90ba..1c5f9ac34 100644
--- a/web-app/src/lib/extensions/__tests__/host.test.ts
+++ b/web-app/src/lib/extensions/__tests__/host.test.ts
@@ -8,6 +8,7 @@ import {
} from '@janhq/core'
import { useGeneralSetting } from '@/hooks/useGeneralSetting'
import { ExtensionHost, toastTitle } from '../host'
+import { listExtensionTools } from '../tools'
import { loopbackFetch } from '@/lib/loopback-fetch'
import { builtin, manifest } from './fixtures'
import { memoryAppSettings, memorySecrets } from './memory'
@@ -288,6 +289,51 @@ describe('ExtensionHost', () => {
error.mockRestore()
})
+ it('gives a rebound same-schema tool a new generation and refuses a call approved for the old one', async () => {
+ const replies = ['old', 'new']
+ const host = newHost()
+ const def = builtin(
+ manifest('jan.regen', {
+ permissions: ['tools'],
+ contributes: {
+ tools: [
+ { name: 'echo', description: 'Echo', inputSchema: { type: 'object' } },
+ ],
+ },
+ }),
+ {
+ activate: (ctx) => {
+ const reply = replies.shift()!
+ ctx.subscriptions.add(
+ ctx.tools.registerTool('echo', async () => ({
+ content: [{ type: 'text', text: reply }],
+ }))
+ )
+ },
+ }
+ )
+ const listed = () => listExtensionTools(host.contributions.getState())
+ await host.activateBuiltins([def])
+ const [before] = listed()
+ expect(await host.callTool('jan.regen', 'echo', {}, { generation: before.generation })).toEqual({
+ content: [{ type: 'text', text: 'old' }],
+ })
+ await host.deactivateAll()
+ expect(listed()).toEqual([])
+ await host.activateBuiltins([def])
+ const [after] = listed()
+ // Identical declaration, different binding: only `generation` tells them apart.
+ expect({ ...after, generation: 0 }).toEqual({ ...before, generation: 0 })
+ expect(after.generation).not.toBe(before.generation)
+ expect(JSON.stringify(after)).not.toBe(JSON.stringify(before))
+ const stale = await host.callTool('jan.regen', 'echo', {}, { generation: before.generation })
+ expect(stale.error).toMatch(/changed since it was offered/)
+ expect(
+ await host.callTool('jan.regen', 'echo', {}, { generation: after.generation })
+ ).toEqual({ content: [{ type: 'text', text: 'new' }] })
+ expect(replies).toEqual([])
+ })
+
it('ignores a second activation of an active built-in and reactivates after deactivateAll', async () => {
const activate = vi.fn()
const host = newHost()
diff --git a/web-app/src/lib/extensions/__tests__/tools.test.ts b/web-app/src/lib/extensions/__tests__/tools.test.ts
index 0cf9822ad..98d946e0e 100644
--- a/web-app/src/lib/extensions/__tests__/tools.test.ts
+++ b/web-app/src/lib/extensions/__tests__/tools.test.ts
@@ -15,6 +15,7 @@ const tool = (name: string, bound = true) => ({
handler: bound
? async () => ({ content: [] })
: undefined,
+ generation: bound ? 1 : undefined,
})
const state = (
@@ -71,6 +72,22 @@ describe('listExtensionTools', () => {
expect(tools[0].server).toBe('ext:acme.one')
})
+ it('exposes the host generation and omits a handler without one', () => {
+ const [one] = listExtensionTools(
+ state({ 'acme.one': { t: { ...tool('t'), generation: 7 } } })
+ )
+ expect(one.generation).toBe(7)
+ const [two] = listExtensionTools(
+ state({ 'acme.one': { t: { ...tool('t'), generation: 8 } } })
+ )
+ expect(JSON.stringify(two)).not.toBe(JSON.stringify(one))
+ expect(
+ listExtensionTools(
+ state({ 'acme.one': { t: { ...tool('t'), generation: undefined } } })
+ )
+ ).toEqual([])
+ })
+
it('never moves a wire name to another extension when one loads', () => {
const before = listExtensionTools(state({ 'acme.x-foo': { t: tool('t') } }))
const after = listExtensionTools(
diff --git a/web-app/src/lib/extensions/contributions.ts b/web-app/src/lib/extensions/contributions.ts
index cd6ee9c6b..556efbc2b 100644
--- a/web-app/src/lib/extensions/contributions.ts
+++ b/web-app/src/lib/extensions/contributions.ts
@@ -22,7 +22,15 @@ import type { L10nTables } from './l10n'
export type RegisteredCommand = CommandContribution & {
handler?: CommandHandler
}
-export type RegisteredTool = ToolContribution & { handler?: ToolHandler }
+export type RegisteredTool = ToolContribution & {
+ handler?: ToolHandler
+ /**
+ * Host-assigned identity of the live binding: set on every bind, cleared on
+ * dispose, never reused. Not extension-provided (`bind` overwrites whatever
+ * a manifest carried), so two bindings of an identical declaration differ.
+ */
+ generation?: number
+}
export type RegisteredProvider = ProviderContribution & {
handler?: ProviderHandlers
}
@@ -103,6 +111,9 @@ const without = <T>(
return next
}
+// Process-wide, so bindings of different stores or reloads never share one.
+let lastGeneration = 0
+
/** The app-wide contributions, read by the host renderers. */
export const useContributions = create<ContributionState>()(emptyState)
@@ -254,6 +265,7 @@ export class ContributionStore {
'E_INVALID_ARGS',
`'${entryId}' is already registered`
)
+ const generation = slice === 'tools' ? ++lastGeneration : undefined
const set = (next: typeof value | undefined) =>
this.store.setState((s) => {
const entries = handlerSlices(s)[slice]
@@ -266,6 +278,10 @@ export class ContributionStore {
[extensionId]: withEntry<HandlerEntries[S]>(current, entryId, {
...entry,
handler: next,
+ // Always overwritten, never inherited from the declaration.
+ ...(slice === 'tools'
+ ? { generation: next === undefined ? undefined : generation }
+ : {}),
}),
},
}
diff --git a/web-app/src/lib/extensions/host.ts b/web-app/src/lib/extensions/host.ts
index 4f4d482c7..8fb7f7257 100644
--- a/web-app/src/lib/extensions/host.ts
+++ b/web-app/src/lib/extensions/host.ts
@@ -458,12 +458,24 @@ export class ExtensionHost {
extensionId: string,
name: string,
input: unknown,
- options: { signal?: AbortSignal; maxOutputChars?: number } = {}
+ options: {
+ signal?: AbortSignal
+ maxOutputChars?: number
+ /** `ExtensionTool.generation` the caller approved; a rebound handler is refused. */
+ generation?: number
+ } = {}
): Promise<ToolCallOutcome> {
- const handler = own(own(this.contributions.getState().tools, extensionId), name)
- ?.handler
+ const tool = own(own(this.contributions.getState().tools, extensionId), name)
+ const handler = tool?.handler
if (!handler)
return { error: `Tool '${name}' of '${extensionId}' is not available` }
+ if (
+ options.generation !== undefined &&
+ tool.generation !== options.generation
+ )
+ return {
+ error: `Tool '${name}' of '${extensionId}' changed since it was offered`,
+ }
const cancellation = new CancellationTokenSource()
const cancel = () => cancellation.cancel()
if (options.signal?.aborted) cancel()
diff --git a/web-app/src/lib/extensions/tools.ts b/web-app/src/lib/extensions/tools.ts
index 623eca33f..7f84ffc55 100644
--- a/web-app/src/lib/extensions/tools.ts
+++ b/web-app/src/lib/extensions/tools.ts
@@ -14,6 +14,13 @@ export interface ExtensionTool {
name: string
description: string
inputSchema: JsonSchemaObject
+ /**
+ * Host-assigned identity of the handler binding behind this tool. It
+ * changes whenever the handler is replaced (reload, update, crash restart)
+ * even if the declaration is identical, so a fingerprint of this object
+ * tells approved code from replacement code.
+ */
+ generation: number
/**
* Groups the tool in the tool toggles and approval prompts. Namespaced so
* an extension cannot pose as an MCP server the user already trusts.
@@ -81,13 +88,14 @@ export function listExtensionTools(state: ContributionState): ExtensionTool[] {
const tools = state.tools[extensionId]
for (const name of Object.keys(tools).sort()) {
const tool = tools[name]
- if (!tool.handler) continue
+ if (!tool.handler || tool.generation === undefined) continue
result.push({
wireName: toolWireName(extensionId, name),
extensionId,
name,
description: tool.description,
inputSchema: tool.inputSchema,
+ generation: tool.generation,
server: extensionToolServer(extensionId),
})
}
diff --git a/web-app/src/routes/threads/$threadId.tsx b/web-app/src/routes/threads/$threadId.tsx
index 15d4bb575..0c363449f 100644
--- a/web-app/src/routes/threads/$threadId.tsx
+++ b/web-app/src/routes/threads/$threadId.tsx
@@ -1017,7 +1017,11 @@ function ThreadDetail() {
extensionTool.extensionId,
extensionTool.name,
toolCall.input,
- { signal: stopSignal, maxOutputChars }
+ {
+ signal: stopSignal,
+ maxOutputChars,
+ generation: extensionTool.generation,
+ }
)
} else if (mcpToolNames.has(toolName)) {
// Give the backend the budget scaled to the window; it narrows