using System.Security.Claims; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Abstractions; using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewEngines; using Microsoft.AspNetCore.Mvc.ViewFeatures; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.FileProviders; using PlotLine.Controllers; using PlotLine.Data; using PlotLine.Models; using PlotLine.Services; using PlotLine.ViewModels; // Isolated, loopback-only host: renders real compiled Razor chrome, never starts app workers or connects to a database. internal static class ToolbarBrowserHost { private static readonly System.Collections.Concurrent.ConcurrentDictionary<(int User, int Chapter), ChapterGoal> writerGoals = new(); private static PlotLineWorkspaceData HealthFixture() { var f = new PlotHealthTests.Fixture(); f.Add(11, 1, "Introduced"); f.Add(11, 20, "Mentioned"); f.Add(11, 29, "Note"); f.Add(22, 1, "Developed"); return f.Data(); } private static SceneEditViewModel SceneWorkspaceFixture() { // Optional read-only export for visual checks. This host never accesses the database. var snapshot = Environment.GetEnvironmentVariable("PD_SCENE_VISUAL_FIXTURE"); if (!string.IsNullOrEmpty(snapshot)) return System.Text.Json.JsonSerializer.Deserialize(File.ReadAllText(snapshot))!; return new() { SceneID = 101, SceneTitle = "Arrival at the harbour", ChapterID = 21, SceneNumber = 1, Project = new Project { ProjectID = 7, ProjectName = "The Glass Harbour" }, Book = new Book { BookID = 12, ProjectID = 7, BookTitle = "A Distant Shore" }, Chapter = new Chapter { ChapterID = 21, ChapterNumber = 1, ChapterTitle = "The crossing" }, RevisionStatusID = 1, RevisionStatuses = [new SelectListItem("Planned", "1")], POVCharacterID = 1, CharacterOptions = [new SelectListItem("Mara Vale", "1"), new SelectListItem("Elias", "2")], RelativeTimeText = "Before dawn", Summary = "Mara reaches the harbour carrying a letter she cannot explain.", ScenePurposeTypes = [new() { ScenePurposeTypeID = 1, PurposeName = "Setup" }], SelectedPurposeTypeIds = [1], ScenePurposeNotes = "Establish the mystery", SceneOutcomeNotes = "Mara decides to stay", Metrics = [new() { MetricName = "Tension", MinValue = 1, MaxValue = 10, Value = 7 }], SceneCharacters = Enumerable.Range(1, 8).Select(i => new SceneCharacter { CharacterID = i, CharacterName = i == 1 ? "Mara Vale" : $"Harbour character {i}", RoleInSceneTypeName = i == 1 ? "POV" : "Supporting" }).ToList(), ThreadEvents = [new() { EventTitle = "The letter", ThreadTitle = "Missing sender", PlotLineName = "Harbour mystery", EventDescription = "A clue at the water's edge." }], Warnings = Enumerable.Range(1, 6).Select(i => new ContinuityWarning { ContinuityWarningID = i, WarningTypeName = "Location", Message = $"Review location evidence {i}." }).ToList(), CharacterKnowledge = [new() { CharacterKnowledgeID = 1, CharacterID = 1, CharacterName = "Mara Vale", AssetName = "The letter", KnowledgeStateName = "Knows", Description = "Mara knows the letter was delivered before dawn. She has not yet discovered who sent it." }], Notes = [new() { NoteTitle = "Atmosphere", NoteText = "Keep the harbour quiet." }, new() { NoteTitle = "Next draft", NoteText = "Let the letter carry the tension. Hold back the identity of the sender until the next chapter." }], ChecklistItems = [new() { ItemText = "Check the tide", IsCompleted = false }] }; } private static SceneContinuityEditorViewModel SceneContinuityFixture() { var scene = SceneWorkspaceFixture(); return new() { Scene = scene, Dashboard = new WarningDashboardViewModel { Project = scene.Project!, BookID = scene.Book?.BookID, ProjectWarnings = scene.Warnings.Select(w => new ProjectWarningViewModel { ContinuityWarningID = w.ContinuityWarningID, Source = "Persisted", WarningTypeDisplayName = w.WarningTypeName, Message = w.Message, Severity = "Warning", SceneID = scene.SceneID }).ToList() }}; } private static T FixtureProxy(Func handler) where T : class { var proxy = System.Reflection.DispatchProxy.Create(); ((StoryPointProxy)(object)proxy).Handler = handler; return proxy; } private static Task SaveFixtureGoal(int userId, ChapterGoalEditViewModel model) { writerGoals[(userId, model.ChapterID)] = new() { ChapterID = model.ChapterID, ChapterGoalID = model.ChapterGoalID, GoalSummary = model.GoalSummary, EmotionalGoal = model.EmotionalGoal, ReaderTakeaway = model.ReaderTakeaway, MustInclude = model.MustInclude, RisksOrConcerns = model.RisksOrConcerns }; return Task.CompletedTask; } private static WriterDashboardViewModel WriterFixture() => new() { ProjectID = 7, ProjectOptions = [new SelectListItem("The Glass Harbour", "7", true)], WriteNext = [new() { ProjectID = 7, BookID = 12, BookTitle = "A Distant Shore", ChapterID = 21, ChapterNumber = 1, SceneID = 101, SceneNumber = 1, SceneTitle = "The crossing", RevisionStatusName = "Outlined", Summary = "A synthetic writing task." }] }; private static async Task RenderFullAsync(HttpContext context, string controller, string actionName, object model) { context.Request.RouteValues["controller"] = controller; context.Request.RouteValues["action"] = actionName; var action = new ActionContext(context, new RouteData(context.Request.RouteValues), new ActionDescriptor()); var view = context.RequestServices.GetRequiredService().GetView(null, $"/Views/{controller}/{actionName}.cshtml", true); if (!view.Success) throw new Exception(string.Join(",", view.SearchedLocations)); using var writer = new StringWriter(); await view.View.RenderAsync(new ViewContext(action, view.View, new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary()) { Model = model }, new TempDataDictionary(context, context.RequestServices.GetRequiredService()), writer, new HtmlHelperOptions())); context.Response.ContentType = "text/html; charset=utf-8"; await context.Response.WriteAsync(writer.ToString()); } public static async Task RunAsync() { var builder = WebApplication.CreateBuilder(new WebApplicationOptions { ApplicationName = typeof(ToolbarController).Assembly.FullName, ContentRootPath = Path.GetFullPath("PlotLine") }); builder.Services.AddControllersWithViews().AddApplicationPart(typeof(ToolbarController).Assembly); builder.Services.AddSignalR(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(FixtureProxy((name, args) => throw new NotSupportedException(name))); builder.Services.AddSingleton(FixtureProxy((name, args) => throw new NotSupportedException(name))); builder.Services.AddSingleton(FixtureProxy((name, args) => throw new NotSupportedException(name))); builder.Services.AddSingleton(); builder.Services.AddHttpContextAccessor(); builder.Services.AddSingleton(); builder.Services.AddScoped(services => new ApplicationNavigation( FixtureProxy((name, args) => name == "GetForUserAsync" ? Task.FromResult(new Project { ProjectID = 7, ProjectName = "The Glass Harbour", AccessRole = "Owner" }) : throw new NotSupportedException(name)), FixtureProxy((name, args) => name == "ListByProjectAsync" ? Task.FromResult>([new() { BookID = 12, ProjectID = 7, BookTitle = "A Distant Shore" }, new() { BookID = 13, ProjectID = 7, BookTitle = "The Return" }]) : throw new NotSupportedException(name)), services.GetRequiredService())); builder.Services.AddScoped(services => FixtureProxy((name, args) => name switch { "GetDashboardAsync" => Task.FromResult(WriterFixture()), "GetChapterWorkflowAsync" => Task.FromResult(new() { Project = new() { ProjectID = 7, ProjectName = "The Glass Harbour" }, Book = new() { BookID = 12, ProjectID = 7, BookTitle = "A Distant Shore" }, Chapter = new() { ChapterID = 21, BookID = 12, ChapterNumber = 1, ChapterTitle = "The crossing" }, Goal = writerGoals.GetOrAdd((services.GetRequiredService().UserId!.Value, 21), _ => new() { ChapterID = 21, GoalSummary = "Reveal the consequence" }) }), "SaveChapterGoalAsync" => SaveFixtureGoal(services.GetRequiredService().UserId!.Value, (ChapterGoalEditViewModel)args![0]!), _ => throw new NotSupportedException(name) })); builder.Services.AddSingleton(FixtureProxy((name, args) => name switch { "GetTodayDashboardAsync" => Task.FromResult(new WritingScheduleDashboardViewModel()), "GetWritingPlansForManagementAsync" => Task.FromResult(new WritingPlansManagementViewModel()), "GetSchedulePreviewAsync" => Task.FromResult(new WritingSchedulePreviewViewModel()), "GetScheduleSetupAsync" => Task.FromResult(new WritingScheduleSetupViewModel()), _ => throw new NotSupportedException(name) })); builder.Services.AddSingleton(FixtureProxy((name, args) => name == "GetEffectiveEntitlementAsync" ? Task.FromResult(new EffectiveEntitlement { UserID = 4, State = EntitlementState.ActivePaid }) : throw new NotSupportedException(name))); builder.Services.AddSingleton(FixtureProxy((name, args) => name == "CountAttentionForUserAsync" ? Task.FromResult(0) : throw new NotSupportedException(name))); builder.Services.AddSingleton(FixtureProxy((name, args) => name == "ShouldShowWordCompanionHeaderAsync" ? Task.FromResult(false) : throw new NotSupportedException(name))); builder.Services.AddSingleton(FixtureProxy((name, args) => name == "GetForCurrentUserAsync" ? Task.FromResult(new StoryIntelligenceGlobalProgressViewModel()) : throw new NotSupportedException(name))); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddMemoryCache(); builder.Services.AddSingleton(); builder.Services.AddScoped(); builder.Services.AddSingleton(); builder.Services.AddSingleton(services=>new WritingSolverPayoff(Path.GetFullPath("PlotLine/Content/WritingSolver/Presentation/payoff-v1.json"))); builder.Services.AddAuthorization(options=>options.AddPolicy("AdminOnly",policy=>policy.RequireClaim(ClaimTypes.Role,"SolverReviewer"))); builder.Services.AddSingleton(new WritingProblemEditorial(Path.GetFullPath("PlotLine/Content/WritingSolver/Editorial/pages-v1.json"))); builder.Services.AddSingleton(new WritingSolverResults(Path.GetFullPath("PlotLine/Content/WritingSolver/Presentation/results-v1.json"))); builder.Services.AddSingleton(); builder.Services.AddScoped(services => new ToolbarTestUser(int.Parse(services.GetRequiredService().HttpContext!.User.FindFirstValue(ClaimTypes.NameIdentifier)!))); builder.Services.AddAuthentication("ReviewFixture").AddCookie("ReviewFixture",options=>{options.Events.OnRedirectToLogin=c=>{c.Response.StatusCode=401;return Task.CompletedTask;};options.Events.OnRedirectToAccessDenied=c=>{c.Response.StatusCode=403;return Task.CompletedTask;};}); builder.Services.AddSingleton(new StoryCalendarService(new FakeTimelineRepository(CalendarNavigationTests.Data()))); var app = builder.Build(); app.UseWritingSolverReviewBoundary(); app.Urls.Add(Environment.GetEnvironmentVariable("PD_BROWSER_FIXTURE_URL") ?? "http://127.0.0.1:5238"); app.UseStaticFiles(new StaticFileOptions { FileProvider = new PhysicalFileProvider(Path.GetFullPath("PlotLine/wwwroot")) }); app.Use(async (context, next) => { var user = context.Request.Cookies["fixture-user"] == "5" ? "5" : "4"; context.User = new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, user), new Claim(ClaimTypes.Name, "Fixture Author")], "Fixture")); if(context.Request.Cookies["solver-reviewer"]=="true") ((ClaimsIdentity)context.User.Identity!).AddClaim(new Claim(ClaimTypes.Role,"SolverReviewer")); if(context.Request.Cookies["solver-anonymous"]=="true") context.User=new ClaimsPrincipal(new ClaimsIdentity()); await next(); }); app.UseRouting(); app.UseAuthorization(); app.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}"); app.MapGet("/Projects", () => Results.Redirect("/fixture")); app.MapGet("/map-story-fixture", () => { var projection = MapStoryComposer.Compose(MapStoryTests.Fixture(), MapStoryTests.Plots(), 1); projection.UserID=4;return Results.Json(projection); }); app.MapGet("/plot-map-fixture", async context => { var data = context.Request.Query["marketing"] == "true" ? PublicWebsiteFixtures.PlotMap() : context.Request.Query["health"] == "true" || context.Request.Query["healthDetail"] == "true" ? HealthFixture() : PlotLineWorkspaceTests.Fixture(); var ids = context.Request.Query["focus"] == "true" ? new[] { 1 } : new[] { 1, 2, 3 }; var model = new PlotLineWorkspaceViewModel { Project = new Project { ProjectID = 7 }, PlotLines = data.PlotLines.Where(l => ids.Contains(l.PlotLineID)).Select(l => new PlotLineWorkspaceLineViewModel { Line = l, IsSelected = true, Threads = data.Threads.Where(t => t.PlotLineID == l.PlotLineID).ToList() }).ToList(), SelectedPlotLineIDs = ids, Mode = ids.Length == 1 ? "Focus" : "Weave", Scenes = PlotLineWorkspaceComposer.Compose(data, ids), MapTargets = data.Targets, AssociationScenes = data.AttributionScenes, Health = new PlotHealthEvaluator().Evaluate(new(7, null, null, ids, data, data)) }; var action = new ActionContext(context, new RouteData(), new ActionDescriptor()); var view = context.RequestServices.GetRequiredService().GetView(null, context.Request.Query["healthDetail"] == "true" ? "/Views/PlotLineWorkspace/_Health.cshtml" : "/Views/PlotLineWorkspace/_NarrativeMap.cshtml", false); if (!view.Success || view.View is null) throw new InvalidOperationException($"Fixture view could not be resolved: {string.Join(", ", view.SearchedLocations)}"); using var writer = new StringWriter(); var viewData = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary()) { Model = model }; await view.View.RenderAsync(new ViewContext(action, view.View, viewData, new TempDataDictionary(context, context.RequestServices.GetRequiredService()), writer, new HtmlHelperOptions())); context.Response.ContentType = "text/html; charset=utf-8"; if (context.Request.Query["healthDetail"] == "true" && context.Request.Query["marketing"] != "true") { await context.Response.WriteAsync(writer.ToString()); return; } await context.Response.WriteAsync("
" + writer + ""); }); // Public QA renders the real views/layout with isolated models; no account, payment or DB calls. app.MapGet("/public-fixture/{page}", async context => { var page = context.Request.RouteValues["page"]?.ToString() ?? "home"; var (controller, viewName, viewModel) = page switch { "home" => ("Home", "Index", (object?)null), "tour" => ("Public", "Features", (object?)null), "login" => ("Account", "Login", (object?)new LoginViewModel { ReturnUrl = "/Projects" }), "register" => ("Account", "Register", (object?)new RegisterViewModel()), "pricing" => ("Pricing", "Index", (object?)new PricingViewModel { Plans = Enumerable.Range(0, 4).Select(i => new SubscriptionLevel { SubscriptionLevelID = i + 1, DisplayName = new[] { "Draft Desk", "Writing Room", "Story Forge", "Author Studio" }[i], RequiresStripeSubscription = i > 0, MonthlyPricePence = i == 0 ? null : i * 500, AnnualPricePence = i == 0 ? null : i * 5000, MaxBooks = i + 1, MaxChaptersPerBook = (i + 1) * 50, MaxCharactersPerProject = (i + 1) * 50, MaxScenesPerBook = (i + 1) * 100, MaxStorageMB = (i + 1) * 250, MaxCollaborators = i }).ToList() }), _ => throw new InvalidOperationException("Unknown public fixture") }; if (context.Request.Query["anonymous"] == "true") context.User = new ClaimsPrincipal(new ClaimsIdentity()); if (context.Request.Query.TryGetValue("theme", out var theme) && ApplicationAppearance.IsValid(theme.ToString())) await context.RequestServices.GetRequiredService().SaveThemeAsync(4, theme.ToString()); var route = new RouteData(); route.Values["controller"] = controller; route.Values["action"] = viewName; var action = new ActionContext(context, route, new ActionDescriptor()); var view = context.RequestServices.GetRequiredService().GetView(null, $"/Views/{controller}/{viewName}.cshtml", true); if (!view.Success) throw new InvalidOperationException(string.Join(",", view.SearchedLocations)); using var writer = new StringWriter(); var data = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary()) { Model = viewModel }; await view.View.RenderAsync(new ViewContext(action, view.View, data, new TempDataDictionary(context, context.RequestServices.GetRequiredService()), writer, new HtmlHelperOptions())); context.Response.ContentType = "text/html; charset=utf-8"; await context.Response.WriteAsync(writer.ToString()); }); app.MapGet("/Writing/Context", context => RenderFullAsync(context, "Writing", "Context", new WritingContextPageViewModel { ProjectID = 7, BookID = int.TryParse(context.Request.Query["bookId"].ToString(), out var bookId) ? bookId : 12 })).WithOrder(-1); app.MapGet("/Writing/Intent", context => RenderFullAsync(context, "Writing", "Intent", new WritingIntentPageViewModel { ProjectID = 7, BookID = int.TryParse(context.Request.Query["bookId"].ToString(), out var bookId) ? bookId : 12 })).WithOrder(-1); app.MapGet("/fixture", async context => { if (context.Request.Query["page"] == "writer" && context.Request.Query["layout"] == "full") { await RenderFullAsync(context, "Writer", "Index", WriterFixture()); return; } var model = new ApplicationNavigationViewModel { ActiveSection = "Calendar", ShowCompanionPresence = true }; if (context.Request.Query["project"] != "none") { model.Project = new Project { ProjectID = 7, ProjectName = "The Glass Harbour", AccessRole = context.Request.Query["owner"] == "false" ? "Editor" : "Owner" }; model.Book = new Book { BookID = 12, ProjectID = 7, BookTitle = "A Distant Shore", BookNumber = 1 }; model.Books = [model.Book, new Book { BookID = 13, ProjectID = 7, BookTitle = "The Return", BookNumber = 2 }]; } string? recordLayout = null; var writerScripts = ""; var dashboardPage = context.Request.Query["page"] == "dashboard"; var timelinePage = context.Request.Query["page"] == "timeline"; if (dashboardPage) model.ActiveSection = "Overview"; if (timelinePage) model.ActiveSection = "Timeline"; var appearance = await context.RequestServices.GetRequiredService().GetAsync(int.Parse(context.User.FindFirstValue(ClaimTypes.NameIdentifier)!)); var route = new RouteData(); route.Values["controller"] = context.Request.Query["page"] == "relationships" ? "RelationshipMap" : dashboardPage ? "Projects" : "StoryCalendar"; route.Values["action"] = dashboardPage ? "Details" : "Index"; var action = new ActionContext(context, route, new ActionDescriptor()); async Task Render(string name, object? viewModel = null) { var view = context.RequestServices.GetRequiredService().GetView(null, $"/Views/{name}.cshtml", false); if (!view.Success) throw new Exception(string.Join(",", view.SearchedLocations)); using var writer = new StringWriter(); var data = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary()) { Model = viewModel ?? model }; data["ApplicationAppearance"] = appearance; var temp = new TempDataDictionary(context, context.RequestServices.GetRequiredService()); await view.View.RenderAsync(new ViewContext(action, view.View, data, temp, writer, new HtmlHelperOptions())); if (name == "FloorPlans/Edit" && view.View is Microsoft.AspNetCore.Mvc.Razor.RazorView razorView && razorView.RazorPage.SectionWriters.TryGetValue("Scripts", out var scripts)) { writer.Write(""); razorView.RazorPage.ViewContext.Writer = writer; await scripts(); } if (name == "Writer/Index" && view.View is Microsoft.AspNetCore.Mvc.Razor.RazorView writerView && writerView.RazorPage.SectionWriters.TryGetValue("Scripts", out var writerSection)) { using var scriptWriter = new StringWriter(); writerView.RazorPage.ViewContext.Writer = scriptWriter; await writerSection(); writerScripts = scriptWriter.ToString(); } return writer.ToString(); } if (context.Request.Query["page"] == "scene-edit" && context.Request.Query.TryGetValue("editor", out var requestedEditor)) { var editors = new Dictionary { ["purpose"] = "Purpose", ["relationships"] = "Relationships", ["characters"] = "Characters", ["metrics"] = "Metrics", ["threads"] = "Threads", ["dependencies"] = "Dependencies", ["locations"] = "Locations", ["assets"] = "Assets", ["notes"] = "Notes", ["checklist"] = "Checklist", ["workflow"] = "Workflow", ["attachments"] = "Attachments", ["warnings"] = "Continuity", ["scene-details"] = "Details", ["knowledge"] = "Knowledge", ["attributes"] = "CharacterAttributes", ["suggestions"] = "Suggestions" }; if (!editors.TryGetValue(requestedEditor.ToString(), out var editorName)) { context.Response.StatusCode = 404; return; } context.Response.ContentType = "text/html"; await context.Response.WriteAsync(await Render($"Shared/SceneInspectorV2/_Scene{editorName}Editor", editorName == "Continuity" ? SceneContinuityFixture() : SceneWorkspaceFixture())); return; } if (context.Request.Query["page"] == "scene-edit") { var scene = SceneWorkspaceFixture(); model.Project = scene.Project; model.Book = scene.Book; model.Books = scene.Book is null ? [] : [scene.Book]; } if (context.Request.Query["page"] == "maps") { model.ActiveSection = "Maps"; route.Values["controller"] = "Maps"; } if (context.Request.Query["page"] == "writer") { model.ActiveSection = "Writer"; route.Values["controller"] = "Writer"; } var menu = await Render("Shared/_ApplicationShell"); var toolbar = ""; var calendar = new StoryCalendarViewModel { Project = model.Project ?? new(), SelectedBookID = model.Book?.BookID, SelectedMonth = new DateOnly(2026, 10, 1), EarliestStoryDate = new DateOnly(2026, 10, 3), LatestStoryDate = new DateOnly(2026, 10, 3), BookOptions = [new SelectListItem("A Distant Shore", "12"), new SelectListItem("The Return", "13")], MonthOptions = [new SelectListItem("October 2026", "2026-10")], DatedScenes = [new StoryCalendarSceneViewModel { Title = "Arrival", StoryDate = new DateOnly(2026, 10, 3) }], Weeks = Enumerable.Range(0, 5).Select(week => new StoryCalendarWeekViewModel { Days = Enumerable.Range(0, 7).Select(day => new StoryCalendarDayViewModel { Date = new DateOnly(2026, 9, 28).AddDays(week * 7 + day), IsInSelectedMonth = week * 7 + day >= 3 }).ToList() }).ToList() }; if (context.Request.Query["page"] == "calendar-test") calendar = (await context.RequestServices.GetRequiredService().GetAsync(7, null, null, null))!; if (context.Request.Query["marketing"] == "true") { calendar.DatedScenes = PublicWebsiteFixtures.CalendarScenes(); foreach (var day in calendar.Weeks.SelectMany(w => w.Days)) day.Scenes = calendar.DatedScenes.Where(scene => scene.StoryDate == day.Date).ToList(); calendar.EarliestStoryDate = new DateOnly(2026, 10, 3); calendar.LatestStoryDate = new DateOnly(2026, 10, 24); } var surface = dashboardPage || context.Request.Query["page"] == "writer" || context.Request.Query["page"] == "relationships" || context.Request.Query["page"] == "maps" ? "" : await Render("StoryCalendar/_StoryCalendarSurface", calendar); if (context.Request.Query["page"] == "calendar-test") surface = "
" + surface + "
"; if (timelinePage) { surface = """
Filters
View
Jump
Saved views
Drag sourcesMara Vale
Scene timeline
The Glass Harbour
A Distant ShoreBook one
Story asset lanes
Brass keyObject / 8
Select a single metric to edit its curve.
"""; } if (context.Request.Query["page"] == "timeline-render") { var scenes = new List { new() { SceneID = 101, ChapterID = 21, SceneNumber = 1, SceneTitle = "Arrival", Summary = "The crossing begins." }, new() { SceneID = 102, ChapterID = 21, SceneNumber = 2, SceneTitle = "Departure", Summary = "The crossing ends." } }; var scenario = context.Request.Query["scenario"] == "true"; if (scenario) scenes.Reverse(); surface = await Render("Timeline/Index", new TimelineViewModel { Project = model.Project!, SelectedBookID = 12, Settings = new ProjectTimelineSettings { ShowPlotLines = true, ShowSceneCards = true, ShowMetricShape = false, ShowStoryAssets = false }, Filter = new TimelineFilterViewModel { ProjectID = 7, PlotLineID = 1, FocusType = "plotline", FocusID = 1 }, Books = [new() { Book = model.Book!, Chapters = [new() { Chapter = new Chapter { ChapterID = 21, ChapterNumber = 1, ChapterTitle = "The crossing" }, Scenes = scenes }] }], OrderedScenes = scenes, MatchingSceneIDs = new HashSet { 101 }, FocusSceneIDs = new HashSet { 101 }, FocusLabel = "Harbour mystery", ScenePlotSearchText = new Dictionary { [101] = "Harbour mystery First clues Revelation" }, PlotLineOptions = [new SelectListItem("Harbour mystery", "1", true)], PlotThreadOptions = [new SelectListItem("First clues", "11")] }); surface += await Render("Timeline/Settings", new TimelineSettingsViewModel { ProjectID = 7, ProjectName = "The Glass Harbour" }); } if (dashboardPage) { surface = await Render("Projects/Details", new ProjectDetailViewModel { Project = model.Project ?? new(), Summary = new() { TotalBooks = 2, DraftingBooks = 1, PlanningBooks = 1, TotalWords = 68420, CharacterCount = 18, LocationCount = 12, ActivePlotThreadCount = 7, ContinuityWarningCount = 3 }, SeriesProgress = new() { Percentage = 42, SupportingLine = "68,420 of 160,000 planned words", CalculationLabel = "Word count" }, Books = [new() { BookID = 12, BookNumber = 1, BookTitle = "A Distant Shore", Subtitle = "The Glass Harbour · Book One", Status = "Drafting", CurrentWordCount = 68420, TargetWordCount = 80000, ProgressPercentage = 85.5m, ChapterCount = 24, SceneCount = 72, UpdatedDate = new DateTime(2026,10,28) }], RecentActivity = [new() { ActivityType = "Updated", EntityType = "Scene", EntityName = "An unexpected arrival", Description = "Chapter 12 · A change of direction", TimeLabel = "Today", UserLabel = "Fixture Author", IconLabel = "Scene" }], NeedsAttention = new() { Warnings = [new() { SeverityName = "Review", WarningTypeName = "Chronology", Message = "Check the order of events at the harbour.", LocationLabel = "Book 1 · Chapter 12" }] } }); } if (context.Request.Query["page"] == "projects") { route.Values["controller"] = "Projects"; route.Values["action"] = "Index"; surface = await Render("Projects/Index", new ProjectIndexViewModel { ActiveProjects = [ new() { ProjectID = 7, ProjectName = "With cover", CoverThumbnailPaths = ["/images/placeholders/book-cover.svg"] }, new() { ProjectID = 8, ProjectName = "Without cover" } ] }); } var desktopPage = context.Request.Query["desktop"].ToString(); if (!string.IsNullOrEmpty(desktopPage)) { var project = model.Project ?? new Project { ProjectID = 7, ProjectName = "Fixture project" }; if (context.Request.Query["owner"] == "false") project.AccessRole = "Editor"; object pageModel = desktopPage switch { "ManuscriptImport" => new OnboardingWizardViewModel { CurrentStep = OnboardingSteps.NextPathPreview, WritingSoftware = WritingSoftwareValues.MicrosoftWord, SelectedProjectName = "The Glass Harbour", SelectedBookTitle = "A Distant Shore", ProjectID = 7, BookID = 12 }, "StoryBible" => new StoryBibleViewModel { Project = project, Query = context.Request.Query["q"] }, "Books" => new BookDetailViewModel { Project = project, Book = model.Book!, Chapters = [ new() { ChapterID = 21, ChapterNumber = 1, ChapterTitle = "Drowning in Silence", RevisionStatusName = "Planned", IsLinkedToManuscript = true, Summary = "A quiet opening." }, new() { ChapterID = 22, ChapterNumber = 2, ChapterTitle = "A deliberately long chapter title about an unexpected journey beyond the distant northern mountains", RevisionStatusName = "Draft", ChapterPurposeName = "Turning point", Summary = "A longer summary remains available on small screens.", IsLinkedToManuscript = false } ] }, "Characters" => new CharacterListViewModel { Project = project, Characters = context.Request.Query["context"] == "objects" ? [new Character { CharacterID = 71, CharacterName = "Context A" }, new Character { CharacterID = 72, CharacterName = "Context B" }] : [] }, "Locations" => new LocationListViewModel { Project = project }, "FloorPlans" => new FloorPlanListViewModel { Project = project }, "PlotLineWorkspace" => new PlotLineWorkspaceViewModel { Project = project }, "Warnings" => new WarningDashboardViewModel { Project = project }, "Archives" => new ArchivedItemsViewModel { ProjectID = project.ProjectID, Items = context.Request.Query["context"] == "objects" ? [new ArchivedItem { EntityType = "Character", EntityID = 71, DisplayName = "Archived context fixture", UpdatedDate = DateTime.UtcNow }] : [] }, "PlotThreads" => new PlotThreadListViewModel { Project = project }, "StoryCalendar" => calendar, "StoryPoint" => new StoryPointViewModel { Project = project }, "ProjectMetrics" => new ProjectSceneMetricsViewModel { Project = project }, "Analytics" => new AnalyticsViewModel { Project = project }, "Dynamics" => new StoryDynamicsViewModel { Project = project }, "ReviewCentre" => new StoryIntelligenceProgressViewModel { ProjectID = 7, BookID = 12 }, "ProjectEdit" => new ProjectEditViewModel { ProjectID = 7, ProjectName = project.ProjectName }, "WritingPlans" => new WritingPlansManagementViewModel(), "SchedulePreview" => new WritingSchedulePreviewViewModel(), _ => throw new InvalidOperationException("Unknown desktop fixture") }; var viewController = desktopPage switch { "ManuscriptImport" or "ReviewCentre" => "Onboarding", "ProjectEdit" => "Projects", "WritingPlans" or "SchedulePreview" => "Writer", _ => desktopPage }; var viewAction = desktopPage switch { "ManuscriptImport" => "Index", "ReviewCentre" => "StoryIntelligenceReviewCentre", "ProjectEdit" => "Edit", "WritingPlans" or "SchedulePreview" => desktopPage, "Dynamics" => "Story", "Books" => "Details", _ => "Index" }; route.Values["controller"] = viewController; route.Values["action"] = viewAction; model.ActiveSection = desktopPage switch { "StoryBible" => "Story Bible", "PlotLineWorkspace" => "Plot Lines", "PlotThreads" => "Threads", "StoryCalendar" => "Calendar", "StoryPoint" => "At This Point", "ProjectMetrics" => "Metrics", "Analytics" or "Dynamics" => "Health", _ => desktopPage }; surface = await Render($"{viewController}/{viewAction}", pageModel); menu = await Render("Shared/_ApplicationShell"); } var record = context.Request.Query["record"].ToString(); if (!string.IsNullOrEmpty(record)) { recordLayout = record is "Projects" or "ProjectMetrics" ? "compact" : "wide"; var project = model.Project!; object recordModel = record switch { "Projects" => new ProjectEditViewModel { ProjectID = 7, ProjectName = project.ProjectName }, "Books" => new BookEditViewModel { BookID = 12, BookNumber = 1, ProjectID = 7, BookTitle = model.Book!.BookTitle, StatusOptions = [new SelectListItem("Planning", "Planning", true)], Project = project }, "Chapters" => new ChapterEditViewModel { ChapterID = 21, BookID = 12, ChapterTitle = "The crossing", Book = model.Book }, "Characters" => new CharacterEditViewModel { CharacterID = 71, ProjectID = 7, CharacterName = "Mara Vale", Project = project }, "Locations" => new LocationEditViewModel { LocationID = 81, ProjectID = 7, LocationName = "The harbour", Project = project }, "StoryAssets" => new StoryAssetEditViewModel { StoryAssetID = 91, ProjectID = 7, AssetName = "The letter", Project = project }, "PlotLines" => new PlotLineEditViewModel { PlotLineID = 1, ProjectID = 7, PlotLineName = "The missing letter", Project = project }, "PlotThreads" => new PlotThreadEditViewModel { PlotThreadID = 2, ProjectID = 7, ThreadTitle = "Arrival", Project = project }, "ProjectMetrics" => new SceneMetricTypeEditViewModel { ProjectID = 7 }, _ => throw new InvalidOperationException("Unknown record fixture") }; route.Values["controller"] = record; route.Values["action"] = "Edit"; surface = await Render($"{record}/Edit", recordModel); surface += ""; menu = await Render("Shared/_ApplicationShell"); } if (context.Request.Query["page"] == "scene-edit") { surface = await Render("Scenes/Edit", SceneWorkspaceFixture()); // The fixture renders a partial page; include its normal Scripts section explicitly. surface += ""; } if (context.Request.Query["page"] == "relationships") { var relationships = await RelationshipWorkspaceTests.Fixture(); surface = await Render("RelationshipMap/Index", relationships); surface += await Render("RelationshipMap/_GraphScripts", relationships); } if (context.Request.Query["page"] == "maps") { var map = new StoryMap { MapID = 1, ProjectID = 7, Name = "Working geography", Kind = "Region" }; surface = await Render("Maps/Index", context.Request.Query["story"] == "true" ? MapStoryTests.Workspace() : new MapsViewModel { Project = model.Project!, Maps = [map], Document = new MapDocument { Map = map }, Locations = [new LocationItem { LocationID = 11, ProjectID = 7, LocationName = "Harbour town" }, new LocationItem { LocationID = 12, ProjectID = 7, LocationName = "Hill village" }] }); surface += ""; } if (context.Request.Query["page"] == "floorplans") { route.Values["controller"] = "FloorPlans"; route.Values["action"] = "Edit"; model.ActiveSection = "Floor Plans"; surface = await Render("FloorPlans/Edit", new FloorPlanEditorViewModel { Project = model.Project!, FloorPlan = new() { ProjectID = 7, FloorPlanID = 31, Name = "Fixture building" }, Floors = [new() { FloorPlanFloorID = 41, FloorPlanID = 31, Name = "Ground floor" }], Blocks = [new() { FloorPlanBlockID = 51, FloorPlanFloorID = 41, LocationName = "Study", X = 2, Y = 2, WidthCells = 3, HeightCells = 2 }] }); } if (context.Request.Query["page"] == "writer") surface = await Render("Writer/Index", WriterFixture()); surface += await Render("Shared/_ConfirmationDialog"); var initialTheme = appearance.ThemeKey ?? "warm-light"; var appearanceScript = ""; using var contributionWriter = new StringWriter(); PlotLine.TagHelpers.RibbonContributionTagHelper.Snapshot(context).WriteTo(contributionWriter, System.Text.Encodings.Web.HtmlEncoder.Default); var contributions = contributionWriter.ToString(); context.Response.ContentType = "text/html; charset=utf-8"; await context.Response.WriteAsync("
" + menu + toolbar + "
" + surface + "
" + appearanceScript + "" + writerScripts + ""); }); app.MapHub("/hubs/word-companion-follow"); await app.RunAsync(); } } internal sealed class WritingSolverFixtureRepository(IHttpContextAccessor accessor) : IWritingSolverRepository { private readonly Lazy candidateSnapshot = new(() => { var path=Environment.GetEnvironmentVariable("PD_WRITING_SOLVER_CANDIDATE"); if(string.IsNullOrEmpty(path)) return null; var graph=WritingSolverRepository.Parse(File.ReadAllText(path)); foreach(var page in graph.Solutions.Cast().Concat(graph.Features)) page.Index=Environment.GetEnvironmentVariable("PD_SOLVER_TEST_INDEXING")=="true"; return System.Text.Json.JsonSerializer.Serialize(graph,WritingSolverRepository.JsonOptions); }); public Task GetAsync() { var snapshot=candidateSnapshot.Value; var graph=snapshot is null ? WritingSolverRepository.Parse(File.ReadAllText("PlotLine/Content/WritingSolver/demo.json")) : System.Text.Json.JsonSerializer.Deserialize(snapshot,WritingSolverRepository.JsonOptions)!; if (snapshot is null && accessor.HttpContext?.Request.Query["curated"].ToString() == "true") { graph.IsDemo = false; foreach(var page in graph.Solutions.Cast().Concat(graph.Features)) page.Index = true; } return Task.FromResult(graph); } public Task PublishAsync(string json,string editor) => throw new NotSupportedException("Read-only fixture"); } internal sealed class SolverWorkspaceFixture : IWritingSolverWorkspaceContext { public Task> ProjectsAsync()=>Task.FromResult>([new(){ProjectID=77,ProjectName="Fixture novel"}]); public Task> CharactersAsync(int projectId)=>Task.FromResult>([new(){CharacterID=88,ProjectID=77,CharacterName="Fixture character"}]); }