Files
cutdex/test/app_database_test.dart
T

572 lines
20 KiB
Dart

import 'dart:io';
import 'package:cutdex/integrations/agent/agent_models.dart';
import 'package:cutdex/persistence/app_database.dart';
import 'package:cutdex/persistence/app_settings_repositories.dart';
import 'package:cutdex/workspace/project_state.dart';
import 'package:cutdex/workspace/workspace_mode.dart';
import 'package:cutdex/workspace/persistence/recent_projects.dart';
import 'package:drift/native.dart';
import 'package:drift/drift.dart' show Value;
import 'package:cutdex_sdk/timeline/layout.dart';
import 'package:cutdex_sdk/timeline/model.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:path/path.dart' as p;
import 'package:sqlite3/sqlite3.dart';
void main() {
for (final version in [2, 3, 4]) {
test(
'schema $version upgrades while preserving project preferences',
() async {
final directory = await Directory.systemTemp.createTemp(
'app-view-schema-',
);
addTearDown(() => directory.delete(recursive: true));
final file = File(p.join(directory.path, 'app.sqlite'));
final current = AppDatabase(NativeDatabase(file));
await DriftProjectViewSettingsRepository(current).save(
'project',
const ProjectViewSettingsData(
propertiesOpen: true,
timelineHeight: 280,
),
);
await current.close();
final old = sqlite3.open(file.path);
try {
old.execute(
'ALTER TABLE project_view_configurations DROP COLUMN media_width',
);
if (version < 4) {
old.execute(
'ALTER TABLE appearance_configurations DROP COLUMN timeline_ruler_layout',
);
}
if (version == 2) {
old.execute(
'ALTER TABLE appearance_configurations DROP COLUMN palette',
);
}
old.userVersion = version;
} finally {
old.close();
}
final reopened = AppDatabase(NativeDatabase(file));
addTearDown(reopened.close);
final repository = DriftProjectViewSettingsRepository(reopened);
final restored = await repository.load('project');
expect(restored.propertiesOpen, isTrue);
expect(restored.timelineHeight, 280);
expect(restored.mediaWidth, isNull);
await repository.save('project', restored.copyWith(mediaWidth: 380));
expect((await repository.load('project')).mediaWidth, 380);
expect(
(await reopened.customSelect('PRAGMA user_version').getSingle())
.read<int>('user_version'),
5,
);
},
);
}
test(
'old app settings schema is rejected without changing its data',
() async {
final directory = await Directory.systemTemp.createTemp('app-schema-');
addTearDown(() => directory.delete(recursive: true));
final file = File(p.join(directory.path, 'app.sqlite'));
final current = AppDatabase(NativeDatabase(file));
await DriftWorkspaceViewSettingsRepository(current)
.save(const WorkspaceViewSettingsData(mode: WorkspaceMode.cut));
await current.close();
final old = sqlite3.open(file.path);
try {
old.execute(
'ALTER TABLE workspace_view_configurations RENAME COLUMN mode TO layout_mode',
);
old.userVersion = 1;
} finally {
old.close();
}
final before = await file.readAsBytes();
final reopened = AppDatabase(NativeDatabase(file));
addTearDown(reopened.close);
await expectLater(
DriftWorkspaceViewSettingsRepository(reopened).load(),
throwsStateError,
);
expect(await file.readAsBytes(), orderedEquals(before));
},
);
test('unknown stored language falls back to the system locale', () async {
final database = AppDatabase(NativeDatabase.memory());
addTearDown(database.close);
await database
.into(database.languageConfigurations)
.insert(
LanguageConfigurationsCompanion.insert(
id: const Value(0),
language: 'unknown',
),
);
expect(
await DriftLanguageSettingsRepository(database).load(),
AppLanguage.system,
);
});
test('provider enabled state persists across repository loads', () async {
final database = AppDatabase(NativeDatabase.memory());
addTearDown(database.close);
final repository = DriftAgentSettingsRepository(database);
await repository.save(
const AgentSettingsState(
providers: [
AgentProviderSettings(
id: 'disabled',
name: 'Disabled',
apiType: 'anthropicMessages',
baseUrl: 'https://example.com/v1',
enabled: false,
models: [AgentModelSettings(id: 'model')],
),
],
),
);
final loaded = await repository.load();
expect(loaded.providers.single.enabled, false);
expect(loaded.providers.single.models.single.id, 'model');
});
test(
'batched agent settings replace providers and all their models',
() async {
final database = AppDatabase(NativeDatabase.memory());
addTearDown(database.close);
final repository = DriftAgentSettingsRepository(database);
await repository.save(
AgentSettingsState(
enabled: true,
selectedProviderId: 'one',
selectedModelId: 'model-0',
revision: 1,
providers: [
for (final id in ['one', 'two'])
AgentProviderSettings(
id: id,
name: id,
apiType: 'openAiChatCompletions',
baseUrl: 'https://example.com/v1',
credentialId: 'credential-$id',
models: [
for (var index = 0; index < 50; index++)
AgentModelSettings(
id: 'model-$index',
contextWindow: 32000 + index,
maxOutputTokens: 4096,
),
],
),
],
),
);
final saved = await repository.load();
expect(saved.providers, hasLength(2));
for (final provider in saved.providers) {
expect(provider.models, hasLength(50));
expect(
provider.models.singleWhere((m) => m.id == 'model-49').contextWindow,
32049,
);
expect(provider.credentialId, 'credential-${provider.id}');
}
final replacement = saved.copyWith(
revision: 2,
selectedModelId: 'replacement',
providers: [
saved.providers.first.copyWith(
models: const [AgentModelSettings(id: 'replacement')],
),
],
);
await repository.save(replacement);
expect(await repository.load(), replacement);
await repository.save(const AgentSettingsState(revision: 3));
expect(await repository.load(), const AgentSettingsState(revision: 3));
expect(await database.select(database.agentModels).get(), isEmpty);
},
);
test(
'a failed agent model batch rolls back the whole configuration',
() async {
final database = AppDatabase(NativeDatabase.memory());
addTearDown(database.close);
final repository = DriftAgentSettingsRepository(database);
const saved = AgentSettingsState(
enabled: true,
selectedProviderId: 'provider',
selectedModelId: 'model',
revision: 1,
providers: [
AgentProviderSettings(
id: 'provider',
name: 'Provider',
apiType: 'openAiChatCompletions',
baseUrl: 'https://example.com/v1',
models: [AgentModelSettings(id: 'model')],
),
],
);
await repository.save(saved);
final invalid = saved.copyWith(
enabled: false,
revision: 2,
providers: [
saved.providers.single.copyWith(
models: const [
AgentModelSettings(id: 'duplicate'),
AgentModelSettings(id: 'duplicate'),
],
),
],
);
await expectLater(
repository.save(invalid),
throwsA(isA<SqliteException>()),
);
expect(await repository.load(), saved);
final retry = saved.copyWith(enabled: false, revision: 2);
await repository.save(retry);
expect(await repository.load(), retry);
},
);
test('typed app repositories share one Drift database', () async {
final database = AppDatabase(NativeDatabase.memory());
addTearDown(database.close);
expect(
(await database.customSelect('PRAGMA user_version').getSingle())
.read<int>('user_version'),
5,
);
final appearance = DriftAppearanceSettingsRepository(database);
expect(await appearance.load(), AppAppearance.system);
await appearance.save(AppAppearance.penLight);
expect(await appearance.load(), AppAppearance.penLight);
await appearance.save(AppAppearance.penDark);
expect(await appearance.load(), AppAppearance.penDark);
final language = DriftLanguageSettingsRepository(database);
expect(await language.load(), AppLanguage.system);
await language.save(AppLanguage.japanese);
expect(await language.load(), AppLanguage.japanese);
await language.save(AppLanguage.system);
expect(await language.load(), AppLanguage.system);
final conversationLocation = DriftConversationLocationSettingsRepository(
database,
);
expect(await conversationLocation.load(), isNull);
await conversationLocation.save('/conversations');
expect(await conversationLocation.load(), '/conversations');
final projectLocation = DriftProjectLocationSettingsRepository(database);
expect(await projectLocation.load(), isNull);
await projectLocation.save('/projects');
expect(await projectLocation.load(), '/projects');
final resourceLocation = DriftResourceLocationSettingsRepository(database);
expect(await resourceLocation.load(), isNull);
await resourceLocation.save('/resources');
expect(await resourceLocation.load(), '/resources');
final mcp = DriftMcpSettingsRepository(database);
expect(await mcp.load(), isNull);
await mcp.save(
const McpSettingsValue(enabled: true, port: 47831, token: 'token'),
);
final mcpValue = await mcp.load();
expect(mcpValue?.enabled, isTrue);
expect(mcpValue?.port, 47831);
expect(mcpValue?.token, 'token');
final agent = DriftAgentSettingsRepository(database);
await agent.save(
const AgentSettingsState(
enabled: true,
selectedProviderId: 'provider',
selectedModelId: 'model',
revision: 3,
providers: [
AgentProviderSettings(
id: 'provider',
name: 'Provider',
apiType: 'openAiChatCompletions',
baseUrl: 'https://example.com/v1',
credentialId: 'credential',
models: [
AgentModelSettings(
id: 'model',
contextWindow: 32000,
maxOutputTokens: 4096,
),
],
),
],
),
);
final agentValue = await agent.load();
expect(agentValue.enabled, isTrue);
expect(agentValue.selectedModelId, 'model');
expect(agentValue.providers.single.credentialId, 'credential');
expect(agentValue.providers.single.models.single.contextWindow, 32000);
final workspaceView = DriftWorkspaceViewSettingsRepository(database);
final columns = await database
.customSelect('PRAGMA table_info(workspace_view_configurations)')
.get();
expect(columns.map((row) => row.read<String>('name')), contains('mode'));
expect(
columns.map((row) => row.read<String>('name')),
isNot(contains('layout_mode')),
);
final initialWorkspace = await workspaceView.load();
expect(initialWorkspace.hasSavedState, isFalse);
expect(initialWorkspace.mode, WorkspaceMode.agent);
await workspaceView.save(
const WorkspaceViewSettingsData(
activeProjectId: 'two',
sidebarCollapsed: true,
sidebarWidth: 312,
),
);
final workspaceValue = await workspaceView.load();
expect(workspaceValue.hasSavedState, isTrue);
expect(workspaceValue.activeProjectId, 'two');
expect(workspaceValue.sidebarCollapsed, isTrue);
expect(workspaceValue.sidebarWidth, 312);
final projectView = DriftProjectViewSettingsRepository(database);
await projectView.save(
'two',
const ProjectViewSettingsData(
propertiesOpen: true,
timelineHeight: 280,
mediaWidth: 360,
),
);
final projectValue = await projectView.load('two');
expect(projectValue.propertiesOpen, isTrue);
expect(projectValue.timelineHeight, 280);
expect(projectValue.mediaWidth, 360);
final timelineView = DriftTimelineViewSettingsRepository(database);
await timelineView.save(
'two',
'timeline',
SequenceId('one'),
TimelineSequenceViewState(
playheadTick: 120,
camera: TimelineCamera(
baseTick: 40,
fractionalTick: .25,
pixelsPerTick: .5,
verticalOffset: 18,
),
),
);
await timelineView.save(
'two',
'timeline',
SequenceId('two'),
TimelineSequenceViewState(
playheadTick: 240,
camera: TimelineCamera(
baseTick: 80,
pixelsPerTick: .75,
verticalOffset: 24,
),
),
);
final timelineValue = await timelineView.load('two', 'timeline');
expect(timelineValue.activeSequenceId, SequenceId('two'));
expect(timelineValue.sequences.keys, {
SequenceId('one'),
SequenceId('two'),
});
expect(timelineValue.sequences[SequenceId('one')]?.playheadTick, 120);
expect(timelineValue.sequences[SequenceId('one')]?.camera.baseTick, 40);
final recent = DriftRecentProjectsRepository(database);
const first = RecentProject(id: 'one', name: 'One', path: '/one');
const second = RecentProject(id: 'two', name: 'Two', path: '/two');
await recent.save([second, first]);
expect(await recent.load(), [second, first]);
await expectLater(
recent.save([first, first]),
throwsA(isA<SqliteException>()),
);
expect(await recent.load(), [second, first]);
await recent.rememberTimeline('two', 'timeline');
expect(await recent.lastTimeline('two'), 'timeline');
await recent.save([]);
expect(await recent.load(), isEmpty);
});
test(
'project location defaults to Documents/Cutdex/Projects and is persisted',
() async {
final database = AppDatabase(NativeDatabase.memory());
addTearDown(database.close);
final documents = await Directory.systemTemp.createTemp(
'cutdex-documents-',
);
addTearDown(() => documents.delete(recursive: true));
final stored = DriftProjectLocationSettingsRepository(database);
final repository = DefaultingProjectLocationSettingsRepository(
stored,
documentsDirectory: () async => documents,
);
final location = await repository.load();
expect(location, p.join(documents.path, 'Cutdex', 'Projects'));
expect(await Directory(location).exists(), isFalse);
expect(await stored.load(), location);
await Directory(location).create(recursive: true);
await Directory(location).delete();
expect(await repository.load(), location);
expect(await Directory(location).exists(), isFalse);
},
);
test('resource location creates the managed directory layout', () async {
final database = AppDatabase(NativeDatabase.memory());
addTearDown(database.close);
final documents = await Directory.systemTemp.createTemp(
'cutdex-resource-documents-',
);
addTearDown(() => documents.delete(recursive: true));
final stored = DriftResourceLocationSettingsRepository(database);
final repository = DefaultingResourceLocationSettingsRepository(
stored,
documentsDirectory: () async => documents,
);
final location = await repository.load();
expect(location, p.join(documents.path, 'Cutdex', 'Resources'));
for (final name in ['Processing', 'Downloads', 'Cache']) {
expect(await Directory(p.join(location, name)).exists(), isTrue);
}
expect(await stored.load(), location);
});
test('app settings survive closing and reopening the database', () async {
final directory = await Directory.systemTemp.createTemp('cutdex-app-db-');
final file = File('${directory.path}/app.sqlite');
addTearDown(() => directory.delete(recursive: true));
final first = AppDatabase(NativeDatabase(file));
await DriftAppearanceSettingsRepository(first).save(AppAppearance.penLight);
await DriftProjectLocationSettingsRepository(first).save('/projects');
await DriftLanguageSettingsRepository(first)
.save(AppLanguage.simplifiedChinese);
await DriftConversationLocationSettingsRepository(first)
.save('/conversations');
await DriftMcpSettingsRepository(first).save(
const McpSettingsValue(enabled: true, port: 47832, token: 'persisted'),
);
await DriftAgentSettingsRepository(first).save(
const AgentSettingsState(
enabled: true,
selectedProviderId: 'provider',
selectedModelId: 'model',
revision: 1,
providers: [
AgentProviderSettings(
id: 'provider',
name: 'Provider',
apiType: 'openAiChatCompletions',
baseUrl: 'https://example.com/v1',
models: [AgentModelSettings(id: 'model')],
),
],
),
);
await DriftRecentProjectsRepository(first)
.rememberTimeline('project', 'timeline');
await DriftWorkspaceViewSettingsRepository(first).save(
const WorkspaceViewSettingsData(
activeProjectId: 'project',
mode: WorkspaceMode.cut,
sidebarWidth: 300,
),
);
await DriftProjectViewSettingsRepository(first).save(
'project',
const ProjectViewSettingsData(propertiesOpen: true, mediaWidth: 380),
);
await DriftTimelineViewSettingsRepository(first).save(
'project',
'timeline',
SequenceId('sequence'),
TimelineSequenceViewState(
playheadTick: 360,
camera: TimelineCamera(baseTick: 120, pixelsPerTick: .5),
),
);
await first.close();
final reopened = AppDatabase(NativeDatabase(file));
addTearDown(reopened.close);
expect(
await DriftAppearanceSettingsRepository(reopened).load(),
AppAppearance.penLight,
);
expect(
await DriftProjectLocationSettingsRepository(reopened).load(),
'/projects',
);
expect(
await DriftLanguageSettingsRepository(reopened).load(),
AppLanguage.simplifiedChinese,
);
expect(
await DriftConversationLocationSettingsRepository(reopened).load(),
'/conversations',
);
final mcp = await DriftMcpSettingsRepository(reopened).load();
expect((mcp?.enabled, mcp?.port, mcp?.token), (true, 47832, 'persisted'));
final agent = await DriftAgentSettingsRepository(reopened).load();
expect((agent.enabled, agent.selectedModelId), (true, 'model'));
expect(
await DriftRecentProjectsRepository(reopened).lastTimeline('project'),
'timeline',
);
final workspace = await DriftWorkspaceViewSettingsRepository(reopened)
.load();
expect(workspace.activeProjectId, 'project');
expect(workspace.mode, WorkspaceMode.cut);
expect(workspace.sidebarWidth, 300);
expect(
(await DriftProjectViewSettingsRepository(reopened).load('project'))
.propertiesOpen,
isTrue,
);
expect(
(await DriftProjectViewSettingsRepository(reopened).load('project'))
.mediaWidth,
380,
);
final timeline = await DriftTimelineViewSettingsRepository(reopened)
.load('project', 'timeline');
expect(timeline.activeSequenceId, SequenceId('sequence'));
expect(timeline.sequences[SequenceId('sequence')]?.playheadTick, 360);
});
}