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: file upload function and assistant migration

Louis0f27aab15f5e
diff --git a/extensions/assistant-extension/src/index.ts b/extensions/assistant-extension/src/index.ts
index 23cd71411..af3c7dacb 100644
--- a/extensions/assistant-extension/src/index.ts
+++ b/extensions/assistant-extension/src/index.ts
@@ -4,6 +4,9 @@ import { Assistant, AssistantExtension, fs, joinPath } from '@janhq/core'
* functionality for managing assistants.
*/
export default class JanAssistantExtension extends AssistantExtension {
+ private readonly CURRENT_MIGRATION_VERSION = 1
+ private readonly MIGRATION_FILE = 'file://assistants/.migration_version'
+
/**
* Called when the extension is loaded.
*/
@@ -11,12 +14,101 @@ export default class JanAssistantExtension extends AssistantExtension {
if (!(await fs.existsSync('file://assistants'))) {
await fs.mkdir('file://assistants')
}
+
+ // Run migrations if needed
+ await this.runMigrations()
+
const assistants = await this.getAssistants()
if (assistants.length === 0) {
await this.createAssistant(this.defaultAssistant)
}
}
+ /**
+ * Gets the current migration version from storage
+ */
+ private async getCurrentMigrationVersion(): Promise<number> {
+ try {
+ if (await fs.existsSync(this.MIGRATION_FILE)) {
+ const versionStr = await fs.readFileSync(this.MIGRATION_FILE)
+ const version = parseInt(versionStr.trim(), 10)
+ return isNaN(version) ? 0 : version
+ }
+ } catch (error) {
+ console.error('Failed to read migration version:', error)
+ }
+ return 0
+ }
+
+ /**
+ * Saves the migration version to storage
+ */
+ private async saveMigrationVersion(version: number): Promise<void> {
+ try {
+ await fs.writeFileSync(this.MIGRATION_FILE, version.toString())
+ } catch (error) {
+ console.error('Failed to save migration version:', error)
+ }
+ }
+
+ /**
+ * Runs all pending migrations
+ */
+ private async runMigrations(): Promise<void> {
+ const currentVersion = await this.getCurrentMigrationVersion()
+
+ if (currentVersion < 1) {
+ console.log('Running migration v1: Update assistant instructions')
+ await this.migrateAssistantInstructions()
+ await this.saveMigrationVersion(1)
+ }
+
+ // Future migrations can be added here
+ // if (currentVersion < 2) {
+ // await this.migrationV2()
+ // await this.saveMigrationVersion(2)
+ // }
+
+ console.log(`Migrations complete. Current version: ${this.CURRENT_MIGRATION_VERSION}`)
+ }
+
+ /**
+ * Migration v1: Update assistant instructions from old format to new format
+ */
+ private async migrateAssistantInstructions(): Promise<void> {
+ const OLD_INSTRUCTION = 'You are a helpful AI assistant.'
+ const NEW_INSTRUCTION = 'You are Jan, a helpful AI assistant.' // TODO: Update with new instruction
+
+ if (!(await fs.existsSync('file://assistants'))) {
+ return
+ }
+
+ const assistants = await this.getAssistants()
+
+ for (const assistant of assistants) {
+ // Check if this assistant has the old instruction format
+ if (assistant.instructions?.startsWith(OLD_INSTRUCTION)) {
+ // Replace old instruction with new one, preserving the rest of the content
+ const restOfInstructions = assistant.instructions.substring(OLD_INSTRUCTION.length)
+ assistant.instructions = NEW_INSTRUCTION + restOfInstructions
+
+ // Save the updated assistant
+ const assistantPath = await joinPath([
+ 'file://assistants',
+ assistant.id,
+ 'assistant.json',
+ ])
+
+ try {
+ await fs.writeFileSync(assistantPath, JSON.stringify(assistant, null, 2))
+ console.log(`Migrated instructions for assistant: ${assistant.id}`)
+ } catch (error) {
+ console.error(`Failed to migrate assistant ${assistant.id}:`, error)
+ }
+ }
+ }
+ }
+
/**
* Called when the extension is unloaded.
*/
@@ -82,7 +174,7 @@ export default class JanAssistantExtension extends AssistantExtension {
'Jan is a helpful desktop assistant that can reason through complex tasks and use tools to complete them on the user’s behalf.',
model: '*',
instructions:
- 'You are a helpful AI assistant. Your primary goal is to assist users with their questions and tasks to the best of your abilities.\n\nWhen responding:\n- Answer directly from your knowledge when you can\n- Be concise, clear, and helpful\n- Admit when you’re unsure rather than making things up\n\nIf tools are available to you:\n- Only use tools when they add real value to your response\n- Use tools when the user explicitly asks (e.g., "search for...", "calculate...", "run this code")\n- Use tools for information you don’t know or that needs verification\n- Never use tools just because they’re available\n\nWhen using tools:\n- Use one tool at a time and wait for results\n- Use actual values as arguments, not variable names\n- Learn from each result before deciding next steps\n- Avoid repeating the same tool call with identical parameters\n- You must use browser screenshot to double check before you announce you finished or completed the task. If you got stuck, go to google.com\n\nRemember: Most questions can be answered without tools. Think first whether you need them.\n\nCurrent date: {{current_date}}',
+ 'You are Jan, a helpful AI assistant. Your primary goal is to assist users with their questions and tasks to the best of your abilities.\n\nWhen responding:\n- Answer directly from your knowledge when you can\n- Be concise, clear, and helpful\n- Admit when you’re unsure rather than making things up\n\nIf tools are available to you:\n- Only use tools when they add real value to your response\n- Use tools when the user explicitly asks (e.g., "search for...", "calculate...", "run this code")\n- Use tools for information you don’t know or that needs verification\n- Never use tools just because they’re available\n\nWhen using tools:\n- Use one tool at a time and wait for results\n- Use actual values as arguments, not variable names\n- Learn from each result before deciding next steps\n- Avoid repeating the same tool call with identical parameters\n- You must use browser screenshot to double check before you announce you finished or completed the task. If you got stuck, go to google.com\n\nRemember: Most questions can be answered without tools. Think first whether you need them.\n\nCurrent date: {{current_date}}',
tools: [
{
type: 'retrieval',
diff --git a/web-app/src/containers/MessageItem.tsx b/web-app/src/containers/MessageItem.tsx
index aecb03cde..274348010 100644
--- a/web-app/src/containers/MessageItem.tsx
+++ b/web-app/src/containers/MessageItem.tsx
@@ -298,7 +298,7 @@ export const MessageItem = memo(
}
return (
- <div className="w-full">
+ <div className="w-full mb-4">
{/* Show assistant header for assistant messages */}
{message.role === 'assistant' && showAssistant && (
<div className="flex items-center gap-2 mb-3 text-main-view-fg/60">
diff --git a/web-app/src/hooks/useAssistant.ts b/web-app/src/hooks/useAssistant.ts
index 0f4a272de..19192e9e5 100644
--- a/web-app/src/hooks/useAssistant.ts
+++ b/web-app/src/hooks/useAssistant.ts
@@ -45,7 +45,7 @@ export const defaultAssistant: Assistant = {
description:
'Jan is a helpful desktop assistant that can reason through complex tasks and use tools to complete them on the user’s behalf.',
instructions:
- 'You are a helpful AI assistant. Your primary goal is to assist users with their questions and tasks to the best of your abilities.\n\nWhen responding:\n- Answer directly from your knowledge when you can\n- Be concise, clear, and helpful\n- Admit when you’re unsure rather than making things up\n\nIf tools are available to you:\n- Only use tools when they add real value to your response\n- Use tools when the user explicitly asks (e.g., "search for...", "calculate...", "run this code")\n- Use tools for information you don’t know or that needs verification\n- Never use tools just because they’re available\n\nWhen using tools:\n- Use one tool at a time and wait for results\n- Use actual values as arguments, not variable names\n- Learn from each result before deciding next steps\n- Avoid repeating the same tool call with identical parameters\n- You must use browser screenshot to double check before you announce you finished or completed the task. If you got stuck, go to google.com\n\nRemember: Most questions can be answered without tools. Think first whether you need them.\n\nCurrent date: {{current_date}}',
+ 'You are Jan, a helpful AI assistant. Your primary goal is to assist users with their questions and tasks to the best of your abilities.\n\nWhen responding:\n- Answer directly from your knowledge when you can\n- Be concise, clear, and helpful\n- Admit when you’re unsure rather than making things up\n\nIf tools are available to you:\n- Only use tools when they add real value to your response\n- Use tools when the user explicitly asks (e.g., "search for...", "calculate...", "run this code")\n- Use tools for information you don’t know or that needs verification\n- Never use tools just because they’re available\n\nWhen using tools:\n- Use one tool at a time and wait for results\n- Use actual values as arguments, not variable names\n- Learn from each result before deciding next steps\n- Avoid repeating the same tool call with identical parameters\n- You must use browser screenshot to double check before you announce you finished or completed the task. If you got stuck, go to google.com\n\nRemember: Most questions can be answered without tools. Think first whether you need them.\n\nCurrent date: {{current_date}}',
}
// Platform-aware initial state
diff --git a/web-app/src/lib/custom-chat-transport.ts b/web-app/src/lib/custom-chat-transport.ts
index 95db7f3c3..4624df6f7 100644
--- a/web-app/src/lib/custom-chat-transport.ts
+++ b/web-app/src/lib/custom-chat-transport.ts
@@ -231,7 +231,10 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
.startModel(updatedProvider ?? this.provider, this.modelId)
// Create the model using the factory
- this.model = await ModelFactory.createModel(this.modelId, updatedProvider ?? this.provider)
+ this.model = await ModelFactory.createModel(
+ this.modelId,
+ updatedProvider ?? this.provider
+ )
} catch (error) {
console.error('Failed to start model:', error)
throw new Error(
@@ -243,7 +246,9 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
}
// Convert UI messages to model messages
- const modelMessages = convertToModelMessages(options.messages)
+ const modelMessages = convertToModelMessages(
+ this.mapUserInlineAttachments(options.messages)
+ )
// Include tools only if we have tools loaded AND model supports them
const hasTools = Object.keys(this.tools).length > 0
@@ -264,7 +269,6 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
return result.toUIMessageStream({
messageMetadata: ({ part }) => {
-
// Track stream start time on first text delta
if (part.type === 'text-delta') {
if (!streamStartTime) {
@@ -374,4 +378,51 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
// Since this project has no backend, we can't reconnect to a stream, so this is intentionally no-op.
return null
}
+
+ /**
+ * Map user messages to include inline attachments in the message parts
+ * @param messages
+ * @returns
+ */
+ mapUserInlineAttachments(messages: UIMessage[]): UIMessage[] {
+ return messages.map((message) => {
+ if (message.role === 'user') {
+ const inlineFileContents = Array.isArray(
+ (message.metadata as any)?.inline_file_contents
+ )
+ ? (
+ (message.metadata as any)?.inline_file_contents as Array<{
+ name?: string
+ content?: string
+ }>
+ ).filter((f) => f?.content)
+ : []
+ // Tool messages have content as array of ToolResultPart
+ if (inlineFileContents.length > 0) {
+ const buildInlineText = (base: string) => {
+ if (!inlineFileContents.length) return base
+ const formatted = inlineFileContents
+ .map((f) => `File: ${f.name || 'attachment'}\n${f.content ?? ''}`)
+ .join('\n\n')
+ return base ? `${base}\n\n${formatted}` : formatted
+ }
+
+ if (message.parts.length > 0) {
+ const parts = message.parts.map((part) => {
+ if (part.type === 'text') {
+ return {
+ type: 'text' as const,
+ text: buildInlineText(part.text ?? ''),
+ }
+ }
+ return part
+ })
+ message.parts = parts
+ }
+ }
+ }
+
+ return message
+ })
+ }
}
diff --git a/web-app/src/routes/threads/$threadId.tsx b/web-app/src/routes/threads/$threadId.tsx
index 978c73f29..1baa9fd2a 100644
--- a/web-app/src/routes/threads/$threadId.tsx
+++ b/web-app/src/routes/threads/$threadId.tsx
@@ -114,7 +114,9 @@ function ThreadDetail() {
// Store model metadata in appState for the chat transport
const setLanguageModel = useAppState((state) => state.setLanguageModel)
const languageModelId = useAppState((state) => state.languageModelId)
- const languageModelProvider = useAppState((state) => state.languageModelProvider)
+ const languageModelProvider = useAppState(
+ (state) => state.languageModelProvider
+ )
useEffect(() => {
// Wait for providers to be loaded before attempting to set model metadata
@@ -169,7 +171,10 @@ function ThreadDetail() {
if (contentParts.length > 0) {
// Extract metadata from the message (including usage and tokenSpeed)
- const messageMetadata = (message.metadata || {}) as Record<string, unknown>
+ const messageMetadata = (message.metadata || {}) as Record<
+ string,
+ unknown
+ >
// Create assistant message with content parts (including tool calls) and metadata
const assistantMessage: ThreadMessage = {
@@ -299,7 +304,11 @@ function ThreadDetail() {
const modelSupportsTools =
selectedModel?.capabilities?.includes('tools') ?? false
- updateRagToolsAvailability(hasDocuments, modelSupportsTools, ragFeatureAvailable)
+ updateRagToolsAvailability(
+ hasDocuments,
+ modelSupportsTools,
+ ragFeatureAvailable
+ )
}, [
thread?.metadata?.hasDocuments,
selectedModel?.capabilities,
@@ -465,11 +474,16 @@ function ThreadDetail() {
)
addMessage(userMessage)
- // Build message parts for AI SDK (only images are sent as file parts)
+ // Build parts for AI SDK (only images are sent as file parts)
const parts: Array<
| { type: 'text'; text: string }
| { type: 'file'; mediaType: string; url: string }
- > = [{ type: 'text', text: message.text }]
+ > = [
+ {
+ type: 'text',
+ text: userMessage.content[0].text?.value ?? message.text,
+ },
+ ]
if (message.files) {
message.files.forEach((file) => {
@@ -481,8 +495,11 @@ function ThreadDetail() {
})
}
- // Send the message
- sendMessage({ parts, id: messageId })
+ sendMessage({
+ parts,
+ id: messageId,
+ metadata: userMessage.metadata,
+ })
// Clear attachments after sending
clearAttachmentsForThread(attachmentsKey)
@@ -574,7 +591,7 @@ function ThreadDetail() {
const parts: Array<
| { type: 'text'; text: string }
| { type: 'file'; mediaType: string; url: string }
- > = [{ type: 'text', text }]
+ > = [{ type: 'text', text: userMessage.content[0].text?.value ?? text }]
if (files) {
files.forEach((file) => {
@@ -586,7 +603,11 @@ function ThreadDetail() {
})
}
- sendMessage({ parts, id: messageId })
+ sendMessage({
+ parts,
+ id: messageId,
+ metadata: userMessage.metadata,
+ })
// Clear attachments after sending
clearAttachmentsForThread(attachmentsKey)
@@ -710,9 +731,7 @@ function ThreadDetail() {
/>
)
})}
- {status === CHAT_STATUS.SUBMITTED && (
- <PromptProgress />
- )}
+ {status === CHAT_STATUS.SUBMITTED && <PromptProgress />}
</ConversationContent>
<ConversationScrollButton />
</Conversation>