This commit is contained in:
Timothy Jaeryang Baek committed 2026-11-24 22:11:32 +04:00
1 parent 26f85aa220
commit 1fbb42be97
19 files changed
+589 -91

No files matched your search

+18 -5
View File
@@ -1118,7 +1118,13 @@ async def chat_completion(
tasks = form_data.pop('background_tasks', None)
normalize_machine_id(form_data)
from open_webui.utils.machines import get_folder_machine_defaults, initialize_machine_directory
from open_webui.utils.machines import (
can_use_machine,
get_folder_directory,
get_folder_machine_defaults,
initialize_machine_directory,
require_chat_folder_machine,
)
folder_defaults = {}
requested_directory = form_data.pop('machine_cwd', None)
@@ -1127,10 +1133,17 @@ async def chat_completion(
requested_directory = legacy_directory
if 'parent_id' in form_data and form_data['parent_id'] is None and not form_data.get('chat_id'):
folder_defaults = await get_folder_machine_defaults(user, form_data.get('folder_id'))
if 'machine_id' not in form_data and folder_defaults.get('machine_id'):
form_data['machine_id'] = folder_defaults['machine_id']
if requested_directory is None and form_data.get('machine_id') == folder_defaults.get('machine_id'):
requested_directory = folder_defaults.get('working_directory')
if not form_data.get('machine_id') and folder_defaults.get('machine_id'):
# People without access to the folder's machine still chat there, without it.
if await can_use_machine(user, folder_defaults['machine_id'], request):
form_data['machine_id'] = folder_defaults['machine_id']
await require_chat_folder_machine(form_data.get('folder_id'), form_data.get('machine_id'))
if form_data.get('machine_id') and form_data['machine_id'] == folder_defaults.get('machine_id'):
requested_directory = (
await get_folder_directory(form_data.get('folder_id'))
or requested_directory
or folder_defaults.get('working_directory')
)
else:
requested_directory = None
@@ -0,0 +1,25 @@
"""Add private per-user folder working views."""
import sqlalchemy as sa
from alembic import op
revision = 'd2f86c0b41ae'
down_revision = 'b7d4f1a2c960'
branch_labels = None
depends_on = None
def upgrade():
op.create_table(
'folder_view_state',
sa.Column('user_id', sa.Text(), primary_key=True),
sa.Column('folder_id', sa.Text(), primary_key=True),
sa.Column('state', sa.JSON(), nullable=False),
sa.Column('revision', sa.BigInteger(), nullable=False),
sa.Column('updated_at', sa.BigInteger(), nullable=False),
)
op.create_index('ix_folder_view_state_folder_id', 'folder_view_state', ['folder_id'])
def downgrade():
op.drop_table('folder_view_state')
+15
View File
@@ -3,10 +3,12 @@
import time
from typing import Annotated, Literal
from fastapi import HTTPException, Request
from open_webui.internal.db import Base
from pydantic import BaseModel, ConfigDict, Field, model_validator
from sqlalchemy import JSON, BigInteger, Column, Text, update
from sqlalchemy.exc import IntegrityError
from starlette.requests import ClientDisconnect
class ViewModel(BaseModel):
@@ -127,6 +129,19 @@ class ChatViewData(ViewModel):
return data
async def read_bounded_view(request: Request) -> bytes:
"""Bound the body before JSON/schema parsing, including chunked requests."""
body = bytearray()
try:
async for chunk in request.stream():
body.extend(chunk)
if len(body) > 1024 * 1024:
raise HTTPException(status_code=413, detail='View is too large')
except ClientDisconnect:
raise HTTPException(status_code=499)
return bytes(body)
class ChatViewStateForm(ViewModel):
state: ChatViewData
+58
View File
@@ -0,0 +1,58 @@
"""Private working views, independently owned by each user of a folder."""
import time
from open_webui.internal.db import Base
from open_webui.models.chat_views import ChatViewData, ViewModel
from sqlalchemy import JSON, BigInteger, Column, Text, delete, update
from sqlalchemy.exc import IntegrityError
class FolderViewStateForm(ViewModel):
state: ChatViewData
revision: int
class FolderViewState(Base):
__tablename__ = 'folder_view_state'
user_id = Column(Text, primary_key=True)
folder_id = Column(Text, primary_key=True, index=True)
state = Column(JSON, nullable=False)
revision = Column(BigInteger, nullable=False)
updated_at = Column(BigInteger, nullable=False)
class FolderViewStatesTable:
async def get(self, user_id, folder_id, db):
row = await db.get(FolderViewState, (user_id, folder_id), populate_existing=True)
return {'state': row.state, 'revision': row.revision} if row else {'state': None, 'revision': 0}
async def save(self, user_id, folder_id, state, revision, db):
"""Save over the given revision; None when another window saved first."""
values = {'state': state, 'revision': revision + 1, 'updated_at': int(time.time())}
if revision == 0:
try:
db.add(FolderViewState(user_id=user_id, folder_id=folder_id, **values))
await db.commit()
return {'revision': 1}
except IntegrityError:
await db.rollback()
return None
result = await db.execute(
update(FolderViewState)
.where(
FolderViewState.user_id == user_id,
FolderViewState.folder_id == folder_id,
FolderViewState.revision == revision,
)
.values(**values)
)
await db.commit()
return {'revision': revision + 1} if result.rowcount else None
async def delete_by_folder_ids(self, folder_ids, db):
await db.execute(delete(FolderViewState).where(FolderViewState.folder_id.in_(folder_ids)))
await db.commit()
FolderViewStates = FolderViewStatesTable()
+21 -13
View File
@@ -7,7 +7,12 @@ from uuid import uuid4
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Query, Request, Response, status
from fastapi.responses import StreamingResponse
from fastapi.security import HTTPAuthorizationCredentials
from open_webui.utils.machines import normalize_machine_id
from open_webui.utils.machines import (
get_folder_directory,
machine_id_of,
normalize_machine_id,
require_chat_folder_machine,
)
from open_webui.config import (
CONTEXT_COMPACTION_RETENTION_PERCENTAGE,
CONTEXT_COMPACTION_TOKEN_THRESHOLD,
@@ -19,7 +24,7 @@ from open_webui.events import EVENTS, publish_event
from open_webui.internal.db import get_async_session
from open_webui.models.access_grants import AccessGrants
from open_webui.models.chat_messages import ChatMessages
from open_webui.models.chat_views import ChatViewStateForm, ChatViewStates
from open_webui.models.chat_views import ChatViewStateForm, ChatViewStates, read_bounded_view
from open_webui.models.chats import (
AggregateChatStats,
ChatBody,
@@ -54,7 +59,6 @@ from open_webui.utils.tool_permissions import DEFAULT_TOOL_PERMISSIONS_AUTO_PROM
from open_webui.utils.tool_search import DEFAULT_TOOL_SEARCH_DECISIONS_PROMPT, validate_decisions_config
from pydantic import BaseModel, Field, ValidationError, field_validator, model_validator
from sqlalchemy.ext.asyncio import AsyncSession
from starlette.requests import ClientDisconnect
log = logging.getLogger(__name__)
@@ -889,6 +893,11 @@ async def create_new_chat(
status_code=status.HTTP_404_NOT_FOUND,
detail=ERROR_MESSAGES.NOT_FOUND,
)
normalize_machine_id(form_data.chat)
await require_chat_folder_machine(form_data.folder_id, machine_id_of(form_data.chat))
directory = await get_folder_directory(form_data.folder_id)
if directory and machine_id_of(form_data.chat):
form_data.chat['working_directory'] = directory
try:
set_message_authors(form_data.chat, user)
@@ -1440,17 +1449,9 @@ async def get_chat_view(
async def bounded_chat_view(request: Request):
# Bound the body before JSON/schema parsing, including chunked requests.
body = bytearray()
body = await read_bounded_view(request)
try:
async for chunk in request.stream():
body.extend(chunk)
if len(body) > 1024 * 1024:
raise HTTPException(status_code=413, detail='Chat view is too large')
except ClientDisconnect:
raise HTTPException(status_code=499)
try:
return ChatViewStateForm.model_validate_json(bytes(body))
return ChatViewStateForm.model_validate_json(body)
except ValueError:
raise HTTPException(status_code=422, detail='Invalid chat view')
@@ -1532,6 +1533,13 @@ async def update_chat_by_id(
)
form_data.chat['title'] = title.strip()
if chat:
if machine_id_of(form_data.chat) != machine_id_of(chat.chat):
await require_chat_folder_machine(chat.folder_id, machine_id_of(form_data.chat))
directory = form_data.chat.get('working_directory')
if directory and directory != (chat.chat or {}).get('working_directory'):
folder_directory = await get_folder_directory(chat.folder_id)
if folder_directory and directory != folder_directory:
raise HTTPException(status.HTTP_409_CONFLICT, 'Chats in this folder start in its directory')
set_message_authors(form_data.chat, user)
touch = 'history' in form_data.chat or 'messages' in form_data.chat
chat = await Chats.update_chat_by_id(id, form_data.chat, db=db, touch=touch)
+38 -1
View File
@@ -7,7 +7,7 @@ from pathlib import Path
from typing import Literal, Optional
from fastapi import APIRouter, Depends, File, HTTPException, Query, Request, UploadFile, status
from fastapi.responses import FileResponse, StreamingResponse
from fastapi.responses import FileResponse, JSONResponse, StreamingResponse
from open_webui.config import UPLOAD_DIR
from open_webui.constants import ERROR_MESSAGES
from open_webui.events import EVENTS, publish_event
@@ -17,6 +17,8 @@ from open_webui.models.automations import AutomationResponse, AutomationRuns, Au
from open_webui.models.chat_messages import ChatMessages
from open_webui.models.chats import FOLDER_PRIORITIES, NO_FOLDER_PRIORITY, Chats
from open_webui.models.config import Config
from open_webui.models.chat_views import read_bounded_view
from open_webui.models.folder_views import FolderViewStateForm, FolderViewStates
from open_webui.models.folders import (
FolderForm,
FolderModel,
@@ -749,6 +751,40 @@ async def check_folder_read_access(request: Request, id: str, user, db: AsyncSes
return folder
# A view is private to its authenticated viewer, even for shared folders.
@router.get('/{id}/view')
async def get_folder_view(
request: Request, id: str, user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session)
):
await check_folder_read_access(request, id, user, db)
return await FolderViewStates.get(user.id, id, db)
async def bounded_folder_view(request: Request):
body = await read_bounded_view(request)
try:
return FolderViewStateForm.model_validate_json(body)
except ValueError:
raise HTTPException(status_code=422, detail='Invalid folder view')
@router.post('/{id}/view')
async def update_folder_view(
request: Request,
id: str,
user=Depends(get_verified_user),
form: FolderViewStateForm = Depends(bounded_folder_view),
db: AsyncSession = Depends(get_async_session),
):
await check_folder_read_access(request, id, user, db)
saved = await FolderViewStates.save(
user.id, id, form.state.model_dump(exclude_unset=True), form.revision, db
)
if not saved:
return JSONResponse(await FolderViewStates.get(user.id, id, db), status_code=409)
return saved
@router.get('/{id}/automations')
async def get_folder_automations(
request: Request, id: str, user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session)
@@ -981,6 +1017,7 @@ async def delete_folder_by_id(
if folder:
try:
folder_ids = await Folders.delete_folder_by_id_and_user_id(folder.id, folder_owner_id, db=db)
await FolderViewStates.delete_by_folder_ids(folder_ids, db)
for folder_id in folder_ids:
if delete_contents:
+11 -1
View File
@@ -51,7 +51,13 @@ from open_webui.utils.recurrence import (
from open_webui.utils.prompt_variables import fill_variables
from open_webui.utils.task import prompt_template
from open_webui.utils.agents.discovery import get_models as get_agent_models
from open_webui.utils.machines import initialize_machine_directory, resolve_machine_connection
from open_webui.utils.machines import (
can_use_machine,
get_folder_machine,
get_folder_machine_mismatch,
initialize_machine_directory,
resolve_machine_connection,
)
from starlette.datastructures import Headers
log = logging.getLogger(__name__)
@@ -460,6 +466,10 @@ async def _execute_automation(app, automation: AutomationModel, variables: Optio
parent_id = None
defaults = await _resolve_model_defaults(app, model_id)
machine = automation_machine_of(automation.data)
if folder_id and await get_folder_machine_mismatch(folder_id, machine.get('server_id')):
folder_machine = await get_folder_machine(folder_id)
if machine.get('server_id') or await can_use_machine(user, folder_machine['machine_id']):
machine = {'server_id': folder_machine['machine_id'], 'cwd': folder_machine['working_directory']}
machine_id = machine.get('server_id') or defaults.get('machine_id')
# An ongoing chat gets this run at its end; the first run, or a run after the chat was deleted, starts it.
+14 -1
View File
@@ -3,12 +3,13 @@ from uuid import UUID
TEMPORARY_CHAT_ID_PREFIX = 'temporary:'
LEGACY_TEMPORARY_CHAT_ID_PREFIX = 'local:' # Legacy temporary chat prefix.
CHANNEL_CHAT_ID_PREFIX = 'channel:'
FOLDER_SESSION_ID_PREFIX = 'folder:' # A person's panels in a folder; not a chat.
TEMPORARY_CHAT_ID_PREFIXES = (
TEMPORARY_CHAT_ID_PREFIX,
LEGACY_TEMPORARY_CHAT_ID_PREFIX,
)
NON_SAVED_CHAT_ID_PREFIXES = (*TEMPORARY_CHAT_ID_PREFIXES, CHANNEL_CHAT_ID_PREFIX)
NON_SAVED_CHAT_ID_PREFIXES = (*TEMPORARY_CHAT_ID_PREFIXES, CHANNEL_CHAT_ID_PREFIX, FOLDER_SESSION_ID_PREFIX)
def is_saved_chat_id(chat_id: str | None) -> bool:
@@ -34,3 +35,15 @@ def get_temporary_chat_session_id(chat_id: str) -> str | None:
return None
return session_id
return None
def folder_session_id(folder_id: str, user_id: str) -> str:
return f'{FOLDER_SESSION_ID_PREFIX}{folder_id}:{user_id}'
def get_folder_id_of_session(session_id: str | None, user_id: str) -> str | None:
"""The folder of a person's folder session id; None when it is not theirs."""
if not session_id or not session_id.startswith(FOLDER_SESSION_ID_PREFIX):
return None
folder_id, _, owner_id = session_id.removeprefix(FOLDER_SESSION_ID_PREFIX).rpartition(':')
return folder_id if folder_id and owner_id == user_id else None
+135 -20
View File
@@ -14,7 +14,12 @@ from fastapi import HTTPException
from open_webui.env import AIOHTTP_CLIENT_SESSION_SSL, AIOHTTP_CLIENT_TIMEOUT_MACHINE, ENABLE_TOOL_SERVERS
from open_webui.utils.headers import bearer_auth_header
from open_webui.utils.chat_id import is_saved_chat_id
from open_webui.utils.chat_id import (
FOLDER_SESSION_ID_PREFIX,
folder_session_id,
get_folder_id_of_session,
is_saved_chat_id,
)
from open_webui.utils.skill_files import (
SKILL_CONTENT_MAX_CHARS,
bounded_skill_manifest,
@@ -339,10 +344,17 @@ async def require_model_access(user, model_id, machine_id, request=None):
def machine_headers(connection):
"""Only consumes context produced by find_machine_connection, never browser headers."""
headers = {}
if connection.get('workspace'):
headers['X-Workspace-Id'] = connection['workspace']['id']
if connection['workspace'].get('directory'):
headers['X-Workspace-Directory'] = quote(connection['workspace']['directory'])
if not connection.get('template_id'):
return {'X-User-Id': connection['instance_user_id']} if connection.get('instance_user_id') else {}
if connection.get('instance_user_id'):
headers['X-User-Id'] = connection['instance_user_id']
return headers
context = connection['machine_context']
headers = {
headers |= {
'X-Terminal-Template-Id': connection['template_id'],
'X-User-Id': context['user_id'],
}
@@ -382,7 +394,11 @@ async def find_machine_connection(user, machine_id, metadata=None, request=None)
shared_session = None
instance_user = user
chat_id = metadata.get('chat_id')
if chat_id and is_saved_chat_id(chat_id):
folder_id = None
if isinstance(chat_id, str) and chat_id.startswith(FOLDER_SESSION_ID_PREFIX):
folder_id = get_folder_id_of_session(chat_id, user.id)
await require_folder_panels(user, folder_id)
elif chat_id and is_saved_chat_id(chat_id):
chat = await Chats.get_chat_metadata_by_id(chat_id)
if chat is None or not await Chats.has_chat_access(chat_id, user, permission='write', chat=chat):
if chat is None or not await has_machine_write_access(user, machine_id):
@@ -395,6 +411,12 @@ async def find_machine_connection(user, machine_id, metadata=None, request=None)
return await find_machine_connection(user, machine_id, metadata, request=request)
from open_webui.utils.agents.session import get_session, model_id
folder_id = chat.folder_id
if folder_id and await get_folder_machine_mismatch(folder_id, machine_id):
# A chat that was on another machine before keeps it.
full_chat = await Chats.get_chat_by_id(chat_id)
if full_chat is None or machine_id_of(full_chat.chat) != machine_id:
raise HTTPException(409, 'Chats in this folder run on its machine')
if not chat.current_message_id:
# Only the full chat knows where the history ends.
chat = await Chats.get_chat_by_id(chat_id)
@@ -410,7 +432,19 @@ async def find_machine_connection(user, machine_id, metadata=None, request=None)
if instance_user is None:
raise HTTPException(403, 'Agent machine owner is unavailable')
workspace = None
if folder_id:
folder_machine = await get_folder_machine(folder_id)
workspace = {
'id': folder_session_id(folder_id, user.id),
'directory': folder_machine['working_directory']
if folder_machine and folder_machine['machine_id'] == machine_id
else None,
}
def authorized_connection(connection):
if workspace:
connection = {**connection, 'workspace': workspace}
if shared_session:
connection = {**connection, 'instance_user_id': instance_user.id}
return connection
@@ -586,11 +620,71 @@ async def get_folder_machine_defaults(user, folder_id):
folder = await Folders.get_folder_by_id(folder_id)
if not folder or not await has_folder_access(user.id, folder, 'write', None):
raise HTTPException(403, 'Folder is unavailable')
data = folder.data or {}
return {
'machine_id': machine_id_of(data),
'working_directory': data.get('working_directory'),
}
return await get_folder_machine(folder_id) or {}
async def get_folder_machine(folder_id):
"""The machine a folder is on, and the directory there."""
from open_webui.models.folders import Folders
folder = await Folders.get_folder_by_id(folder_id)
data = (folder.data or {}) if folder else {}
if not machine_id_of(data):
return None
return {'machine_id': machine_id_of(data), 'working_directory': data.get('working_directory')}
async def get_folder_machine_mismatch(folder_id, machine_id):
"""The folder's machine id when it is a different one that everything in the folder has to use."""
folder_machine = await get_folder_machine(folder_id)
if not folder_machine or folder_machine['machine_id'] == machine_id:
return None
if folder_machine['machine_id'].startswith('template:'):
# A machine per chat or model is not one place, so the folder only suggests it.
from open_webui.models.users import Users
from open_webui.models.folders import Folders
folder = await Folders.get_folder_by_id(folder_id)
owner = await Users.get_user_by_id(folder.user_id)
try:
_, template = await template_connection(owner, folder_machine['machine_id'])
except HTTPException:
return None
if (template.get('data') or {}).get('scope') in ('chat', 'model'):
return None
return folder_machine['machine_id']
async def get_folder_directory(folder_id):
"""The directory everything in the folder starts in, when its machine is fixed and it has one."""
if not folder_id or not await get_folder_machine_mismatch(folder_id, None):
return None
return (await get_folder_machine(folder_id))['working_directory']
async def can_use_machine(user, machine_id, request=None):
try:
return await find_machine_connection(user, machine_id, request=request) is not None
except HTTPException:
return False
async def require_chat_folder_machine(folder_id, machine_id):
if folder_id and machine_id and await get_folder_machine_mismatch(folder_id, machine_id):
raise HTTPException(409, 'Chats in this folder run on its machine')
async def require_folder_panels(user, folder_id):
"""Check that a person may have panels in a folder; machine access is checked apart.
Shells left on the folder's earlier machine stay reachable, so its current one is not required.
"""
from open_webui.models.folders import Folders
from open_webui.utils.access_control.folders import has_folder_access
folder = await Folders.get_folder_by_id(folder_id) if folder_id else None
if not folder or (user.role != 'admin' and not await has_folder_access(user.id, folder, 'read', None)):
raise HTTPException(403, 'Folder access denied')
async def initialize_machine_directory(request, user, metadata, machine_id, path):
@@ -727,24 +821,45 @@ async def get_machine_file(request, user, metadata: dict, path: str, *, max_byte
return bytes(data)
async def get_chat_folder_directory(metadata: dict) -> str | None:
"""The directory of the chat's folder, when the chat runs on the folder's machine."""
from open_webui.models.chats import Chats
chat_id = metadata.get('chat_id')
chat = await Chats.get_chat_metadata_by_id(chat_id) if is_saved_chat_id(chat_id) else None
folder_machine = await get_folder_machine(chat.folder_id) if chat and chat.folder_id else None
if not folder_machine or folder_machine['machine_id'] != metadata.get('machine_id'):
return None
return folder_machine['working_directory']
async def get_machine_agents_md(request, user, metadata: dict, extra_params: dict | None = None) -> str | None:
"""Load the selected terminal user's home AGENTS.md afresh for this turn."""
"""Load the machine user's home AGENTS.md, then the folder's, afresh for this turn."""
try:
async with asyncio.timeout(5):
data = await get_machine_json(request, user, metadata, '/files/cwd', extra_params)
home = data.get('home') if isinstance(data, dict) else None
if not isinstance(home, str) or not (posixpath.isabs(home) or ntpath.isabs(home)):
return None
path = quote(posixpath.join(home, 'AGENTS.md'), safe='')
data = await get_machine_json(request, user, metadata, f'/files/read?path={path}', extra_params)
content = data.get('content') if isinstance(data, dict) else None
if not isinstance(content, str) or not content.strip():
return None
if len(content.encode('utf-8')) > MAX_AGENTS_MD_BYTES:
log.warning('Skipping terminal AGENTS.md: exceeds %s bytes', MAX_AGENTS_MD_BYTES)
return None
return f'# AGENTS.md\n\n{content}'
contents = []
candidates = [[home, ('AGENTS.md',)]]
directory = await get_chat_folder_directory(metadata)
if directory and directory != home:
candidates.append([directory, ('AGENTS.md', 'CLAUDE.md')])
for directory, names in candidates:
for name in names:
path = quote(posixpath.join(directory, name), safe='')
data = await get_machine_json(request, user, metadata, f'/files/read?path={path}', extra_params)
content = data.get('content') if isinstance(data, dict) else None
if not isinstance(content, str) or not content.strip():
continue
size = sum(len(text.encode('utf-8')) for text in [*contents, content])
if size > MAX_AGENTS_MD_BYTES:
log.warning('Skipping machine %s: exceeds %s bytes', name, MAX_AGENTS_MD_BYTES)
else:
contents.append(f'# {name}\n\n{content}')
break
return '\n\n'.join(contents) or None
except Exception as e:
log.debug('Failed to load terminal AGENTS.md (%s)', type(e).__name__)
return None
+23 -7
View File
@@ -1,19 +1,35 @@
import { WEBUI_API_BASE_URL } from '$lib/constants';
import type { ChatViewState } from '$lib/components/chat/Tabs/tabs';
import { isFolderSessionId } from '$lib/utils/chatId';
async function request(id: string, state?: ChatViewState) {
const response = await fetch(`${WEBUI_API_BASE_URL}/chats/${encodeURIComponent(id)}/view`, {
method: state ? 'POST' : 'GET',
export type SavedChatView = { state: ChatViewState | null; revision?: number };
export class ChatViewConflict extends Error {
constructor(public saved: SavedChatView) {
super('The layout was changed in another window');
}
}
async function request(id: string, body?: { state: ChatViewState; revision?: number }) {
const path = isFolderSessionId(id)
? `folders/${encodeURIComponent(id.split(':')[1])}`
: `chats/${encodeURIComponent(id)}`;
const response = await fetch(`${WEBUI_API_BASE_URL}/${path}/view`, {
method: body ? 'POST' : 'GET',
headers: {
Authorization: `Bearer ${localStorage.token ?? ''}`,
'Content-Type': 'application/json'
},
...(state ? { body: JSON.stringify({ state }) } : {})
...(body ? { body: JSON.stringify(body) } : {})
});
if (response.status === 409) throw new ChatViewConflict(await response.json());
if (!response.ok) throw new Error(`Chat view request failed (${response.status})`);
return response.json();
}
export const getChatView = (id: string): Promise<{ state: ChatViewState | null }> => request(id);
export const updateChatView = (id: string, state: ChatViewState): Promise<{ updated_at: number }> =>
request(id, state);
export const getChatView = (id: string): Promise<SavedChatView> => request(id);
export const updateChatView = (
id: string,
state: ChatViewState,
revision: number
): Promise<{ revision?: number }> =>
request(id, isFolderSessionId(id) ? { state, revision } : { state });
+46 -1
View File
@@ -63,6 +63,7 @@
import { refreshChatList, refreshFolderChatLists, setChatTitle } from '$lib/stores/chatList';
import { updateFolderById } from '$lib/apis/folders';
import {
loadFolderDetails,
getFolderAgentModels,
loadFolderAgentModels,
setFolderModelConnections,
@@ -568,6 +569,17 @@
$: canOpenArtifacts = !embedded || !!onOpenArtifacts;
let chat: any = null;
// A folder on a machine fixes it for its chats. One per chat or model is only suggested.
let machineFixed = false;
const checkFolderMachine = async (id: string | null) => {
machineFixed = false;
const folder = id ? await loadFolderDetails(localStorage.token, id).catch(() => null) : null;
const machineId = machineIdOf(folder?.data);
const scope = ($machines ?? []).find((machine) => machine.id === machineId)?.scope;
if (id === chatFolderId) machineFixed = !!machineId && scope !== 'chat' && scope !== 'model';
};
$: chatFolderId = (chat ? chat.folder_id : (draftFolderId ?? $selectedFolder?.id)) ?? null;
$: if ($machines) void checkFolderMachine(chatFolderId);
let tags = [];
// Non-owners may reply when the sharing mode allows it, but cannot save chat edits.
@@ -2850,6 +2862,33 @@
});
return () => bridge?.end();
});
/** A chat in a folder opens as one of the folder's tabs. */
const openInFolder = async (id: string, preserveTabs: boolean) => {
// Phones show one chat at a time, and links into a message need the chat itself.
if ($mobile || $page.url.search || $page.url.hash) return false;
const promise =
pendingChatRequest?.id === id
? pendingChatRequest.promise
: getChatById(localStorage.token, id);
pendingChatRequest = { id, promise };
const found = await promise.catch(() => null);
const folder = found?.folder_id
? await loadFolderDetails(localStorage.token, found.folder_id).catch(() => null)
: null;
if ($page.params.id !== id) return true;
if (!folder) return false;
pendingChatRequest = null;
const href = `/folders/${folder.id}`;
if ($selectedFolder?.id !== folder.id || $chatId || mainChatHref !== href) {
selectedFolder.set(folder);
await initNewChat({ preserveTabs, url: new URL(href, location.origin) });
await tick();
if ($page.params.id !== id) return true;
}
tabs?.openPageTab({ href: `/c/${id}`, label: found.title });
void tabs?.joinChatSessions(id);
return true;
};
// The layout keeps this component mounted; route changes update only the main pane.
let routeInitialized = false;
const followRoute = async () => {
@@ -2857,7 +2896,10 @@
routeInitialized = true;
await tick();
if ($page.route.id === '/(app)/c/[id]') {
chatIdProp = $page.params.id ?? '';
const id = $page.params.id ?? '';
if (await openInFolder(id, preserveTabs)) return;
if ($page.params.id !== id) return;
chatIdProp = id;
} else if ($page.params.folderId || $page.url.pathname === '/') {
selectedFolder.set($page.data.folder ?? null);
// On a first load the input is on screen before set-up, which resets it;
@@ -6456,6 +6498,7 @@
>
<MessageInput
{selectedMachineId}
machineSelectionEnabled={!machineFixed}
{machineSkills}
{messagesContainerId}
{inputId}
@@ -6589,6 +6632,7 @@
<div id={embedded ? messageInputDropzoneId : undefined} class="pb-2 z-10">
<MessageInput
{selectedMachineId}
machineSelectionEnabled={!machineFixed}
{machineSkills}
{messagesContainerId}
{inputId}
@@ -6675,6 +6719,7 @@
onNewFolderChat={() => tabs?.openFeatureTab('chat')}
bind:folderTabActions
{selectedMachineId}
machineSelectionEnabled={!machineFixed}
{machineSkills}
chatId={$chatId}
{onTemporaryChange}
+4 -2
View File
@@ -45,7 +45,7 @@
type MachineFileRoot,
type MachineCwd
} from '$lib/apis/machines';
import { isSavedChatId, isTemporaryChatId } from '$lib/utils/chatId';
import { isFolderSessionId, isSavedChatId, isTemporaryChatId } from '$lib/utils/chatId';
import { copyToClipboard } from '$lib/utils';
import { normalizeDocumentTargetPage } from '$lib/utils/documentPreview';
@@ -73,7 +73,9 @@
// savedPath is only a placeholder until a directory has loaded.
let savedPathLoaded = false;
$: folderDirectory =
!onSelectDirectory && !chatId && machineIdOf($selectedFolder?.data) === effectiveMachineId
!onSelectDirectory &&
(!chatId || isFolderSessionId(chatId)) &&
machineIdOf($selectedFolder?.data) === effectiveMachineId
? $selectedFolder.data.working_directory
: null;
let savedFileRoot: MachineFileRoot | null = null;
@@ -57,6 +57,7 @@
export let prompt = '';
export let files = [];
export let machineContext: MachineContext | null = null;
export let machineSelectionEnabled = true;
export let selectedMachineId: Pick<Writable<string | null>, 'subscribe' | 'set'>;
export let machineSkills: Writable<any[]>;
export let messageInput = null;
@@ -153,6 +154,7 @@
{#snippet composer(placeholder = '')}
<MessageInput
{selectedMachineId}
{machineSelectionEnabled}
{machineSkills}
{chatId}
{onTemporaryChange}
+92 -26
View File
@@ -34,7 +34,9 @@
embed,
temporaryChat,
machines,
selectedFolder,
showTabs,
activeChatTabId,
chatTabRequest,
showSidebar,
mobile,
@@ -101,7 +103,7 @@
import UntitledFile from './Tabs/UntitledFile.svelte';
import QuickOpen from './Tabs/QuickOpen.svelte';
import MachinePicker, { type MachineOption } from './Tabs/MachinePicker.svelte';
import { selectMachine } from '$lib/utils/machines';
import { machineIdOf, selectMachine } from '$lib/utils/machines';
import { terminalIconName } from '$lib/utils/terminal';
import VoiceNote from './Tabs/VoiceNote.svelte';
import Browser from './Tabs/Browser.svelte';
@@ -120,7 +122,13 @@
import ConfirmDialog from '../common/ConfirmDialog.svelte';
let stopTerminalChoice: ((stop: boolean) => void) | null = null;
import SplitPanel from '../icons/SplitPanel.svelte';
import { isSavedChatId, isTemporaryChatId } from '$lib/utils/chatId';
import {
folderSessionId,
isFolderSessionId,
isSavedChatId,
isTemporaryChatId
} from '$lib/utils/chatId';
import { getChatView } from '$lib/apis/chats/view';
const i18n = getContext<any>('i18n');
const appLayout = getContext<AppLayoutContext | undefined>('appLayout');
@@ -188,6 +196,8 @@
};
$: if (!mainTabFolder) isRenamingFolder = false;
$: mainTabTitle = mainTabFolder?.name ?? title;
/** What the open tabs belong to: the folder on screen, or the chat. */
$: panelChatId = mainTabFolder && $user ? folderSessionId(mainTabFolder.id, $user.id) : chatId;
export let getEmbeddedDraft: (
text?: string,
files?: any[]
@@ -338,7 +348,7 @@
panels: carried,
selectedMachineId: $selectedMachineId
};
setView({ status: 'carrying', entry, fromChatId: chatId });
setView({ status: 'carrying', entry, fromChatId: panelChatId });
tabs = carried;
hasExtraTabs = carried.tabs.some((tab) => tab.id !== mainChatTabId);
}
@@ -389,6 +399,7 @@
return done;
}
let lastFolderView: string | null = null;
async function restoreChatView(id: string | null) {
if (!$user?.id) return;
captureView();
@@ -410,8 +421,11 @@
let panels = setMainChatTab(entry.state.panels, true, mainTabTitle);
const mainGroup = panels.groups.find((group) => group.tabIds.includes(mainChatTabId));
const activeIds = [panels.activeId, mainGroup?.activeId];
// Opening a chat shows that chat, not the page or other chat it was left on.
if (
// Opening a chat shows that chat, not the page or other chat it was left on. A folder opens
// as it was left; opening it again from inside shows the folder itself.
if (isFolderSessionId(id)) {
if (id === lastFolderView && !pendingPageTab) panels = activateTab(panels, mainChatTabId);
} else if (
panels.tabs.some(
(tab) =>
activeIds.includes(tab.id) &&
@@ -430,7 +444,10 @@
commentAnchor = {};
sessionFailures = {};
sessionAttempts = {};
lastFolderView = isFolderSessionId(id) ? id : null;
setView({ status: 'ready', entry, chatId: id, error: entry.error });
if (isFolderSessionId(id) && !entry.persisted && machineIdOf($selectedFolder?.data))
openFiles($selectedMachineId, $selectedFolder?.data?.working_directory || undefined);
hasExtraTabs = tabs.tabs.some((tab) => tab.id !== mainChatTabId);
} catch (error) {
if (viewState === loading)
@@ -440,6 +457,8 @@
/** Keeps the layout in step with the chat: carry it over, attach it to the new chat id, or load. */
function followChat(current: ViewState, id: string | null) {
if (current.status === 'idle') return void restoreChatView(id);
// A folder keeps its own tabs; nothing is carried into it.
if (isFolderSessionId(id) && current.entry.chatId !== id) return void restoreChatView(id);
if (current.status === 'carrying') {
if (id === current.fromChatId) return;
if (id) void attachChatViewTo(id).catch(() => {});
@@ -511,7 +530,11 @@
tab.machineId,
$machines ?? [],
localStorage.token ?? '',
tab.target?.context ?? { chatId, modelId: modelId ?? null }
tab.target?.context ?? {
// A session that came along with a chat stays under that chat.
chatId: (tab.kind !== 'chat' && tab.chatId) || panelChatId,
modelId: modelId ?? null
}
);
if (target) tab.target = target;
return target;
@@ -520,7 +543,15 @@
const target = resolveTabConnection(tab);
if (target) {
delete sessionFailures[tab.id];
void createViewSession(chatView, tab.id, target);
void createViewSession(
chatView,
tab.id,
target,
getCurrentDirectory(target.selector) ||
(machineIdOf($selectedFolder?.data) === target.selector
? $selectedFolder?.data?.working_directory || undefined
: undefined)
);
}
};
@@ -560,7 +591,7 @@
if (!canVoiceNote || !$user) return;
voiceNoteDestination = {
target: selectedConnection,
chatId,
chatId: panelChatId,
directory: getCurrentDirectory(selectedConnection.selector)
};
};
@@ -691,7 +722,7 @@
const target =
tab.target ??
resolveMachineTarget(tab.machineId, $machines ?? [], localStorage.token, {
chatId: chatId,
chatId: panelChatId,
modelId: modelId ?? null
});
tab = { ...tab, target: target ?? undefined };
@@ -718,13 +749,16 @@
tabs.tabs.find(
(tab) =>
(tab.href && pageTabKey(new URL(tab.href, location.origin)) === pageTabKey(url)) ||
(tab.chatId && url.pathname === `/c/${tab.chatId}`) ||
(tab.kind === 'chat' && tab.chatId && url.pathname === `/c/${tab.chatId}`) ||
(url.pathname === '/workspace' && tab.href?.startsWith('/workspace/'))
);
// A folder's tabs are not there yet while the chat being left is still shown.
const isPanelViewReady = (id: string | null, entry: ChatViewEntry | null) =>
!isFolderSessionId(id) || entry?.chatId === id;
export const openPageTab = (request: { href: string; label: string; inSplit?: boolean }) => {
const url = new URL(request.href, location.origin);
if (url.origin !== location.origin || !pageTabKey(url)) return;
if (!viewReady) {
if (!viewReady || !isPanelViewReady(panelChatId, viewEntry)) {
pendingPageTab = request;
return;
}
@@ -743,6 +777,28 @@
void navigatePageTab(existing.id, request.href);
} else openPanel(createPageTab(request), request.inSplit);
};
/** Brings the live shells and browsers of a chat into its folder's tabs. */
export const joinChatSessions = async (id: string) => {
const saved = await getChatView(id).catch(() => null);
const entry = viewEntry;
if (!entry || !isFolderSessionId(panelChatId) || entry.chatId !== panelChatId) return;
for (const tab of saved?.state?.panels.tabs ?? []) {
if (!tab.sessionId || !tab.machineId || !['terminal', 'browser'].includes(tab.kind)) continue;
const joined = { ...tab, chatId: id };
const target = resolveTabConnection(joined);
const path = tab.kind === 'terminal' ? '/api/terminals' : '/browser/sessions';
const alive =
target &&
(await machineRequest(target, `${path}/${encodeURIComponent(tab.sessionId)}`).then(
() => true,
() => false
));
if (!alive || entry !== viewEntry || !viewReady) continue;
if (tabs.tabs.some((item) => item.id === tab.id)) continue;
const activeId = tabs.activeId;
tabs = activateTab(openTab(tabs, joined), activeId);
}
};
const navigatePageTab = async (id: string, href: string) => {
const url = new URL(href, location.origin);
if (url.pathname === '/' && !url.search) {
@@ -763,10 +819,11 @@
await tick();
};
$: if (viewReady && pendingPageTab) {
$: if (viewReady && pendingPageTab && isPanelViewReady(panelChatId, viewEntry)) {
const request = pendingPageTab;
pendingPageTab = null;
openPageTab(request);
// Once the restored tabs are in place, so they cannot overwrite the choice.
void tick().then(() => openPageTab(request));
}
$: if (viewReady && chatId) {
const duplicate = tabs.tabs.find(
@@ -785,7 +842,7 @@
return askForMachine(() => openFiles($selectedMachineId, directory, newTab, sourceModelId));
if (machineId ? !isMachineReachable(machineId) : !showFilesTab) return;
const target = resolveMachineTarget(machineId, $machines ?? [], localStorage.token, {
chatId: chatId,
chatId: panelChatId,
modelId: sourceModelId ?? null
});
const pinnedModel = target?.context.modelId ?? null;
@@ -831,7 +888,7 @@
) => {
if (!isMachineReachable(machineId)) return;
const target = resolveMachineTarget(machineId, $machines ?? [], localStorage.token, {
chatId: chatId,
chatId: panelChatId,
modelId: sourceModelId ?? null
});
const pinnedModel = target?.context.modelId ?? null;
@@ -1097,7 +1154,7 @@
? findPageTab(new URL(droppedPage.href!, location.origin))?.id
: savedId === chatId
? mainChatTabId
: tabs.tabs.find((tab) => tab.chatId === savedId)?.id);
: tabs.tabs.find((tab) => tab.kind === 'chat' && tab.chatId === savedId)?.id);
let id = existing;
if (!id) {
focusGroup(groupId);
@@ -1207,7 +1264,7 @@
}
const target = machineId
? resolveMachineTarget(machineId, $machines ?? [], localStorage.token ?? '', {
chatId: chatId,
chatId: panelChatId,
modelId: modelId ?? null
})
: null;
@@ -1215,8 +1272,8 @@
const machine = ($machines ?? []).find((item) => item.id === machineId);
const proxyBase =
baseUrl ??
(target && chatContextNeedsSavedChat(machine) && chatId
? `${target.baseUrl}/chats/${encodeURIComponent(chatId)}`
(target && chatContextNeedsSavedChat(machine) && panelChatId
? `${target.baseUrl}/chats/${encodeURIComponent(panelChatId)}`
: target?.baseUrl);
const id = uuidv4();
openPanel({
@@ -1647,7 +1704,7 @@
$: selectedConnection =
supportsMachineFiles && isMounted
? resolveMachineTarget($selectedMachineId, $machines ?? [], localStorage.token ?? '', {
chatId: chatId,
chatId: panelChatId,
modelId: modelId ?? null
})
: null;
@@ -1700,11 +1757,11 @@
};
$: {
selectedConnection;
chatId;
panelChatId;
void loadMachineFeatures();
}
$: if (isMounted && !chatLoading && $user?.id) followChat(viewState, chatId);
$: if (isMounted && !chatLoading && $user?.id) followChat(viewState, panelChatId);
$: if (
isMounted &&
viewReady &&
@@ -1777,7 +1834,8 @@
if (from?.url.pathname === to?.url.pathname) {
// The router stays on the main chat while other tabs are in front; going there uncovers it.
if (to && location.pathname !== to.url.pathname) {
focusMainChat();
// A folder's chats are tabs, opened again by the route.
if (!mainTabFolder || !to.url.pathname.startsWith('/c/')) focusMainChat();
if (!isLargeScreen) showTabs.set(false);
}
return;
@@ -1844,6 +1902,10 @@
mediaQuery.removeEventListener('change', handleMediaQuery);
};
});
$: activeChatTabId.set(
activeTab?.kind === 'chat' && activeTab.id !== mainChatTabId ? (activeTab.chatId ?? null) : null
);
onDestroy(() => activeChatTabId.set(null));
// Tab-opening handlers mutate tabs indirectly, so derive visibility and placement after them.
$: renderedTabs = fullWidth ? tabs : setMainChatTab(tabs, false);
$: layoutRects = fullWidth
@@ -1860,6 +1922,10 @@
.filter((group) => fullWidth || group.id === renderedTabs.activeGroupId)
.map((group) => group.activeId)
);
// A folder remembers many chats; each loads when it is first looked at.
let seenTabIds = new Set<string>();
$: if ([...visibleTabIds].some((id) => !seenTabIds.has(id)))
seenTabIds = new Set([...seenTabIds, ...visibleTabIds]);
$: mainChatActive = fullWidth && visibleTabIds.has(mainChatTabId);
$: if (isMounted && viewReady && !chatLoading) {
const active = tabs.tabs.find((tab) => tab.id === tabs.activeId);
@@ -1971,10 +2037,10 @@
{/if}
{#if showQuickOpen && supportsMachineFiles && selectedConnection}
{#key JSON.stringify([selectedConnection.baseUrl, selectedConnection.context.modelId, chatId])}
{#key JSON.stringify( [selectedConnection.baseUrl, selectedConnection.context.modelId, panelChatId] )}
<QuickOpen
target={selectedConnection}
{chatId}
chatId={panelChatId}
onclose={() => {
showQuickOpen = false;
}}
@@ -2104,7 +2170,7 @@
></div>
</div>
{/each}
{#each (viewReady ? tabs.tabs : []).filter((tab) => tab.id !== mainChatTabId) as tab (tab.kind === 'page' ? tab.id : `${viewEntry?.instanceId}:${tab.id}`)}
{#each (viewReady ? tabs.tabs : []).filter((tab) => tab.id !== mainChatTabId && (tab.kind !== 'chat' || !mainTabFolder || seenTabIds.has(tab.id))) as tab (tab.kind === 'page' ? tab.id : `${viewEntry?.instanceId}:${tab.id}`)}
{@const chatView = viewEntry!}
{@const target =
isMounted && $config && $user && $settings && $machines !== null
@@ -38,6 +38,7 @@
updateChatFolderIdById
} from '$lib/apis/chats';
import {
activeChatTabId,
chatId,
folders,
pinnedChats,
@@ -160,7 +161,7 @@
// would overwrite the `lastReadAt` prop with a stale server value.
let viewedAt: number | null = null;
$: if (id === $chatId) {
$: if (id === $chatId || id === $activeChatTabId) {
viewedAt = updatedAt ?? Date.now() / 1000;
}
@@ -179,7 +180,7 @@
selected ||
multiSelected;
$: chatItemClass = ` w-full flex justify-between rounded-xl px-2 py-1.5 ${
id === $chatId || confirmEdit
id === $chatId || id === $activeChatTabId || confirmEdit
? ($settings?.highContrastMode ?? false)
? 'bg-base-1000/[0.035] dark:bg-base-0/[0.06] selected'
: 'bg-base-1000/[0.035] dark:bg-base-0/[0.045] selected'
@@ -367,9 +367,9 @@
class="grid min-h-7 grid-cols-[7rem_minmax(0,1fr)] items-center gap-2 px-1 text-xs font-normal text-base-600 dark:text-base-400 sm:grid-cols-[8rem_minmax(0,1fr)]"
>
<ModelSettingsLabel
label={$i18n.t('Default machine')}
label={$i18n.t('Machine')}
description={$i18n.t(
'Select the machine used by default for new chats in this folder.'
'Chats, files and terminals in this folder run on this machine.'
)}
/>
<div class="flex min-w-0">
@@ -379,7 +379,7 @@
type="button"
class="flex w-fit max-w-full min-w-0 items-center gap-1 bg-transparent px-0.5 text-left text-xs font-normal text-base-900 dark:text-base-100"
>
<span class="sr-only">{$i18n.t('Default machine')}: </span>
<span class="sr-only">{$i18n.t('Machine')}: </span>
<span class="truncate">{selected ? label : $i18n.t('None')}</span>
<ChevronDown className="size-3 shrink-0" />
</button>
@@ -398,7 +398,7 @@
<ModelSettingsLabel
label={$i18n.t('Working directory')}
description={$i18n.t(
'Path on the selected machine. Applies to new chats only.'
'Path on the selected machine. Chats, files and terminals in this folder start here.'
)}
/>
</label>
+66 -7
View File
@@ -1,14 +1,21 @@
import { browser } from '$app/environment';
import { v4 as uuidv4 } from 'uuid';
import { writable } from 'svelte/store';
import { getChatView, updateChatView } from '$lib/apis/chats/view';
import {
ChatViewConflict,
getChatView,
updateChatView,
type SavedChatView
} from '$lib/apis/chats/view';
import { machineRequest, type MachineTarget } from '$lib/apis/machines';
import { createBrowserSession } from '$lib/apis/machines/browser';
import { isSavedChatId } from '$lib/utils/chatId';
import { isFolderSessionId, isSavedChatId } from '$lib/utils/chatId';
import {
activateTab,
createTabsState,
mainChatTabId,
normalizeChatTab,
openTab,
removeTab,
type ChatViewState,
type Tab
@@ -34,6 +41,8 @@ type Entry = {
pending: Map<string, Promise<void>>;
revision: number;
persistedRevision: number;
/** Revision of the saved folder view the next save replaces. */
savedRevision: number;
persisted?: string;
loaded: boolean;
persistent: boolean;
@@ -99,8 +108,9 @@ export function chatViewEntry(userId: string, chatId: string | null, temporary =
pending: new Map(),
revision: 0,
persistedRevision: 0,
loaded: !isSavedChatId(chatId) || temporary,
persistent: isSavedChatId(chatId) && !temporary,
savedRevision: 0,
loaded: !isFolderSessionId(chatId) && (!isSavedChatId(chatId) || temporary),
persistent: isFolderSessionId(chatId) || (isSavedChatId(chatId) && !temporary),
promoting: false,
error: '',
sessionErrors: {}
@@ -118,6 +128,7 @@ export async function loadChatView(entry: Entry) {
const result = await getChatView(entry.chatId!);
if (result.state && result.state.schemaVersion !== 1)
throw new Error('Unsupported chat view version');
if (!entry.loaded) entry.savedRevision = result.revision ?? 0;
if (!entry.loaded && result.state) {
entry.state = normalizeViewMachineId(result.state);
entry.state.panels.tabs = entry.state.panels.tabs.map((tab) =>
@@ -147,6 +158,29 @@ export function changeChatView(entry: Entry, state = entry.state, immediate = fa
notify();
}
/** Takes the tabs another window opened and closed; this window keeps its own arrangement. */
function mergeSavedView(entry: Entry, saved: SavedChatView) {
const before = new Set<string>(
entry.persisted
? JSON.parse(entry.persisted).panels.tabs.map((tab: Tab) => tab.id)
: [mainChatTabId]
);
const savedTabs = saved.state?.panels.tabs ?? [];
let panels = entry.state.panels;
for (const tab of panels.tabs) {
if (before.has(tab.id) && !savedTabs.some((item) => item.id === tab.id))
panels = removeTab(panels, tab.id);
}
const activeId = panels.activeId;
for (const tab of savedTabs) {
if (!before.has(tab.id) && !panels.tabs.some((item) => item.id === tab.id))
panels = openTab(panels, tab);
}
entry.savedRevision = saved.revision ?? 0;
entry.persisted = saved.state ? JSON.stringify(saved.state) : undefined;
changeChatView(entry, { ...entry.state, panels: activateTab(panels, activeId) });
}
export async function flushChatView(entry: Entry): Promise<void> {
clearTimeout(entry.timer);
if (!entry.loaded || !entry.persistent || entry.promoting) return;
@@ -161,7 +195,18 @@ export async function flushChatView(entry: Entry): Promise<void> {
const revision = entry.revision;
const snapshot = JSON.stringify(serializeChatView(entry.state));
if (snapshot !== entry.persisted) {
await updateChatView(entry.chatId!, JSON.parse(snapshot));
try {
const saved = await updateChatView(
entry.chatId!,
JSON.parse(snapshot),
entry.savedRevision
);
entry.savedRevision = saved.revision ?? 0;
} catch (error) {
if (!(error instanceof ChatViewConflict)) throw error;
mergeSavedView(entry, error.saved);
continue;
}
entry.persisted = snapshot;
}
entry.persistedRevision = revision;
@@ -193,7 +238,9 @@ export function updateViewTab(entry: Entry, id: string, values: Partial<Tab>) {
export function renameChatTabs(chatId: string, label: string) {
for (const entry of entries.values()) {
const tabs = entry.state.panels.tabs.filter((t) => t.chatId === chatId && t.label !== label);
const tabs = entry.state.panels.tabs.filter(
(t) => t.kind === 'chat' && t.chatId === chatId && t.label !== label
);
if (!tabs.length) continue;
for (const tab of tabs) tab.label = label;
changeChatView(entry);
@@ -215,7 +262,12 @@ export function closeChatTabs(chatId: string) {
}
}
export function createViewSession(entry: Entry, id: string, target: MachineTarget) {
export function createViewSession(
entry: Entry,
id: string,
target: MachineTarget,
directory?: string
) {
const pending = entry.pending.get(id);
if (pending) return pending;
const tab = entry.state.panels.tabs.find((tab) => tab.id === id);
@@ -223,6 +275,13 @@ export function createViewSession(entry: Entry, id: string, target: MachineTarge
delete entry.sessionErrors[id];
const request = (async () => {
try {
// A folder's shells start in its directory; a chat's follow the directory of the chat.
if (directory && tab.kind === 'terminal' && isFolderSessionId(target.context.chatId))
await machineRequest(target, '/files/cwd', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ path: directory })
});
const session =
tab.kind === 'browser'
? await createBrowserSession(target, tab.path ?? '')
+2
View File
@@ -227,6 +227,8 @@ export const embed = writable<any>(null);
/** Whether the main chat is temporary, or for a new chat, whether it starts as one. */
export const temporaryChat = writable(false);
export const openEmbeddedChatIds = writable<Set<string>>(new Set());
/** The saved chat whose tab is in front, when it is not the main chat. */
export const activeChatTabId = writable<string | null>(null);
export const chatTabRequest = writable<
{ parentChatId: string; prompt: string } | { folderId: string } | null
>(null);
+12 -1
View File
@@ -3,6 +3,7 @@ import { v4 as uuidv4 } from 'uuid';
const TEMPORARY_CHAT_ID_PREFIX = 'temporary:';
const LEGACY_TEMPORARY_CHAT_ID_PREFIX = 'local:'; // Legacy temporary chat prefix.
const CHANNEL_CHAT_ID_PREFIX = 'channel:';
const FOLDER_SESSION_ID_PREFIX = 'folder:';
export const createTemporaryChatId = (sessionId: string | undefined) => {
if (!sessionId) throw new Error('Connect before starting a temporary chat');
@@ -15,4 +16,14 @@ export const isTemporaryChatId = (chatId: string | null | undefined) =>
chatId.startsWith(LEGACY_TEMPORARY_CHAT_ID_PREFIX));
export const isSavedChatId = (chatId: string | null | undefined) =>
!!chatId && !isTemporaryChatId(chatId) && !chatId.startsWith(CHANNEL_CHAT_ID_PREFIX);
!!chatId &&
!isTemporaryChatId(chatId) &&
!chatId.startsWith(CHANNEL_CHAT_ID_PREFIX) &&
!chatId.startsWith(FOLDER_SESSION_ID_PREFIX);
/** The session a person's panels in a folder run under, in place of a chat id. */
export const folderSessionId = (folderId: string, userId: string) =>
`${FOLDER_SESSION_ID_PREFIX}${folderId}:${userId}`;
export const isFolderSessionId = (id: string | null | undefined) =>
!!id && id.startsWith(FOLDER_SESSION_ID_PREFIX);