Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/calm-files-cache.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@moonshot-ai/kimi-code": patch
---

Cache web assets between page loads while revalidating the application shell.
8 changes: 8 additions & 0 deletions packages/kap-server/src/routes/webAssets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,18 @@ async function serveWebAsset(

return reply
.type(mimeType(filePath))
.header('Cache-Control', cacheControl(assetsDir, filePath))
.header('Content-Length', String(fileInfo.size))
.send(createReadStream(filePath));
}

function cacheControl(assetsDir: string, filePath: string): string {
const assetsRoot = resolve(assetsDir, 'assets');
return filePath.startsWith(`${assetsRoot}${sep}`)
? 'public, max-age=31536000, immutable'
: 'no-cache';
}

async function resolveStaticFile(
assetsDir: string,
pathname: string,
Expand Down
52 changes: 52 additions & 0 deletions packages/kap-server/test/webAssets.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';

import Fastify, { type FastifyInstance } from 'fastify';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';

import { registerWebAssetRoutes } from '../src/routes/webAssets';

describe('web asset cache policy', () => {
let app: FastifyInstance;
let assetsDir: string;

beforeEach(async () => {
assetsDir = await mkdtemp(join(tmpdir(), 'kimi-web-assets-'));
await mkdir(join(assetsDir, 'assets'));
await writeFile(join(assetsDir, 'index.html'), '<main>Kimi</main>');
await writeFile(join(assetsDir, 'assets', 'index-Dy7xs5tu.js'), 'export {};');

app = Fastify();
await registerWebAssetRoutes(app, assetsDir);
await app.ready();
});

afterEach(async () => {
await app.close();
await rm(assetsDir, { recursive: true, force: true });
});

it('caches fingerprinted Vite assets as immutable', async () => {
const response = await app.inject({
method: 'GET',
url: '/assets/index-Dy7xs5tu.js',
});

expect(response.statusCode).toBe(200);
expect(response.headers['cache-control']).toBe(
'public, max-age=31536000, immutable',
);
});

it.each(['/', '/index.html', '/sessions/current', '/assets/preview'])(
'revalidates HTML responses for %s',
async (url) => {
const response = await app.inject({ method: 'GET', url });

expect(response.statusCode).toBe(200);
expect(response.headers['cache-control']).toBe('no-cache');
expect(response.headers['content-type']).toBe('text/html; charset=utf-8');
},
);
});